aboutsummaryrefslogtreecommitdiff
path: root/src/client
diff options
context:
space:
mode:
Diffstat (limited to 'src/client')
-rw-r--r--src/client/camera.cpp336
-rw-r--r--src/client/camera.h94
-rw-r--r--src/client/client.cpp792
-rw-r--r--src/client/client.h277
-rw-r--r--src/client/clientenvironment.cpp198
-rw-r--r--src/client/clientenvironment.h39
-rw-r--r--src/client/clientlauncher.cpp131
-rw-r--r--src/client/clientlauncher.h2
-rw-r--r--src/client/clientmap.cpp240
-rw-r--r--src/client/clientmap.h50
-rw-r--r--src/client/clientmedia.cpp193
-rw-r--r--src/client/clientmedia.h43
-rw-r--r--src/client/clientobject.cpp17
-rw-r--r--src/client/clientobject.h30
-rw-r--r--src/client/clouds.cpp375
-rw-r--r--src/client/clouds.h42
-rw-r--r--src/client/content_cao.cpp798
-rw-r--r--src/client/content_cao.h97
-rw-r--r--src/client/content_cso.cpp36
-rw-r--r--src/client/content_cso.h4
-rw-r--r--src/client/content_mapblock.cpp975
-rw-r--r--src/client/content_mapblock.h61
-rw-r--r--src/client/filecache.cpp27
-rw-r--r--src/client/fontengine.cpp152
-rw-r--r--src/client/fontengine.h54
-rw-r--r--src/client/game.cpp1398
-rw-r--r--src/client/game.h318
-rw-r--r--src/client/gameui.cpp156
-rw-r--r--src/client/gameui.h5
-rw-r--r--src/client/guiscalingfilter.cpp68
-rw-r--r--src/client/guiscalingfilter.h11
-rw-r--r--src/client/hud.cpp644
-rw-r--r--src/client/hud.h32
-rw-r--r--src/client/imagefilters.cpp207
-rw-r--r--src/client/imagefilters.h3
-rw-r--r--src/client/inputhandler.h22
-rw-r--r--src/client/joystick_controller.cpp96
-rw-r--r--src/client/joystick_controller.h62
-rw-r--r--src/client/keycode.cpp377
-rw-r--r--src/client/keys.h2
-rw-r--r--src/client/localplayer.cpp255
-rw-r--r--src/client/localplayer.h40
-rw-r--r--src/client/mapblock_mesh.cpp659
-rw-r--r--src/client/mapblock_mesh.h47
-rw-r--r--src/client/mesh.cpp934
-rw-r--r--src/client/mesh.h29
-rw-r--r--src/client/mesh_generator_thread.cpp113
-rw-r--r--src/client/minimap.cpp353
-rw-r--r--src/client/minimap.h34
-rw-r--r--src/client/particles.cpp287
-rw-r--r--src/client/particles.h82
-rw-r--r--src/client/render/core.cpp37
-rw-r--r--src/client/render/interlaced.cpp4
-rw-r--r--src/client/render/plain.cpp4
-rw-r--r--src/client/render/sidebyside.cpp7
-rw-r--r--src/client/render/stereo.cpp4
-rw-r--r--src/client/renderingengine.cpp67
-rw-r--r--src/client/renderingengine.h6
-rw-r--r--src/client/shader.cpp381
-rw-r--r--src/client/shader.h107
-rw-r--r--src/client/sky.cpp551
-rw-r--r--src/client/sky.h55
-rw-r--r--src/client/sound_openal.cpp229
-rw-r--r--src/client/tile.cpp1012
-rw-r--r--src/client/tile.h96
-rw-r--r--src/client/wieldmesh.cpp365
66 files changed, 7041 insertions, 7181 deletions
diff --git a/src/client/camera.cpp b/src/client/camera.cpp
index 9d74447d5..c9e8fab6a 100644
--- a/src/client/camera.cpp
+++ b/src/client/camera.cpp
@@ -22,13 +22,13 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client.h"
#include "config.h"
#include "map.h"
-#include "clientmap.h" // MapDrawControl
+#include "clientmap.h" // MapDrawControl
#include "player.h"
#include <cmath>
#include "client/renderingengine.h"
#include "settings.h"
#include "wieldmesh.h"
-#include "noise.h" // easeCurve
+#include "noise.h" // easeCurve
#include "sound.h"
#include "event.h"
#include "nodedef.h"
@@ -43,8 +43,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define WIELDMESH_AMPLITUDE_X 7.0f
#define WIELDMESH_AMPLITUDE_Y 10.0f
-Camera::Camera(MapDrawControl &draw_control, Client *client) :
- m_draw_control(draw_control), m_client(client)
+Camera::Camera(MapDrawControl &draw_control, Client *client):
+ m_draw_control(draw_control),
+ m_client(client)
{
scene::ISceneManager *smgr = RenderingEngine::get_scene_manager();
// note: making the camera node a child of the player node
@@ -75,8 +76,8 @@ Camera::Camera(MapDrawControl &draw_control, Client *client) :
m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount");
// 45 degrees is the lowest FOV that doesn't cause the server to treat this
// as a zoom FOV and load world beyond the set server limits.
- m_cache_fov = std::fmax(g_settings->getFloat("fov"), 45.0f);
- m_arm_inertia = g_settings->getBool("arm_inertia");
+ m_cache_fov = std::fmax(g_settings->getFloat("fov"), 45.0f);
+ m_arm_inertia = g_settings->getBool("arm_inertia");
m_nametags.clear();
}
@@ -102,8 +103,7 @@ void Camera::notifyFovChange()
if (m_fov_transition_active)
m_old_fov_degrees = m_curr_fov_degrees;
else
- m_old_fov_degrees =
- m_server_sent_fov ? m_target_fov_degrees : m_cache_fov;
+ m_old_fov_degrees = m_server_sent_fov ? m_target_fov_degrees : m_cache_fov;
/*
* Update m_server_sent_fov next - it corresponds to the target FOV of the
@@ -118,8 +118,7 @@ void Camera::notifyFovChange()
m_target_fov_degrees = m_cache_fov;
} else {
m_server_sent_fov = true;
- m_target_fov_degrees =
- spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov;
+ m_target_fov_degrees = spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov;
}
if (spec.transition_time > 0.0f)
@@ -163,9 +162,10 @@ inline f32 my_modf(f32 x)
void Camera::step(f32 dtime)
{
- if (m_view_bobbing_fall > 0) {
+ if(m_view_bobbing_fall > 0)
+ {
m_view_bobbing_fall -= 3 * dtime;
- if (m_view_bobbing_fall <= 0)
+ if(m_view_bobbing_fall <= 0)
m_view_bobbing_fall = -1; // Mark the effect as finished
}
@@ -175,8 +175,9 @@ void Camera::step(f32 dtime)
if (m_wield_change_timer >= 0 && was_under_zero)
m_wieldnode->setItem(m_wield_item_next, m_client);
- if (m_view_bobbing_state != 0) {
- // f32 offset = dtime * m_view_bobbing_speed * 0.035;
+ if (m_view_bobbing_state != 0)
+ {
+ //f32 offset = dtime * m_view_bobbing_speed * 0.035;
f32 offset = dtime * m_view_bobbing_speed * 0.030;
if (m_view_bobbing_state == 2) {
// Animation is getting turned off
@@ -201,15 +202,15 @@ void Camera::step(f32 dtime)
m_view_bobbing_anim = 0;
m_view_bobbing_state = 0;
}
- } else {
+ }
+ else {
float was = m_view_bobbing_anim;
m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
bool step = (was == 0 ||
(was < 0.5f && m_view_bobbing_anim >= 0.5f) ||
(was > 0.5f && m_view_bobbing_anim <= 0.5f));
- if (step) {
- m_client->getEventManager()->put(new SimpleTriggerEvent(
- MtEvent::VIEW_BOBBING_STEP));
+ if(step) {
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::VIEW_BOBBING_STEP));
}
}
}
@@ -218,18 +219,18 @@ void Camera::step(f32 dtime)
f32 offset = dtime * 3.5f;
float m_digging_anim_was = m_digging_anim;
m_digging_anim += offset;
- if (m_digging_anim >= 1) {
+ if (m_digging_anim >= 1)
+ {
m_digging_anim = 0;
m_digging_button = -1;
}
float lim = 0.15;
- if (m_digging_anim_was < lim && m_digging_anim >= lim) {
+ if(m_digging_anim_was < lim && m_digging_anim >= lim)
+ {
if (m_digging_button == 0) {
- m_client->getEventManager()->put(new SimpleTriggerEvent(
- MtEvent::CAMERA_PUNCH_LEFT));
- } else if (m_digging_button == 1) {
- m_client->getEventManager()->put(new SimpleTriggerEvent(
- MtEvent::CAMERA_PUNCH_RIGHT));
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_LEFT));
+ } else if(m_digging_button == 1) {
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_RIGHT));
}
}
}
@@ -258,9 +259,8 @@ static inline v2f dir(const v2f &pos_dist)
void Camera::addArmInertia(f32 player_yaw)
{
- m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw, -100.0f, 100.0f) /
- 0.016f) *
- 0.01f;
+ m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw,
+ -100.0f, 100.0f) / 0.016f) * 0.01f;
m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / 0.016f);
f32 gap_X = std::fabs(WIELDMESH_OFFSET_X - m_wieldmesh_offset.X);
f32 gap_Y = std::fabs(WIELDMESH_OFFSET_Y - m_wieldmesh_offset.Y);
@@ -276,17 +276,14 @@ void Camera::addArmInertia(f32 player_yaw)
m_cam_vel_old.X = m_cam_vel.X;
f32 acc_X = 0.12f * (m_cam_vel.X - (gap_X * 0.1f));
- m_wieldmesh_offset.X +=
- m_last_cam_pos.X < player_yaw ? acc_X : -acc_X;
+ m_wieldmesh_offset.X += m_last_cam_pos.X < player_yaw ? acc_X : -acc_X;
if (m_last_cam_pos.X != player_yaw)
m_last_cam_pos.X = player_yaw;
m_wieldmesh_offset.X = rangelim(m_wieldmesh_offset.X,
- WIELDMESH_OFFSET_X -
- (WIELDMESH_AMPLITUDE_X * 0.5f),
- WIELDMESH_OFFSET_X +
- (WIELDMESH_AMPLITUDE_X * 0.5f));
+ WIELDMESH_OFFSET_X - (WIELDMESH_AMPLITUDE_X * 0.5f),
+ WIELDMESH_OFFSET_X + (WIELDMESH_AMPLITUDE_X * 0.5f));
}
if (m_cam_vel.Y > 1.0f) {
@@ -294,18 +291,15 @@ void Camera::addArmInertia(f32 player_yaw)
m_cam_vel_old.Y = m_cam_vel.Y;
f32 acc_Y = 0.12f * (m_cam_vel.Y - (gap_Y * 0.1f));
- m_wieldmesh_offset.Y += m_last_cam_pos.Y > m_camera_direction.Y
- ? acc_Y
- : -acc_Y;
+ m_wieldmesh_offset.Y +=
+ m_last_cam_pos.Y > m_camera_direction.Y ? acc_Y : -acc_Y;
if (m_last_cam_pos.Y != m_camera_direction.Y)
m_last_cam_pos.Y = m_camera_direction.Y;
m_wieldmesh_offset.Y = rangelim(m_wieldmesh_offset.Y,
- WIELDMESH_OFFSET_Y -
- (WIELDMESH_AMPLITUDE_Y * 0.5f),
- WIELDMESH_OFFSET_Y +
- (WIELDMESH_AMPLITUDE_Y * 0.5f));
+ WIELDMESH_OFFSET_Y - (WIELDMESH_AMPLITUDE_Y * 0.5f),
+ WIELDMESH_OFFSET_Y + (WIELDMESH_AMPLITUDE_Y * 0.5f));
}
m_arm_dir = dir(m_wieldmesh_offset);
@@ -315,34 +309,27 @@ void Camera::addArmInertia(f32 player_yaw)
following a vector, with a smooth deceleration factor.
*/
- f32 dec_X = 0.35f *
- (std::min(15.0f, m_cam_vel_old.X) *
- (1.0f + (1.0f - m_arm_dir.X))) *
- (gap_X / 20.0f);
+ f32 dec_X = 0.35f * (std::min(15.0f, m_cam_vel_old.X) * (1.0f +
+ (1.0f - m_arm_dir.X))) * (gap_X / 20.0f);
- f32 dec_Y = 0.25f *
- (std::min(15.0f, m_cam_vel_old.Y) *
- (1.0f + (1.0f - m_arm_dir.Y))) *
- (gap_Y / 15.0f);
+ f32 dec_Y = 0.25f * (std::min(15.0f, m_cam_vel_old.Y) * (1.0f +
+ (1.0f - m_arm_dir.Y))) * (gap_Y / 15.0f);
if (gap_X < 0.1f)
m_cam_vel_old.X = 0.0f;
- m_wieldmesh_offset.X -= m_wieldmesh_offset.X > WIELDMESH_OFFSET_X
- ? dec_X
- : -dec_X;
+ m_wieldmesh_offset.X -=
+ m_wieldmesh_offset.X > WIELDMESH_OFFSET_X ? dec_X : -dec_X;
if (gap_Y < 0.1f)
m_cam_vel_old.Y = 0.0f;
- m_wieldmesh_offset.Y -= m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y
- ? dec_Y
- : -dec_Y;
+ m_wieldmesh_offset.Y -=
+ m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y ? dec_Y : -dec_Y;
}
}
-void Camera::update(
- LocalPlayer *player, f32 frametime, f32 busytime, f32 tool_reload_ratio)
+void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio)
{
// Get player position
// Smooth the movement when walking up stairs
@@ -353,24 +340,19 @@ void Camera::update(
// mods expect the player head to be at the parent's position
// plus eye height.
if (player->getParent())
- player_position =
- player->getParent()->getPosition() +
- v3f(0, g_settings->getBool("float_above_parent") ? BS : 0,
- 0);
-
- // Smooth the camera movement when the player instantly moves upward due to
- // stepheight. To smooth the 'not touching_ground' stepheight, smoothing is
- // necessary when jumping or swimming (for when moving from liquid to land).
- // Disable smoothing if climbing or flying, to avoid upwards offset of player
- // model when seen in 3rd person view.
- bool flying = g_settings->getBool("free_move") &&
- m_client->checkLocalPrivilege("fly");
- if (player_position.Y > old_player_position.Y && !player->is_climbing &&
- !flying) {
+ player_position = player->getParent()->getPosition() + v3f(0, g_settings->getBool("float_above_parent") ? BS : 0, 0);
+
+ // Smooth the camera movement when the player instantly moves upward due to stepheight.
+ // To smooth the 'not touching_ground' stepheight, smoothing is necessary when jumping
+ // or swimming (for when moving from liquid to land).
+ // Disable smoothing if climbing or flying, to avoid upwards offset of player model
+ // when seen in 3rd person view.
+ bool flying = g_settings->getBool("free_move") && m_client->checkLocalPrivilege("fly");
+ if (player_position.Y > old_player_position.Y && !player->is_climbing && !flying) {
f32 oldy = old_player_position.Y;
f32 newy = player_position.Y;
f32 t = std::exp(-23 * frametime);
- player_position.Y = oldy * t + newy * (1 - t);
+ player_position.Y = oldy * t + newy * (1-t);
}
// Set player node transformation
@@ -379,20 +361,19 @@ void Camera::update(
m_playernode->updateAbsolutePosition();
// Get camera tilt timer (hurt animation)
- float cameratilt = fabs(fabs(player->hurt_tilt_timer - 0.75) - 0.75);
+ float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75);
// Fall bobbing animation
float fall_bobbing = 0;
- if (player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD) {
- if (m_view_bobbing_fall == -1) // Effect took place and has finished
+ if(player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD)
+ {
+ if(m_view_bobbing_fall == -1) // Effect took place and has finished
player->camera_impact = m_view_bobbing_fall = 0;
- else if (m_view_bobbing_fall == 0) // Initialize effect
+ else if(m_view_bobbing_fall == 0) // Initialize effect
m_view_bobbing_fall = 1;
// Convert 0 -> 1 to 0 -> 1 -> 0
- fall_bobbing = m_view_bobbing_fall < 0.5
- ? m_view_bobbing_fall * 2
- : -(m_view_bobbing_fall - 0.5) * 2 + 1;
+ fall_bobbing = m_view_bobbing_fall < 0.5 ? m_view_bobbing_fall * 2 : -(m_view_bobbing_fall - 0.5) * 2 + 1;
// Smoothen and invert the above
fall_bobbing = sin(fall_bobbing * 0.5 * M_PI) * -1;
// Amplify according to the intensity of the impact
@@ -413,56 +394,60 @@ void Camera::update(
eye_offset.Y += cameratilt * -player->hurt_tilt_strength + fall_bobbing;
m_headnode->setPosition(eye_offset);
m_headnode->setRotation(v3f(player->getPitch(), 0,
- cameratilt * player->hurt_tilt_strength));
+ cameratilt * player->hurt_tilt_strength));
m_headnode->updateAbsolutePosition();
}
// Compute relative camera position and target
- v3f rel_cam_pos = v3f(0, 0, 0);
- v3f rel_cam_target = v3f(0, 0, 1);
- v3f rel_cam_up = v3f(0, 1, 0);
+ v3f rel_cam_pos = v3f(0,0,0);
+ v3f rel_cam_target = v3f(0,0,1);
+ v3f rel_cam_up = v3f(0,1,0);
if (m_cache_view_bobbing_amount != 0.0f && m_view_bobbing_anim != 0.0f &&
- m_camera_mode < CAMERA_MODE_THIRD) {
+ m_camera_mode < CAMERA_MODE_THIRD) {
f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
-#if 1
+ #if 1
f32 bobknob = 1.2;
f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI);
- // f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI);
+ //f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI);
- v3f bobvec = v3f(0.3 * bobdir * sin(bobfrac * M_PI),
- -0.28 * bobtmp * bobtmp, 0.);
+ v3f bobvec = v3f(
+ 0.3 * bobdir * sin(bobfrac * M_PI),
+ -0.28 * bobtmp * bobtmp,
+ 0.);
- // rel_cam_pos += 0.2 * bobvec;
- // rel_cam_target += 0.03 * bobvec;
- // rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI);
+ //rel_cam_pos += 0.2 * bobvec;
+ //rel_cam_target += 0.03 * bobvec;
+ //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI);
float f = 1.0;
f *= m_cache_view_bobbing_amount;
rel_cam_pos += bobvec * f;
- // rel_cam_target += 0.995 * bobvec * f;
+ //rel_cam_target += 0.995 * bobvec * f;
rel_cam_target += bobvec * f;
rel_cam_target.Z -= 0.005 * bobvec.Z * f;
- // rel_cam_target.X -= 0.005 * bobvec.X * f;
- // rel_cam_target.Y -= 0.005 * bobvec.Y * f;
+ //rel_cam_target.X -= 0.005 * bobvec.X * f;
+ //rel_cam_target.Y -= 0.005 * bobvec.Y * f;
rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * f);
-#else
+ #else
f32 angle_deg = 1 * bobdir * sin(bobfrac * M_PI);
f32 angle_rad = angle_deg * M_PI / 180;
f32 r = 0.05;
- v3f off = v3f(r * sin(angle_rad), r * (cos(angle_rad) - 1), 0);
+ v3f off = v3f(
+ r * sin(angle_rad),
+ r * (cos(angle_rad) - 1),
+ 0);
rel_cam_pos += off;
- // rel_cam_target += off;
+ //rel_cam_target += off;
rel_cam_up.rotateXYBy(angle_deg);
-#endif
+ #endif
+
}
// Compute absolute camera position and target
- m_headnode->getAbsoluteTransformation().transformVect(
- m_camera_position, rel_cam_pos);
- m_headnode->getAbsoluteTransformation().rotateVect(
- m_camera_direction, rel_cam_target - rel_cam_pos);
+ m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
+ m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
v3f abs_cam_up;
m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
@@ -471,7 +456,8 @@ void Camera::update(
v3f my_cp = m_camera_position;
// Reposition the camera for third person view
- if (m_camera_mode > CAMERA_MODE_FIRST) {
+ if (m_camera_mode > CAMERA_MODE_FIRST)
+ {
if (m_camera_mode == CAMERA_MODE_THIRD_FRONT)
m_camera_direction *= -1;
@@ -483,46 +469,41 @@ void Camera::update(
my_cp.X = m_camera_position.X + m_camera_direction.X * -i;
my_cp.Z = m_camera_position.Z + m_camera_direction.Z * -i;
if (i > 12)
- my_cp.Y = m_camera_position.Y +
- (m_camera_direction.Y * -i);
+ my_cp.Y = m_camera_position.Y + (m_camera_direction.Y * -i);
// Prevent camera positioned inside nodes
const NodeDefManager *nodemgr = m_client->ndef();
- MapNode n = m_client->getEnv().getClientMap().getNode(
- floatToInt(my_cp, BS));
+ MapNode n = m_client->getEnv().getClientMap()
+ .getNode(floatToInt(my_cp, BS));
- const ContentFeatures &features = nodemgr->get(n);
+ const ContentFeatures& features = nodemgr->get(n);
if (features.walkable) {
- my_cp.X += m_camera_direction.X * -1 * -BS / 2;
- my_cp.Z += m_camera_direction.Z * -1 * -BS / 2;
- my_cp.Y += m_camera_direction.Y * -1 * -BS / 2;
+ my_cp.X += m_camera_direction.X*-1*-BS/2;
+ my_cp.Z += m_camera_direction.Z*-1*-BS/2;
+ my_cp.Y += m_camera_direction.Y*-1*-BS/2;
abort = true;
break;
}
}
// If node blocks camera position don't move y to heigh
- if (abort && my_cp.Y > player_position.Y + BS * 2)
- my_cp.Y = player_position.Y + BS * 2;
+ if (abort && my_cp.Y > player_position.Y+BS*2)
+ my_cp.Y = player_position.Y+BS*2;
}
// Update offset if too far away from the center of the map
- m_camera_offset.X +=
- CAMERA_OFFSET_STEP *
- (((s16)(my_cp.X / BS) - m_camera_offset.X) / CAMERA_OFFSET_STEP);
- m_camera_offset.Y +=
- CAMERA_OFFSET_STEP *
- (((s16)(my_cp.Y / BS) - m_camera_offset.Y) / CAMERA_OFFSET_STEP);
- m_camera_offset.Z +=
- CAMERA_OFFSET_STEP *
- (((s16)(my_cp.Z / BS) - m_camera_offset.Z) / CAMERA_OFFSET_STEP);
+ m_camera_offset.X += CAMERA_OFFSET_STEP*
+ (((s16)(my_cp.X/BS) - m_camera_offset.X)/CAMERA_OFFSET_STEP);
+ m_camera_offset.Y += CAMERA_OFFSET_STEP*
+ (((s16)(my_cp.Y/BS) - m_camera_offset.Y)/CAMERA_OFFSET_STEP);
+ m_camera_offset.Z += CAMERA_OFFSET_STEP*
+ (((s16)(my_cp.Z/BS) - m_camera_offset.Z)/CAMERA_OFFSET_STEP);
// Set camera node transformation
- m_cameranode->setPosition(my_cp - intToFloat(m_camera_offset, BS));
+ m_cameranode->setPosition(my_cp-intToFloat(m_camera_offset, BS));
m_cameranode->setUpVector(abs_cam_up);
// *100.0 helps in large map coordinates
- m_cameranode->setTarget(my_cp - intToFloat(m_camera_offset, BS) +
- 100 * m_camera_direction);
+ m_cameranode->setTarget(my_cp-intToFloat(m_camera_offset, BS) + 100 * m_camera_direction);
// update the camera position in third-person mode to render blocks behind player
// and correctly apply liquid post FX.
@@ -542,9 +523,7 @@ void Camera::update(
// Mark transition as complete if target FOV has been reached
if ((m_fov_diff > 0.0f && m_curr_fov_degrees >= m_target_fov_degrees) ||
- (m_fov_diff < 0.0f &&
- m_curr_fov_degrees <=
- m_target_fov_degrees)) {
+ (m_fov_diff < 0.0f && m_curr_fov_degrees <= m_target_fov_degrees)) {
m_fov_transition_active = false;
m_curr_fov_degrees = m_target_fov_degrees;
}
@@ -562,10 +541,10 @@ void Camera::update(
// FOV and aspect ratio
const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
- m_aspect = (f32)window_size.X / (f32)window_size.Y;
+ m_aspect = (f32) window_size.X / (f32) window_size.Y;
m_fov_y = m_curr_fov_degrees * M_PI / 180.0;
// Increase vertical FOV on lower aspect ratios (<16:10)
- m_fov_y *= core::clamp(sqrt(16. / 10. / m_aspect), 1.0, 1.4);
+ m_fov_y *= core::clamp(sqrt(16./10. / m_aspect), 1.0, 1.4);
m_fov_x = 2 * atan(m_aspect * tan(0.5 * m_fov_y));
m_cameranode->setAspectRatio(m_aspect);
m_cameranode->setFOV(m_fov_y);
@@ -574,27 +553,29 @@ void Camera::update(
addArmInertia(player->getYaw());
// Position the wielded item
- // v3f wield_position = v3f(45, -35, 65);
+ //v3f wield_position = v3f(45, -35, 65);
v3f wield_position = v3f(m_wieldmesh_offset.X, m_wieldmesh_offset.Y, 65);
- // v3f wield_rotation = v3f(-100, 120, -100);
+ //v3f wield_rotation = v3f(-100, 120, -100);
v3f wield_rotation = v3f(-100, 120, -100);
- wield_position.Y += fabs(m_wield_change_timer) * 320 - 40;
- if (m_digging_anim < 0.05 || m_digging_anim > 0.5) {
+ wield_position.Y += fabs(m_wield_change_timer)*320 - 40;
+ if(m_digging_anim < 0.05 || m_digging_anim > 0.5)
+ {
f32 frac = 1.0;
- if (m_digging_anim > 0.5)
+ if(m_digging_anim > 0.5)
frac = 2.0 * (m_digging_anim - 0.5);
// This value starts from 1 and settles to 0
f32 ratiothing = std::pow((1.0f - tool_reload_ratio), 0.5f);
- // f32 ratiothing2 = pow(ratiothing, 0.5f);
- f32 ratiothing2 = (easeCurve(ratiothing * 0.5)) * 2.0;
+ //f32 ratiothing2 = pow(ratiothing, 0.5f);
+ f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0;
wield_position.Y -= frac * 25.0 * pow(ratiothing2, 1.7f);
- // wield_position.Z += frac * 5.0 * ratiothing2;
+ //wield_position.Z += frac * 5.0 * ratiothing2;
wield_position.X -= frac * 35.0 * pow(ratiothing2, 1.1f);
wield_rotation.Y += frac * 70.0 * pow(ratiothing2, 1.4f);
- // wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
- // wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
+ //wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
+ //wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
}
- if (m_digging_button != -1) {
+ if (m_digging_button != -1)
+ {
f32 digfrac = m_digging_anim;
wield_position.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI);
wield_position.Y += 24 * sin(digfrac * 1.8 * M_PI);
@@ -609,8 +590,8 @@ void Camera::update(
wield_rotation *= core::RADTODEG;
} else {
f32 bobfrac = my_modf(m_view_bobbing_anim);
- wield_position.X -= sin(bobfrac * M_PI * 2.0) * 3.0;
- wield_position.Y += sin(my_modf(bobfrac * 2.0) * M_PI) * 3.0;
+ wield_position.X -= sin(bobfrac*M_PI*2.0) * 3.0;
+ wield_position.Y += sin(my_modf(bobfrac*2.0)*M_PI) * 3.0;
}
m_wieldnode->setPosition(wield_position);
m_wieldnode->setRotation(wield_rotation);
@@ -628,8 +609,7 @@ void Camera::update(
const bool movement_Y = fabs(speed.Y) > BS;
const bool walking = movement_XZ && player->touching_ground;
- const bool swimming =
- (movement_XZ || player->swimming_vertical) && player->in_liquid;
+ const bool swimming = (movement_XZ || player->swimming_vertical) && player->in_liquid;
const bool climbing = movement_Y && player->is_climbing;
if ((walking || swimming || climbing) && !flying) {
// Start animation
@@ -648,20 +628,18 @@ void Camera::updateViewingRange()
// Ignore near_plane setting on all other platforms to prevent abuse
#if ENABLE_GLES
- m_cameranode->setNearValue(
- rangelim(g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS);
+ m_cameranode->setNearValue(rangelim(
+ g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS);
#else
m_cameranode->setNearValue(0.1f * BS);
#endif
- m_draw_control.wanted_range =
- std::fmin(adjustDist(viewing_range, getFovMax()), 4000);
+ m_draw_control.wanted_range = std::fmin(adjustDist(viewing_range, getFovMax()), 4000);
if (m_draw_control.range_all) {
m_cameranode->setFarValue(100000.0);
return;
}
- m_cameranode->setFarValue(
- (viewing_range < 2000) ? 2000 * BS : viewing_range * BS);
+ m_cameranode->setFarValue((viewing_range < 2000) ? 2000 * BS : viewing_range * BS);
}
void Camera::setDigging(s32 button)
@@ -682,23 +660,23 @@ void Camera::wield(const ItemStack &item)
}
}
-void Camera::drawWieldedTool(irr::core::matrix4 *translation)
+void Camera::drawWieldedTool(irr::core::matrix4* translation)
{
// Clear Z buffer so that the wielded tool stays in front of world geometry
m_wieldmgr->getVideoDriver()->clearZBuffer();
// Draw the wielded node (in a separate scene manager)
- scene::ICameraSceneNode *cam = m_wieldmgr->getActiveCamera();
+ scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
cam->setAspectRatio(m_cameranode->getAspectRatio());
- cam->setFOV(72.0 * M_PI / 180.0);
+ cam->setFOV(72.0*M_PI/180.0);
cam->setNearValue(10);
cam->setFarValue(1000);
- if (translation != NULL) {
+ if (translation != NULL)
+ {
irr::core::matrix4 startMatrix = cam->getAbsoluteTransformation();
- irr::core::vector3df focusPoint =
- (cam->getTarget() - cam->getAbsolutePosition())
- .setLength(1) +
- cam->getAbsolutePosition();
+ irr::core::vector3df focusPoint = (cam->getTarget()
+ - cam->getAbsolutePosition()).setLength(1)
+ + cam->getAbsolutePosition();
irr::core::vector3df camera_pos =
(startMatrix * *translation).getTranslation();
@@ -713,7 +691,8 @@ void Camera::drawNametags()
core::matrix4 trans = m_cameranode->getProjectionMatrix();
trans *= m_cameranode->getViewMatrix();
- for (std::list<Nametag *>::const_iterator i = m_nametags.begin();
+ for (std::list<Nametag *>::const_iterator
+ i = m_nametags.begin();
i != m_nametags.end(); ++i) {
Nametag *nametag = *i;
if (nametag->nametag_color.getAlpha() == 0) {
@@ -722,34 +701,27 @@ void Camera::drawNametags()
// shadow can remain.
continue;
}
- v3f pos = nametag->parent_node->getAbsolutePosition() +
- nametag->nametag_pos * BS;
- f32 transformed_pos[4] = {pos.X, pos.Y, pos.Z, 1.0f};
+ v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->nametag_pos * BS;
+ f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f };
trans.multiplyWith1x4Matrix(transformed_pos);
if (transformed_pos[3] > 0) {
- std::wstring nametag_colorless = unescape_translate(
- utf8_to_wide(nametag->nametag_text));
+ std::wstring nametag_colorless =
+ unescape_translate(utf8_to_wide(nametag->nametag_text));
core::dimension2d<u32> textsize =
- g_fontengine->getFont()->getDimension(
- nametag_colorless.c_str());
- f32 zDiv = transformed_pos[3] == 0.0f
- ? 1.0f
- : core::reciprocal(transformed_pos[3]);
- v2u32 screensize = RenderingEngine::get_video_driver()
- ->getScreenSize();
+ g_fontengine->getFont()->getDimension(
+ nametag_colorless.c_str());
+ f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
+ core::reciprocal(transformed_pos[3]);
+ v2u32 screensize = RenderingEngine::get_video_driver()->getScreenSize();
v2s32 screen_pos;
- screen_pos.X = screensize.X * (0.5 * transformed_pos[0] * zDiv +
- 0.5) -
- textsize.Width / 2;
- screen_pos.Y = screensize.Y * (0.5 - transformed_pos[1] * zDiv *
- 0.5) -
- textsize.Height / 2;
+ screen_pos.X = screensize.X *
+ (0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2;
+ screen_pos.Y = screensize.Y *
+ (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
g_fontengine->getFont()->draw(
- translate_string(
- utf8_to_wide(nametag->nametag_text))
- .c_str(),
- size + screen_pos, nametag->nametag_color);
+ translate_string(utf8_to_wide(nametag->nametag_text)).c_str(),
+ size + screen_pos, nametag->nametag_color);
}
}
}
diff --git a/src/client/camera.h b/src/client/camera.h
index bf10329ab..3a59637bc 100644
--- a/src/client/camera.h
+++ b/src/client/camera.h
@@ -31,13 +31,15 @@ struct MapDrawControl;
class Client;
class WieldMeshSceneNode;
-struct Nametag
-{
- Nametag(scene::ISceneNode *a_parent_node, const std::string &a_nametag_text,
- const video::SColor &a_nametag_color, const v3f &a_nametag_pos) :
- parent_node(a_parent_node),
- nametag_text(a_nametag_text), nametag_color(a_nametag_color),
- nametag_pos(a_nametag_pos)
+struct Nametag {
+ Nametag(scene::ISceneNode *a_parent_node,
+ const std::string &a_nametag_text,
+ const video::SColor &a_nametag_color,
+ const v3f &a_nametag_pos):
+ parent_node(a_parent_node),
+ nametag_text(a_nametag_text),
+ nametag_color(a_nametag_color),
+ nametag_pos(a_nametag_pos)
{
}
scene::ISceneNode *parent_node;
@@ -46,17 +48,12 @@ struct Nametag
v3f nametag_pos;
};
-enum CameraMode
-{
- CAMERA_MODE_FIRST,
- CAMERA_MODE_THIRD,
- CAMERA_MODE_THIRD_FRONT
-};
+enum CameraMode {CAMERA_MODE_FIRST, CAMERA_MODE_THIRD, CAMERA_MODE_THIRD_FRONT};
/*
- Client camera class, manages the player and camera scene nodes, the viewing
- distance and performs view bobbing etc. It also displays the wielded tool in front of
- the first-person camera.
+ Client camera class, manages the player and camera scene nodes, the viewing distance
+ and performs view bobbing etc. It also displays the wielded tool in front of the
+ first-person camera.
*/
class Camera
{
@@ -66,30 +63,54 @@ public:
// Get camera scene node.
// It has the eye transformation, pitch and view bobbing applied.
- inline scene::ICameraSceneNode *getCameraNode() const { return m_cameranode; }
+ inline scene::ICameraSceneNode* getCameraNode() const
+ {
+ return m_cameranode;
+ }
// Get the camera position (in absolute scene coordinates).
// This has view bobbing applied.
- inline v3f getPosition() const { return m_camera_position; }
+ inline v3f getPosition() const
+ {
+ return m_camera_position;
+ }
// Returns the absolute position of the head SceneNode in the world
- inline v3f getHeadPosition() const { return m_headnode->getAbsolutePosition(); }
+ inline v3f getHeadPosition() const
+ {
+ return m_headnode->getAbsolutePosition();
+ }
// Get the camera direction (in absolute camera coordinates).
// This has view bobbing applied.
- inline v3f getDirection() const { return m_camera_direction; }
+ inline v3f getDirection() const
+ {
+ return m_camera_direction;
+ }
// Get the camera offset
- inline v3s16 getOffset() const { return m_camera_offset; }
+ inline v3s16 getOffset() const
+ {
+ return m_camera_offset;
+ }
// Horizontal field of view
- inline f32 getFovX() const { return m_fov_x; }
+ inline f32 getFovX() const
+ {
+ return m_fov_x;
+ }
// Vertical field of view
- inline f32 getFovY() const { return m_fov_y; }
+ inline f32 getFovY() const
+ {
+ return m_fov_y;
+ }
// Get maximum of getFovX() and getFovY()
- inline f32 getFovMax() const { return MYMAX(m_fov_x, m_fov_y); }
+ inline f32 getFovMax() const
+ {
+ return MYMAX(m_fov_x, m_fov_y);
+ }
// Notify about new server-sent FOV and initialize smooth FOV transition
void notifyFovChange();
@@ -102,7 +123,7 @@ public:
// Update the camera from the local player's position.
// busytime is used to adjust the viewing range.
- void update(LocalPlayer *player, f32 frametime, f32 busytime,
+ void update(LocalPlayer* player, f32 frametime, f32 busytime,
f32 tool_reload_ratio);
// Update render distance
@@ -118,11 +139,10 @@ public:
// Draw the wielded tool.
// This has to happen *after* the main scene is drawn.
// Warning: This clears the Z buffer.
- void drawWieldedTool(irr::core::matrix4 *translation = NULL);
+ void drawWieldedTool(irr::core::matrix4* translation=NULL);
// Toggle the current camera mode
- void toggleCameraMode()
- {
+ void toggleCameraMode() {
if (m_camera_mode == CAMERA_MODE_FIRST)
m_camera_mode = CAMERA_MODE_THIRD;
else if (m_camera_mode == CAMERA_MODE_THIRD)
@@ -132,14 +152,20 @@ public:
}
// Set the current camera mode
- inline void setCameraMode(CameraMode mode) { m_camera_mode = mode; }
+ inline void setCameraMode(CameraMode mode)
+ {
+ m_camera_mode = mode;
+ }
- // read the current camera mode
- inline CameraMode getCameraMode() { return m_camera_mode; }
+ //read the current camera mode
+ inline CameraMode getCameraMode()
+ {
+ return m_camera_mode;
+ }
Nametag *addNametag(scene::ISceneNode *parent_node,
- const std::string &nametag_text, video::SColor nametag_color,
- const v3f &pos);
+ const std::string &nametag_text, video::SColor nametag_color,
+ const v3f &pos);
void removeNametag(Nametag *nametag);
@@ -159,7 +185,7 @@ private:
WieldMeshSceneNode *m_wieldnode = nullptr;
// draw control
- MapDrawControl &m_draw_control;
+ MapDrawControl& m_draw_control;
Client *m_client;
diff --git a/src/client/client.cpp b/src/client/client.cpp
index 54fbbf8b5..aa3e257ac 100644
--- a/src/client/client.cpp
+++ b/src/client/client.cpp
@@ -59,7 +59,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "chatmessage.h"
#include "translation.h"
-extern gui::IGUIEnvironment *guienv;
+extern gui::IGUIEnvironment* guienv;
/*
Utility classes
@@ -76,11 +76,10 @@ u32 PacketCounter::sum() const
void PacketCounter::print(std::ostream &o) const
{
for (const auto &it : m_packets) {
- auto name = it.first >= TOCLIENT_NUM_MSG_TYPES
- ? "?"
- : toClientCommandTable[it.first].name;
- o << "cmd " << it.first << " (" << name << ") count " << it.second
- << std::endl;
+ auto name = it.first >= TOCLIENT_NUM_MSG_TYPES ? "?"
+ : toClientCommandTable[it.first].name;
+ o << "cmd " << it.first << " (" << name << ") count "
+ << it.second << std::endl;
}
}
@@ -88,23 +87,42 @@ void PacketCounter::print(std::ostream &o) const
Client
*/
-Client::Client(const char *playername, const std::string &password,
- const std::string &address_name, MapDrawControl &control,
- IWritableTextureSource *tsrc, IWritableShaderSource *shsrc,
- IWritableItemDefManager *itemdef, NodeDefManager *nodedef,
- ISoundManager *sound, MtEventManager *event, bool ipv6, GameUI *game_ui) :
- m_mesh_update_thread(this),
- m_tsrc(tsrc), m_shsrc(shsrc), m_itemdef(itemdef), m_nodedef(nodedef),
- m_sound(sound), m_event(event),
- m_env(new ClientMap(this, control, 666), tsrc, this),
- m_particle_manager(&m_env),
- m_con(new con::Connection(
- PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
- m_address_name(address_name), m_server_ser_ver(SER_FMT_VER_INVALID),
- m_last_chat_message_sent(time(NULL)), m_password(password),
- m_chosen_auth_mech(AUTH_MECHANISM_NONE),
- m_media_downloader(new ClientMediaDownloader()), m_state(LC_Created),
- m_game_ui(game_ui), m_modchannel_mgr(new ModChannelMgr())
+Client::Client(
+ const char *playername,
+ const std::string &password,
+ const std::string &address_name,
+ MapDrawControl &control,
+ IWritableTextureSource *tsrc,
+ IWritableShaderSource *shsrc,
+ IWritableItemDefManager *itemdef,
+ NodeDefManager *nodedef,
+ ISoundManager *sound,
+ MtEventManager *event,
+ bool ipv6,
+ GameUI *game_ui
+):
+ m_mesh_update_thread(this),
+ m_tsrc(tsrc),
+ m_shsrc(shsrc),
+ m_itemdef(itemdef),
+ m_nodedef(nodedef),
+ m_sound(sound),
+ m_event(event),
+ m_env(
+ new ClientMap(this, control, 666),
+ tsrc, this
+ ),
+ m_particle_manager(&m_env),
+ m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
+ m_address_name(address_name),
+ m_server_ser_ver(SER_FMT_VER_INVALID),
+ m_last_chat_message_sent(time(NULL)),
+ m_password(password),
+ m_chosen_auth_mech(AUTH_MECHANISM_NONE),
+ m_media_downloader(new ClientMediaDownloader()),
+ m_state(LC_Created),
+ m_game_ui(game_ui),
+ m_modchannel_mgr(new ModChannelMgr())
{
// Add local player
m_env.setLocalPlayer(new LocalPlayer(this, playername));
@@ -128,8 +146,8 @@ void Client::loadMods()
// TODO Delete this code block when server-sent CSM and verifying of builtin are
// complete.
if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
- warningstream << "Client-provided mod loading is disabled by server."
- << std::endl;
+ warningstream << "Client-provided mod loading is disabled by server." <<
+ std::endl;
return;
}
@@ -173,8 +191,7 @@ void Client::loadMods()
for (const ModSpec &mod : m_mods) {
if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
throw ModError("Error loading mod \"" + mod.name +
- "\": Mod name does not follow naming "
- "conventions: "
+ "\": Mod name does not follow naming conventions: "
"Only characters [a-z0-9_] are allowed.");
}
scanModIntoMemory(mod.name, mod.path);
@@ -208,14 +225,13 @@ bool Client::checkBuiltinIntegrity()
}
void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
- std::string mod_subpath)
+ std::string mod_subpath)
{
std::string full_path = mod_path + DIR_DELIM + mod_subpath;
std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
for (const fs::DirListNode &j : mod) {
if (j.dir) {
- scanModSubfolder(mod_name, mod_path,
- mod_subpath + j.name + DIR_DELIM);
+ scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
continue;
}
std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
@@ -223,12 +239,12 @@ void Client::scanModSubfolder(const std::string &mod_name, const std::string &mo
std::string real_path = full_path + j.name;
std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
infostream << "Client::scanModSubfolder(): Loading \"" << real_path
- << "\" as \"" << vfs_path << "\"." << std::endl;
+ << "\" as \"" << vfs_path << "\"." << std::endl;
std::ifstream is(real_path, std::ios::binary | std::ios::ate);
- if (!is.good()) {
+ if(!is.good()) {
errorstream << "Client::scanModSubfolder(): Can't read file \""
- << real_path << "\"." << std::endl;
+ << real_path << "\"." << std::endl;
continue;
}
auto size = is.tellg();
@@ -243,25 +259,23 @@ void Client::scanModSubfolder(const std::string &mod_name, const std::string &mo
const std::string &Client::getBuiltinLuaPath()
{
- static const std::string builtin_dir =
- porting::path_share + DIR_DELIM + "builtin";
+ static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
return builtin_dir;
}
const std::string &Client::getClientModsLuaPath()
{
- static const std::string clientmods_dir =
- porting::path_share + DIR_DELIM + "clientmods";
+ static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
return clientmods_dir;
}
-const std::vector<ModSpec> &Client::getMods() const
+const std::vector<ModSpec>& Client::getMods() const
{
static std::vector<ModSpec> client_modspec_temp;
return client_modspec_temp;
}
-const ModSpec *Client::getModSpec(const std::string &modname) const
+const ModSpec* Client::getModSpec(const std::string &modname) const
{
return NULL;
}
@@ -271,7 +285,7 @@ void Client::Stop()
m_shutdown = true;
if (m_mods_loaded)
m_script->on_shutdown();
- // request all client managed threads to stop
+ //request all client managed threads to stop
m_mesh_update_thread.stop();
// Save local server map
if (m_localdb) {
@@ -302,6 +316,7 @@ Client::~Client()
delete r.mesh;
}
+
delete m_inventory_from_server;
// Delete detached inventories
@@ -311,8 +326,7 @@ Client::~Client()
// cleanup 3d model meshes on client shutdown
while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
- scene::IAnimatedMesh *mesh =
- RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
+ scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
if (mesh)
RenderingEngine::get_mesh_cache()->removeMesh(mesh);
@@ -338,7 +352,7 @@ void Client::step(float dtime)
dtime = 2.0;
m_animation_time += dtime;
- if (m_animation_time > 60.0)
+ if(m_animation_time > 60.0)
m_animation_time -= 60.0;
m_time_of_day_update_timer += dtime;
@@ -351,14 +365,14 @@ void Client::step(float dtime)
{
float &counter = m_packetcounter_timer;
counter -= dtime;
- if (counter <= 0.0f) {
+ if(counter <= 0.0f)
+ {
counter = 30.0f;
u32 sum = m_packetcounter.sum();
float avg = sum / counter;
infostream << "Client packetcounter (" << counter << "s): "
- << "sum=" << sum << " avg=" << avg << "/s"
- << std::endl;
+ << "sum=" << sum << " avg=" << avg << "/s" << std::endl;
m_packetcounter.print(infostream);
m_packetcounter.clear();
}
@@ -369,19 +383,19 @@ void Client::step(float dtime)
static bool initial_step = true;
if (initial_step) {
initial_step = false;
- } else if (m_state == LC_Created) {
+ }
+ else if(m_state == LC_Created) {
if (m_is_registration_confirmation_state) {
// Waiting confirmation
return;
}
float &counter = m_connection_reinit_timer;
counter -= dtime;
- if (counter <= 0.0) {
+ if(counter <= 0.0) {
counter = 2.0;
LocalPlayer *myplayer = m_env.getLocalPlayer();
- FATAL_ERROR_IF(myplayer == NULL,
- "Local player not found in environment.");
+ FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
sendInit(myplayer->getName());
}
@@ -398,12 +412,12 @@ void Client::step(float dtime)
Run Map's timers and unload unused data
*/
const float map_timer_and_unload_dtime = 5.25;
- if (m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
+ if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
std::vector<v3s16> deleted_blocks;
m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
- g_settings->getFloat("client_unload_unused_data_timeout"),
- g_settings->getS32("client_mapblock_limit"),
- &deleted_blocks);
+ g_settings->getFloat("client_unload_unused_data_timeout"),
+ g_settings->getS32("client_mapblock_limit"),
+ &deleted_blocks);
/*
Send info to server
@@ -412,9 +426,9 @@ void Client::step(float dtime)
std::vector<v3s16>::iterator i = deleted_blocks.begin();
std::vector<v3s16> sendlist;
- for (;;) {
- if (sendlist.size() == 255 || i == deleted_blocks.end()) {
- if (sendlist.empty())
+ for(;;) {
+ if(sendlist.size() == 255 || i == deleted_blocks.end()) {
+ if(sendlist.empty())
break;
/*
[0] u16 command
@@ -426,7 +440,7 @@ void Client::step(float dtime)
sendDeletedBlocks(sendlist);
- if (i == deleted_blocks.end())
+ if(i == deleted_blocks.end())
break;
sendlist.clear();
@@ -463,8 +477,7 @@ void Client::step(float dtime)
if (envEvent.type == CEE_PLAYER_DAMAGE) {
u16 damage = envEvent.player_damage.amount;
- if (envEvent.player_damage.send_to_server &&
- !g_settings->getBool("prevent_natural_damage"))
+ if (envEvent.player_damage.send_to_server && ! g_settings->getBool("prevent_natural_damage"))
sendDamage(damage);
// Add to ClientEvent queue
@@ -480,7 +493,7 @@ void Client::step(float dtime)
*/
float &counter = m_avg_rtt_timer;
counter += dtime;
- if (counter >= 10) {
+ if(counter >= 10) {
counter = 0.0;
// connectedAndInitialized() is true, peer exists.
float avg_rtt = getRTT();
@@ -493,7 +506,8 @@ void Client::step(float dtime)
{
float &counter = m_playerpos_send_timer;
counter += dtime;
- if ((m_state == LC_Ready) && (counter >= m_recommended_send_interval)) {
+ if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
+ {
counter = 0.0;
sendPlayerPos();
}
@@ -505,14 +519,14 @@ void Client::step(float dtime)
{
int num_processed_meshes = 0;
std::vector<v3s16> blocks_to_ack;
- while (!m_mesh_update_thread.m_queue_out.empty()) {
+ while (!m_mesh_update_thread.m_queue_out.empty())
+ {
num_processed_meshes++;
MinimapMapblock *minimap_mapblock = NULL;
bool do_mapper_update = true;
- MeshUpdateResult r =
- m_mesh_update_thread.m_queue_out.pop_frontNoEx();
+ MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
if (block) {
// Delete the old mesh
@@ -526,8 +540,7 @@ void Client::step(float dtime)
bool is_empty = true;
for (int l = 0; l < MAX_TILE_LAYERS; l++)
- if (r.mesh->getMesh(l)->getMeshBufferCount() !=
- 0)
+ if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
is_empty = false;
if (is_empty)
@@ -553,13 +566,12 @@ void Client::step(float dtime)
}
}
if (blocks_to_ack.size() > 0) {
- // Acknowledge block(s)
- sendGotBlocks(blocks_to_ack);
+ // Acknowledge block(s)
+ sendGotBlocks(blocks_to_ack);
}
if (num_processed_meshes > 0)
- g_profiler->graphAdd(
- "num_processed_meshes", num_processed_meshes);
+ g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
}
/*
@@ -588,8 +600,7 @@ void Client::step(float dtime)
if (count_after != count_before) {
// Do this every <interval> seconds after TOCLIENT_INVENTORY
- // Reset the locally changed inventory to the authoritative
- // inventory
+ // Reset the locally changed inventory to the authoritative inventory
player->inventory = *m_inventory_from_server;
m_update_wielded_item = true;
}
@@ -613,17 +624,16 @@ void Client::step(float dtime)
Handle removed remotely initiated sounds
*/
m_removed_sounds_check_timer += dtime;
- if (m_removed_sounds_check_timer >= 2.32) {
+ if(m_removed_sounds_check_timer >= 2.32) {
m_removed_sounds_check_timer = 0;
// Find removed sounds and clear references to them
std::vector<s32> removed_server_ids;
- for (std::unordered_map<s32, int>::iterator i =
- m_sounds_server_to_client.begin();
+ for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
i != m_sounds_server_to_client.end();) {
s32 server_id = i->first;
int client_id = i->second;
++i;
- if (!m_sound->soundExists(client_id)) {
+ if(!m_sound->soundExists(client_id)) {
m_sounds_server_to_client.erase(server_id);
m_sounds_client_to_server.erase(client_id);
m_sounds_to_objects.erase(client_id);
@@ -632,47 +642,48 @@ void Client::step(float dtime)
}
// Sync to server
- if (!removed_server_ids.empty()) {
+ if(!removed_server_ids.empty()) {
sendRemovedSounds(removed_server_ids);
}
}
m_mod_storage_save_timer -= dtime;
if (m_mod_storage_save_timer <= 0.0f) {
- m_mod_storage_save_timer =
- g_settings->getFloat("server_map_save_interval");
+ m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
int n = 0;
- for (std::unordered_map<std::string, ModMetadata *>::const_iterator it =
- m_mod_storages.begin();
- it != m_mod_storages.end(); ++it) {
+ for (std::unordered_map<std::string, ModMetadata *>::const_iterator
+ it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
if (it->second->isModified()) {
it->second->save(getModStoragePath());
n++;
}
}
if (n > 0)
- infostream << "Saved " << n << " modified mod storages."
- << std::endl;
+ infostream << "Saved " << n << " modified mod storages." << std::endl;
}
// Write server map
- if (m_localdb && m_localdb_save_interval.step(dtime, m_cache_save_interval)) {
+ if (m_localdb && m_localdb_save_interval.step(dtime,
+ m_cache_save_interval)) {
m_localdb->endSave();
m_localdb->beginSave();
}
}
bool Client::loadMedia(const std::string &data, const std::string &filename,
- bool from_media_push)
+ bool from_media_push)
{
std::string name;
- const char *image_ext[] = {".png", ".jpg", ".bmp", ".tga", ".pcx", ".ppm", ".psd",
- ".wal", ".rgb", NULL};
+ const char *image_ext[] = {
+ ".png", ".jpg", ".bmp", ".tga",
+ ".pcx", ".ppm", ".psd", ".wal", ".rgb",
+ NULL
+ };
name = removeStringEnd(filename, image_ext);
if (!name.empty()) {
TRACESTREAM(<< "Client: Attempting to load image "
- << "file \"" << filename << "\"" << std::endl);
+ << "file \"" << filename << "\"" << std::endl);
io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
@@ -689,8 +700,8 @@ bool Client::loadMedia(const std::string &data, const std::string &filename,
// Read image
video::IImage *img = vdrv->createImageFromFile(rfile);
if (!img) {
- errorstream << "Client: Cannot create image from data of "
- << "file \"" << filename << "\"" << std::endl;
+ errorstream<<"Client: Cannot create image from data of "
+ <<"file \""<<filename<<"\""<<std::endl;
rfile->drop();
return false;
}
@@ -701,53 +712,62 @@ bool Client::loadMedia(const std::string &data, const std::string &filename,
return true;
}
- const char *sound_ext[] = {".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
- ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg", ".ogg", NULL};
+ const char *sound_ext[] = {
+ ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
+ ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
+ ".ogg", NULL
+ };
name = removeStringEnd(filename, sound_ext);
if (!name.empty()) {
TRACESTREAM(<< "Client: Attempting to load sound "
- << "file \"" << filename << "\"" << std::endl);
+ << "file \"" << filename << "\"" << std::endl);
return m_sound->loadSoundData(name, data);
}
- const char *model_ext[] = {".x", ".b3d", ".md2", ".obj", NULL};
+ const char *model_ext[] = {
+ ".x", ".b3d", ".md2", ".obj",
+ NULL
+ };
name = removeStringEnd(filename, model_ext);
if (!name.empty()) {
- verbosestream << "Client: Storing model into memory: "
- << "\"" << filename << "\"" << std::endl;
- if (m_mesh_data.count(filename))
- errorstream << "Multiple models with name \"" << filename.c_str()
- << "\" found; replacing previous model" << std::endl;
+ verbosestream<<"Client: Storing model into memory: "
+ <<"\""<<filename<<"\""<<std::endl;
+ if(m_mesh_data.count(filename))
+ errorstream<<"Multiple models with name \""<<filename.c_str()
+ <<"\" found; replacing previous model"<<std::endl;
m_mesh_data[filename] = data;
return true;
}
- const char *translate_ext[] = {".tr", NULL};
+ const char *translate_ext[] = {
+ ".tr", NULL
+ };
name = removeStringEnd(filename, translate_ext);
if (!name.empty()) {
if (from_media_push)
return false;
TRACESTREAM(<< "Client: Loading translation: "
- << "\"" << filename << "\"" << std::endl);
+ << "\"" << filename << "\"" << std::endl);
g_client_translations->loadTranslation(data);
return true;
}
- errorstream << "Client: Don't know how to load file \"" << filename << "\""
- << std::endl;
+ errorstream << "Client: Don't know how to load file \""
+ << filename << "\"" << std::endl;
return false;
}
// Virtual methods from con::PeerHandler
void Client::peerAdded(con::Peer *peer)
{
- infostream << "Client::peerAdded(): peer->id=" << peer->id << std::endl;
+ infostream << "Client::peerAdded(): peer->id="
+ << peer->id << std::endl;
}
void Client::deletingPeer(con::Peer *peer, bool timeout)
{
infostream << "Client::deletingPeer(): "
- "Server Peer is getting deleted "
- << "(timeout=" << timeout << ")" << std::endl;
+ "Server Peer is getting deleted "
+ << "(timeout=" << timeout << ")" << std::endl;
if (timeout) {
m_access_denied = true;
@@ -769,13 +789,12 @@ void Client::request_media(const std::vector<std::string> &file_requests)
writeU16(os, TOSERVER_REQUEST_MEDIA);
size_t file_requests_size = file_requests.size();
- FATAL_ERROR_IF(file_requests_size > 0xFFFF,
- "Unsupported number of file requests");
+ FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
// Packet dynamicly resized
NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
- pkt << (u16)(file_requests_size & 0xFFFF);
+ pkt << (u16) (file_requests_size & 0xFFFF);
for (const std::string &file_request : file_requests) {
pkt << file_request;
@@ -784,20 +803,23 @@ void Client::request_media(const std::vector<std::string> &file_requests)
Send(&pkt);
infostream << "Client: Sending media request list to server ("
- << file_requests.size() << " files. packet size)" << std::endl;
+ << file_requests.size() << " files. packet size)" << std::endl;
}
-void Client::initLocalMapSaving(
- const Address &address, const std::string &hostname, bool is_local_server)
+void Client::initLocalMapSaving(const Address &address,
+ const std::string &hostname,
+ bool is_local_server)
{
if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
return;
}
std::string world_path;
-#define set_world_path(hostname) \
- world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "server_" + \
- hostname + "_" + std::to_string(address.getPort());
+#define set_world_path(hostname) \
+ world_path = porting::path_user \
+ + DIR_DELIM + "worlds" \
+ + DIR_DELIM + "server_" \
+ + hostname + "_" + std::to_string(address.getPort());
set_world_path(hostname);
if (!fs::IsDir(world_path)) {
@@ -810,8 +832,7 @@ void Client::initLocalMapSaving(
m_localdb = new MapDatabaseSQLite3(world_path);
m_localdb->beginSave();
- actionstream << "Local map saving started, map will be saved at '" << world_path
- << "'" << std::endl;
+ actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
}
void Client::ReceiveAll()
@@ -819,13 +840,12 @@ void Client::ReceiveAll()
NetworkPacket pkt;
u64 start_ms = porting::getTimeMs();
const u64 budget = 100;
- for (;;) {
+ for(;;) {
// Limit time even if there would be huge amounts of data to
// process
if (porting::getTimeMs() > start_ms + budget) {
infostream << "Client::ReceiveAll(): "
- "Packet processing budget exceeded."
- << std::endl;
+ "Packet processing budget exceeded." << std::endl;
break;
}
@@ -836,15 +856,15 @@ void Client::ReceiveAll()
ProcessData(&pkt);
} catch (const con::InvalidIncomingDataException &e) {
infostream << "Client::ReceiveAll(): "
- "InvalidIncomingDataException: what()="
- << e.what() << std::endl;
+ "InvalidIncomingDataException: what()="
+ << e.what() << std::endl;
}
}
}
-inline void Client::handleCommand(NetworkPacket *pkt)
+inline void Client::handleCommand(NetworkPacket* pkt)
{
- const ToClientCommandHandler &opHandle = toClientCommandTable[pkt->getCommand()];
+ const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
(this->*opHandle.handler)(pkt);
}
@@ -853,10 +873,10 @@ inline void Client::handleCommand(NetworkPacket *pkt)
*/
void Client::ProcessData(NetworkPacket *pkt)
{
- ToClientCommand command = (ToClientCommand)pkt->getCommand();
+ ToClientCommand command = (ToClientCommand) pkt->getCommand();
u32 sender_peer_id = pkt->getPeerId();
- // infostream<<"Client: received command="<<command<<std::endl;
+ //infostream<<"Client: received command="<<command<<std::endl;
m_packetcounter.add((u16)command);
g_profiler->graphAdd("client_received_packets", 1);
@@ -864,16 +884,17 @@ void Client::ProcessData(NetworkPacket *pkt)
If this check is removed, be sure to change the queue
system to know the ids
*/
- if (sender_peer_id != PEER_ID_SERVER) {
+ if(sender_peer_id != PEER_ID_SERVER) {
infostream << "Client::ProcessData(): Discarding data not "
- "coming from server: peer_id="
- << sender_peer_id << std::endl;
+ "coming from server: peer_id=" << sender_peer_id
+ << std::endl;
return;
}
// Command must be handled into ToClientCommandHandler
if (command >= TOCLIENT_NUM_MSG_TYPES) {
- infostream << "Client: Ignoring unknown command " << command << std::endl;
+ infostream << "Client: Ignoring unknown command "
+ << command << std::endl;
return;
}
@@ -882,16 +903,15 @@ void Client::ProcessData(NetworkPacket *pkt)
* But we must use the new ToClientConnectionState in the future,
* as a byte mask
*/
- if (toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
+ if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
handleCommand(pkt);
return;
}
- if (m_server_ser_ver == SER_FMT_VER_INVALID) {
+ if(m_server_ser_ver == SER_FMT_VER_INVALID) {
infostream << "Client: Server serialization"
- " format invalid or not initialized."
- " Skipping incoming command="
- << command << std::endl;
+ " format invalid or not initialized."
+ " Skipping incoming command=" << command << std::endl;
return;
}
@@ -902,23 +922,25 @@ void Client::ProcessData(NetworkPacket *pkt)
handleCommand(pkt);
}
-void Client::Send(NetworkPacket *pkt)
+void Client::Send(NetworkPacket* pkt)
{
- m_con->Send(PEER_ID_SERVER, serverCommandFactoryTable[pkt->getCommand()].channel,
- pkt, serverCommandFactoryTable[pkt->getCommand()].reliable);
+ m_con->Send(PEER_ID_SERVER,
+ serverCommandFactoryTable[pkt->getCommand()].channel,
+ pkt,
+ serverCommandFactoryTable[pkt->getCommand()].reliable);
}
// Will fill up 12 + 12 + 4 + 4 + 4 bytes
void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
-{
- v3f pf = myplayer->getLegitPosition() * 100;
- v3f sf = myplayer->getLegitSpeed() * 100;
- s32 pitch = myplayer->getPitch() * 100;
- s32 yaw = myplayer->getYaw() * 100;
- u32 keyPressed = myplayer->keyPressed;
+{
+ v3f pf = myplayer->getLegitPosition() * 100;
+ v3f sf = myplayer->getLegitSpeed() * 100;
+ s32 pitch = myplayer->getPitch() * 100;
+ s32 yaw = myplayer->getYaw() * 100;
+ u32 keyPressed = myplayer->keyPressed;
// scaled by 80, so that pi can fit into a u8
- u8 fov = clientMap->getCameraFov() * 80;
- u8 wanted_range = MYMIN(255,
+ u8 fov = clientMap->getCameraFov() * 80;
+ u8 wanted_range = MYMIN(255,
std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
v3s32 position(pf.X, pf.Y, pf.Z);
@@ -938,12 +960,12 @@ void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *
*pkt << fov << wanted_range;
}
-void Client::interact(InteractAction action, const PointedThing &pointed)
+void Client::interact(InteractAction action, const PointedThing& pointed)
{
- if (m_state != LC_Ready) {
+ if(m_state != LC_Ready) {
errorstream << "Client::interact() "
- "Canceled (not connected)"
- << std::endl;
+ "Canceled (not connected)"
+ << std::endl;
return;
}
@@ -981,19 +1003,20 @@ void Client::deleteAuthData()
return;
switch (m_chosen_auth_mech) {
- case AUTH_MECHANISM_FIRST_SRP:
- break;
- case AUTH_MECHANISM_SRP:
- case AUTH_MECHANISM_LEGACY_PASSWORD:
- srp_user_delete((SRPUser *)m_auth_data);
- m_auth_data = NULL;
- break;
- case AUTH_MECHANISM_NONE:
- break;
+ case AUTH_MECHANISM_FIRST_SRP:
+ break;
+ case AUTH_MECHANISM_SRP:
+ case AUTH_MECHANISM_LEGACY_PASSWORD:
+ srp_user_delete((SRPUser *) m_auth_data);
+ m_auth_data = NULL;
+ break;
+ case AUTH_MECHANISM_NONE:
+ break;
}
m_chosen_auth_mech = AUTH_MECHANISM_NONE;
}
+
AuthMechanism Client::choseAuthMech(const u32 mechs)
{
if (mechs & AUTH_MECHANISM_SRP)
@@ -1015,8 +1038,8 @@ void Client::sendInit(const std::string &playerName)
// we don't support network compression yet
u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
- pkt << (u8)SER_FMT_VER_HIGHEST_READ << (u16)supp_comp_modes;
- pkt << (u16)CLIENT_PROTOCOL_VERSION_MIN << (u16)CLIENT_PROTOCOL_VERSION_MAX;
+ pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
+ pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
pkt << playerName;
Send(&pkt);
@@ -1039,47 +1062,47 @@ void Client::startAuth(AuthMechanism chosen_auth_mechanism)
m_chosen_auth_mech = chosen_auth_mechanism;
switch (chosen_auth_mechanism) {
- case AUTH_MECHANISM_FIRST_SRP: {
- // send srp verifier to server
- std::string verifier;
- std::string salt;
- generate_srp_verifier_and_salt(
- getPlayerName(), m_password, &verifier, &salt);
+ case AUTH_MECHANISM_FIRST_SRP: {
+ // send srp verifier to server
+ std::string verifier;
+ std::string salt;
+ generate_srp_verifier_and_salt(getPlayerName(), m_password,
+ &verifier, &salt);
- NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
- resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
-
- Send(&resp_pkt);
- break;
- }
- case AUTH_MECHANISM_SRP:
- case AUTH_MECHANISM_LEGACY_PASSWORD: {
- u8 based_on = 1;
+ NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
+ resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
- if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
- m_password = translate_password(getPlayerName(), m_password);
- based_on = 0;
+ Send(&resp_pkt);
+ break;
}
+ case AUTH_MECHANISM_SRP:
+ case AUTH_MECHANISM_LEGACY_PASSWORD: {
+ u8 based_on = 1;
+
+ if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
+ m_password = translate_password(getPlayerName(), m_password);
+ based_on = 0;
+ }
- std::string playername_u = lowercase(getPlayerName());
- m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
+ std::string playername_u = lowercase(getPlayerName());
+ m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
getPlayerName().c_str(), playername_u.c_str(),
- (const unsigned char *)m_password.c_str(),
+ (const unsigned char *) m_password.c_str(),
m_password.length(), NULL, NULL);
- char *bytes_A = 0;
- size_t len_A = 0;
- SRP_Result res = srp_user_start_authentication(
- (struct SRPUser *)m_auth_data, NULL, NULL, 0,
- (unsigned char **)&bytes_A, &len_A);
- FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
-
- NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
- resp_pkt << std::string(bytes_A, len_A) << based_on;
- Send(&resp_pkt);
- break;
- }
- case AUTH_MECHANISM_NONE:
- break; // not handled in this method
+ char *bytes_A = 0;
+ size_t len_A = 0;
+ SRP_Result res = srp_user_start_authentication(
+ (struct SRPUser *) m_auth_data, NULL, NULL, 0,
+ (unsigned char **) &bytes_A, &len_A);
+ FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
+
+ NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
+ resp_pkt << std::string(bytes_A, len_A) << based_on;
+ Send(&resp_pkt);
+ break;
+ }
+ case AUTH_MECHANISM_NONE:
+ break; // not handled in this method
}
}
@@ -1087,7 +1110,7 @@ void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
{
NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
- pkt << (u8)blocks.size();
+ pkt << (u8) blocks.size();
for (const v3s16 &block : blocks) {
pkt << block;
@@ -1099,7 +1122,7 @@ void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
{
NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
- pkt << (u8)blocks.size();
+ pkt << (u8) blocks.size();
for (const v3s16 &block : blocks)
pkt << block;
@@ -1113,7 +1136,7 @@ void Client::sendRemovedSounds(std::vector<s32> &soundList)
NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
- pkt << (u16)(server_ids & 0xFFFF);
+ pkt << (u16) (server_ids & 0xFFFF);
for (s32 sound_id : soundList)
pkt << sound_id;
@@ -1121,8 +1144,8 @@ void Client::sendRemovedSounds(std::vector<s32> &soundList)
Send(&pkt);
}
-void Client::sendNodemetaFields(
- v3s16 p, const std::string &formname, const StringMap &fields)
+void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
+ const StringMap &fields)
{
size_t fields_size = fields.size();
@@ -1130,7 +1153,7 @@ void Client::sendNodemetaFields(
NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
- pkt << p << formname << (u16)(fields_size & 0xFFFF);
+ pkt << p << formname << (u16) (fields_size & 0xFFFF);
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
@@ -1143,17 +1166,18 @@ void Client::sendNodemetaFields(
Send(&pkt);
}
-void Client::sendInventoryFields(const std::string &formname, const StringMap &fields)
+void Client::sendInventoryFields(const std::string &formname,
+ const StringMap &fields)
{
size_t fields_size = fields.size();
FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
- pkt << formname << (u16)(fields_size & 0xFFFF);
+ pkt << formname << (u16) (fields_size & 0xFFFF);
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
- const std::string &name = it->first;
+ const std::string &name = it->first;
const std::string &value = it->second;
pkt << name;
pkt.putLongString(value);
@@ -1172,7 +1196,7 @@ void Client::sendInventoryAction(InventoryAction *a)
std::string s = os.str();
NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
- pkt.putRawString(s.c_str(), s.size());
+ pkt.putRawString(s.c_str(),s.size());
Send(&pkt);
}
@@ -1182,9 +1206,8 @@ bool Client::canSendChatMessage() const
u32 now = time(NULL);
float time_passed = now - m_last_chat_message_sent;
- float virt_chat_message_allowance =
- m_chat_message_allowance +
- time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
+ float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
+ (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
if (virt_chat_message_allowance < 1.0f)
return false;
@@ -1200,26 +1223,22 @@ void Client::sendChatMessage(const std::wstring &message)
float time_passed = now - m_last_chat_message_sent;
m_last_chat_message_sent = time(NULL);
- m_chat_message_allowance +=
- time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
+ m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
m_chat_message_allowance -= 1.0f;
- NetworkPacket pkt(
- TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
+ NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
pkt << message;
Send(&pkt);
- } else if (m_out_chat_queue.size() < (u16)max_queue_size ||
- max_queue_size == -1) {
+ } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
m_out_chat_queue.push(message);
} else {
- infostream << "Could not queue chat message because maximum out chat "
- "queue size ("
- << max_queue_size << ") is reached." << std::endl;
+ infostream << "Could not queue chat message because maximum out chat queue size ("
+ << max_queue_size << ") is reached." << std::endl;
}
}
@@ -1228,8 +1247,8 @@ void Client::clearOutChatQueue()
m_out_chat_queue = std::queue<std::wstring>();
}
-void Client::sendChangePassword(
- const std::string &oldpassword, const std::string &newpassword)
+void Client::sendChangePassword(const std::string &oldpassword,
+ const std::string &newpassword)
{
LocalPlayer *player = m_env.getLocalPlayer();
if (player == NULL)
@@ -1241,6 +1260,7 @@ void Client::sendChangePassword(
startAuth(choseAuthMech(m_sudo_auth_methods));
}
+
void Client::sendDamage(u16 damage)
{
NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
@@ -1259,10 +1279,10 @@ void Client::sendReady()
NetworkPacket pkt(TOSERVER_CLIENT_READY,
1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
- pkt << (u8)VERSION_MAJOR << (u8)VERSION_MINOR << (u8)VERSION_PATCH << (u8)0
- << (u16)strlen(g_version_hash);
+ pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
+ << (u8) 0 << (u16) strlen(g_version_hash);
- pkt.putRawString(g_version_hash, (u16)strlen(g_version_hash));
+ pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
pkt << (u16)FORMSPEC_API_VERSION;
Send(&pkt);
}
@@ -1274,31 +1294,32 @@ void Client::sendPlayerPos(v3f pos)
return;
ClientMap &map = m_env.getClientMap();
- u8 camera_fov = map.getCameraFov();
+ u8 camera_fov = map.getCameraFov();
u8 wanted_range = map.getControl().wanted_range;
// Save bandwidth by only updating position when
// player is not dead and something changed
- // FIXME: This part causes breakages in mods like 3d_armor, and has been commented
- // for now if (m_activeobjects_received && player->isDead())
+ // FIXME: This part causes breakages in mods like 3d_armor, and has been commented for now
+ // if (m_activeobjects_received && player->isDead())
// return;
- if (player->last_position == pos &&
- player->last_speed == player->getLegitSpeed() &&
- player->last_pitch == player->getPitch() &&
- player->last_yaw == player->getYaw() &&
- player->last_keyPressed == player->keyPressed &&
- player->last_camera_fov == camera_fov &&
+ if (
+ player->last_position == pos &&
+ player->last_speed == player->getLegitSpeed() &&
+ player->last_pitch == player->getPitch() &&
+ player->last_yaw == player->getYaw() &&
+ player->last_keyPressed == player->keyPressed &&
+ player->last_camera_fov == camera_fov &&
player->last_wanted_range == wanted_range)
return;
- player->last_position = pos;
- player->last_speed = player->getLegitSpeed();
- player->last_pitch = player->getPitch();
- player->last_yaw = player->getYaw();
- player->last_keyPressed = player->keyPressed;
- player->last_camera_fov = camera_fov;
+ player->last_position = pos;
+ player->last_speed = player->getLegitSpeed();
+ player->last_pitch = player->getPitch();
+ player->last_yaw = player->getYaw();
+ player->last_keyPressed = player->keyPressed;
+ player->last_camera_fov = camera_fov;
player->last_wanted_range = wanted_range;
NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
@@ -1318,11 +1339,12 @@ void Client::sendPlayerPos()
void Client::removeNode(v3s16 p)
{
- std::map<v3s16, MapBlock *> modified_blocks;
+ std::map<v3s16, MapBlock*> modified_blocks;
try {
m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
- } catch (InvalidPositionException &e) {
+ }
+ catch(InvalidPositionException &e) {
}
for (const auto &modified_block : modified_blocks) {
@@ -1341,7 +1363,7 @@ MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position)
{
if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
- if ((u32)ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
+ if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
*is_valid_position = false;
return {};
}
@@ -1367,22 +1389,24 @@ v3s16 Client::CSMClampPos(v3s16 pos)
return pos;
v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
const int range = m_csm_restriction_noderange;
- return v3s16(core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
- core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
- core::clamp<int>(
- pos.Z, (int)ppos.Z - range, (int)ppos.Z + range));
+ return v3s16(
+ core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
+ core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
+ core::clamp<int>(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)
+ );
}
void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
{
- // TimeTaker timer1("Client::addNode()");
+ //TimeTaker timer1("Client::addNode()");
- std::map<v3s16, MapBlock *> modified_blocks;
+ std::map<v3s16, MapBlock*> modified_blocks;
try {
- // TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
+ //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
- } catch (InvalidPositionException &e) {
+ }
+ catch(InvalidPositionException &e) {
}
for (const auto &modified_block : modified_blocks) {
@@ -1426,28 +1450,35 @@ bool Client::updateWieldedItem()
return true;
}
-Inventory *Client::getInventory(const InventoryLocation &loc)
+Inventory* Client::getInventory(const InventoryLocation &loc)
{
- switch (loc.type) {
- case InventoryLocation::UNDEFINED: {
- } break;
+ switch(loc.type){
+ case InventoryLocation::UNDEFINED:
+ {}
+ break;
case InventoryLocation::PLAYER:
- case InventoryLocation::CURRENT_PLAYER: {
+ case InventoryLocation::CURRENT_PLAYER:
+ {
LocalPlayer *player = m_env.getLocalPlayer();
assert(player);
return &player->inventory;
- } break;
- case InventoryLocation::NODEMETA: {
+ }
+ break;
+ case InventoryLocation::NODEMETA:
+ {
NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
- if (!meta)
+ if(!meta)
return NULL;
return meta->getInventory();
- } break;
- case InventoryLocation::DETACHED: {
+ }
+ break;
+ case InventoryLocation::DETACHED:
+ {
if (m_detached_inventories.count(loc.name) == 0)
return NULL;
return m_detached_inventories[loc.name];
- } break;
+ }
+ break;
default:
FATAL_ERROR("Invalid inventory location type.");
break;
@@ -1494,11 +1525,13 @@ void Client::setCrack(int level, v3s16 pos)
m_crack_level = level;
m_crack_pos = pos;
- if (old_crack_level >= 0 && (level < 0 || pos != old_crack_pos)) {
+ if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
+ {
// remove old crack
addUpdateMeshTaskForNode(old_crack_pos, false, true);
}
- if (level >= 0 && (old_crack_level < 0 || pos != old_crack_pos)) {
+ if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
+ {
// add new crack
addUpdateMeshTaskForNode(pos, false, true);
}
@@ -1522,20 +1555,20 @@ bool Client::getChatMessage(std::wstring &res)
res = L"";
switch (chatMessage->type) {
- case CHATMESSAGE_TYPE_RAW:
- case CHATMESSAGE_TYPE_ANNOUNCE:
- case CHATMESSAGE_TYPE_SYSTEM:
- res = chatMessage->message;
- break;
- case CHATMESSAGE_TYPE_NORMAL: {
- if (!chatMessage->sender.empty())
- res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
- else
+ case CHATMESSAGE_TYPE_RAW:
+ case CHATMESSAGE_TYPE_ANNOUNCE:
+ case CHATMESSAGE_TYPE_SYSTEM:
res = chatMessage->message;
- break;
- }
- default:
- break;
+ break;
+ case CHATMESSAGE_TYPE_NORMAL: {
+ if (!chatMessage->sender.empty())
+ res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
+ else
+ res = chatMessage->message;
+ break;
+ }
+ default:
+ break;
}
delete chatMessage;
@@ -1570,18 +1603,19 @@ void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
{
- try {
+ try{
addUpdateMeshTask(blockpos, ack_to_server, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e){}
// Leading edge
- for (int i = 0; i < 6; i++) {
- try {
+ for (int i=0;i<6;i++)
+ {
+ try{
v3s16 p = blockpos + g_6dirs[i];
addUpdateMeshTask(p, false, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e){}
}
}
@@ -1589,56 +1623,56 @@ void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool ur
{
{
v3s16 p = nodepos;
- infostream << "Client::addUpdateMeshTaskForNode(): "
- << "(" << p.X << "," << p.Y << "," << p.Z << ")" << std::endl;
+ infostream<<"Client::addUpdateMeshTaskForNode(): "
+ <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
+ <<std::endl;
}
- v3s16 blockpos = getNodeBlockPos(nodepos);
+ v3s16 blockpos = getNodeBlockPos(nodepos);
v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
- try {
+ try{
addUpdateMeshTask(blockpos, ack_to_server, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e) {}
// Leading edge
- if (nodepos.X == blockpos_relative.X) {
- try {
- v3s16 p = blockpos + v3s16(-1, 0, 0);
+ if(nodepos.X == blockpos_relative.X){
+ try{
+ v3s16 p = blockpos + v3s16(-1,0,0);
addUpdateMeshTask(p, false, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e){}
}
- if (nodepos.Y == blockpos_relative.Y) {
- try {
- v3s16 p = blockpos + v3s16(0, -1, 0);
+ if(nodepos.Y == blockpos_relative.Y){
+ try{
+ v3s16 p = blockpos + v3s16(0,-1,0);
addUpdateMeshTask(p, false, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e){}
}
- if (nodepos.Z == blockpos_relative.Z) {
- try {
- v3s16 p = blockpos + v3s16(0, 0, -1);
+ if(nodepos.Z == blockpos_relative.Z){
+ try{
+ v3s16 p = blockpos + v3s16(0,0,-1);
addUpdateMeshTask(p, false, urgent);
- } catch (InvalidPositionException &e) {
}
+ catch(InvalidPositionException &e){}
}
}
void Client::updateAllMapBlocks()
{
- v3s16 currentBlock = getNodeBlockPos(
- floatToInt(m_env.getLocalPlayer()->getPosition(), BS));
-
+ v3s16 currentBlock = getNodeBlockPos(floatToInt(m_env.getLocalPlayer()->getPosition(), BS));
+
for (s16 X = currentBlock.X - 2; X <= currentBlock.X + 2; X++)
- for (s16 Y = currentBlock.Y - 2; Y <= currentBlock.Y + 2; Y++)
- for (s16 Z = currentBlock.Z - 2; Z <= currentBlock.Z + 2; Z++)
- addUpdateMeshTask(v3s16(X, Y, Z), false, true);
-
- std::map<v2s16, MapSector *> *sectors = m_env.getMap().getSectorsPtr();
-
+ for (s16 Y = currentBlock.Y - 2; Y <= currentBlock.Y + 2; Y++)
+ for (s16 Z = currentBlock.Z - 2; Z <= currentBlock.Z + 2; Z++)
+ addUpdateMeshTask(v3s16(X, Y, Z), false, true);
+
+ std::map<v2s16, MapSector*> *sectors = m_env.getMap().getSectorsPtr();
+
for (auto &sector_it : *sectors) {
MapSector *sector = sector_it.second;
MapBlockVect blocks;
@@ -1677,48 +1711,46 @@ float Client::mediaReceiveProgress()
return 1.0; // downloader only exists when not yet done
}
-typedef struct TextureUpdateArgs
-{
+typedef struct TextureUpdateArgs {
gui::IGUIEnvironment *guienv;
u64 last_time_ms;
u16 last_percent;
- const wchar_t *text_base;
+ const wchar_t* text_base;
ITextureSource *tsrc;
} TextureUpdateArgs;
void texture_update_progress(void *args, u32 progress, u32 max_progress)
{
- TextureUpdateArgs *targs = (TextureUpdateArgs *)args;
- u16 cur_percent = ceil(progress / (double)max_progress * 100.);
-
- // update the loading menu -- if neccessary
- bool do_draw = false;
- u64 time_ms = targs->last_time_ms;
- if (cur_percent != targs->last_percent) {
- targs->last_percent = cur_percent;
- time_ms = porting::getTimeMs();
- // only draw when the user will notice something:
- do_draw = (time_ms - targs->last_time_ms > 100);
- }
+ TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
+ u16 cur_percent = ceil(progress / (double) max_progress * 100.);
+
+ // update the loading menu -- if neccessary
+ bool do_draw = false;
+ u64 time_ms = targs->last_time_ms;
+ if (cur_percent != targs->last_percent) {
+ targs->last_percent = cur_percent;
+ time_ms = porting::getTimeMs();
+ // only draw when the user will notice something:
+ do_draw = (time_ms - targs->last_time_ms > 100);
+ }
- if (do_draw) {
- targs->last_time_ms = time_ms;
- std::basic_stringstream<wchar_t> strm;
- strm << targs->text_base << " " << targs->last_percent << "%...";
- RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc,
- 0, 72 + (u16)((18. / 100.) * (double)targs->last_percent),
- true);
- }
+ if (do_draw) {
+ targs->last_time_ms = time_ms;
+ std::basic_stringstream<wchar_t> strm;
+ strm << targs->text_base << " " << targs->last_percent << "%...";
+ RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
+ 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
+ }
}
void Client::afterContentReceived()
{
- infostream << "Client::afterContentReceived() started" << std::endl;
+ infostream<<"Client::afterContentReceived() started"<<std::endl;
assert(m_itemdef_received); // pre-condition
assert(m_nodedef_received); // pre-condition
- assert(mediaReceived()); // pre-condition
+ assert(mediaReceived()); // pre-condition
- const wchar_t *text = wgettext("Loading textures...");
+ const wchar_t* text = wgettext("Loading textures...");
// Clear cached pre-scaled 2D GUI images, as this cache
// might have images with the same name but different
@@ -1726,46 +1758,45 @@ void Client::afterContentReceived()
guiScalingCacheClear();
// Rebuild inherited images and recreate textures
- infostream << "- Rebuilding images and textures" << std::endl;
+ infostream<<"- Rebuilding images and textures"<<std::endl;
RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
m_tsrc->rebuildImagesAndTextures();
delete[] text;
// Rebuild shaders
- infostream << "- Rebuilding shaders" << std::endl;
+ infostream<<"- Rebuilding shaders"<<std::endl;
text = wgettext("Rebuilding shaders...");
RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
m_shsrc->rebuildShaders();
delete[] text;
// Update node aliases
- infostream << "- Updating node aliases" << std::endl;
+ infostream<<"- Updating node aliases"<<std::endl;
text = wgettext("Initializing nodes...");
RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
m_nodedef->updateAliases(m_itemdef);
for (const auto &path : getTextureDirs()) {
TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
- m_itemdef->applyTextureOverrides(
- override_source.getItemTextureOverrides());
+ m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
}
m_nodedef->setNodeRegistrationStatus(true);
m_nodedef->runNodeResolveCallbacks();
delete[] text;
// Update node textures and assign shaders to each tile
- infostream << "- Updating node textures" << std::endl;
+ infostream<<"- Updating node textures"<<std::endl;
TextureUpdateArgs tu_args;
tu_args.guienv = guienv;
tu_args.last_time_ms = porting::getTimeMs();
tu_args.last_percent = 0;
- tu_args.text_base = wgettext("Initializing nodes");
+ tu_args.text_base = wgettext("Initializing nodes");
tu_args.tsrc = m_tsrc;
m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
delete[] tu_args.text_base;
// Start mesh update thread after setting up content definitions
- infostream << "- Starting mesh update thread" << std::endl;
+ infostream<<"- Starting mesh update thread"<<std::endl;
m_mesh_update_thread.start();
m_state = LC_Ready;
@@ -1776,13 +1807,13 @@ void Client::afterContentReceived()
text = wgettext("Done!");
RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
- infostream << "Client::afterContentReceived() done" << std::endl;
+ infostream<<"Client::afterContentReceived() done"<<std::endl;
delete[] text;
}
float Client::getRTT()
{
- return m_con->getPeerStat(PEER_ID_SERVER, con::AVG_RTT);
+ return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
}
float Client::getCurRate()
@@ -1794,7 +1825,7 @@ float Client::getCurRate()
void Client::makeScreenshot()
{
irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
- irr::video::IImage *const raw_image = driver->createScreenShot();
+ irr::video::IImage* const raw_image = driver->createScreenShot();
if (!raw_image)
return;
@@ -1810,12 +1841,12 @@ void Client::makeScreenshot()
if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
screenshot_dir = g_settings->get("screenshot_path");
else
- screenshot_dir = porting::path_user + DIR_DELIM +
- g_settings->get("screenshot_path");
+ screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
- std::string filename_base = screenshot_dir + DIR_DELIM +
- std::string("screenshot_") +
- std::string(timetstamp_c);
+ std::string filename_base = screenshot_dir
+ + DIR_DELIM
+ + std::string("screenshot_")
+ + std::string(timetstamp_c);
std::string filename_ext = "." + g_settings->get("screenshot_format");
std::string filename;
@@ -1830,20 +1861,18 @@ void Client::makeScreenshot()
unsigned serial = 0;
while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
- filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") +
- filename_ext;
+ filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
std::ifstream tmp(filename.c_str());
if (!tmp.good())
- break; // File did not apparently exist, we'll go with it
+ break; // File did not apparently exist, we'll go with it
serial++;
}
if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
- infostream << "Could not find suitable filename for screenshot"
- << std::endl;
+ infostream << "Could not find suitable filename for screenshot" << std::endl;
} else {
- irr::video::IImage *const image = driver->createImage(
- video::ECF_R8G8B8, raw_image->getDimension());
+ irr::video::IImage* const image =
+ driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
if (image) {
raw_image->copyTo(image);
@@ -1881,32 +1910,32 @@ void Client::showMinimap(const bool show)
// IGameDef interface
// Under envlock
-IItemDefManager *Client::getItemDefManager()
+IItemDefManager* Client::getItemDefManager()
{
return m_itemdef;
}
-IWritableItemDefManager *Client::getWritableItemDefManager()
+IWritableItemDefManager* Client::getWritableItemDefManager()
{
return m_itemdef;
}
-const NodeDefManager *Client::getNodeDefManager()
+const NodeDefManager* Client::getNodeDefManager()
{
return m_nodedef;
}
-NodeDefManager *Client::getWritableNodeDefManager()
+NodeDefManager* Client::getWritableNodeDefManager()
{
return m_nodedef;
}
-ICraftDefManager *Client::getCraftDefManager()
+ICraftDefManager* Client::getCraftDefManager()
{
return NULL;
- // return m_craftdef;
+ //return m_craftdef;
}
-ITextureSource *Client::getTextureSource()
+ITextureSource* Client::getTextureSource()
{
return m_tsrc;
}
-IWritableShaderSource *Client::getShaderSource()
+IWritableShaderSource* Client::getShaderSource()
{
return m_shsrc;
}
@@ -1914,39 +1943,39 @@ IWritableShaderSource *Client::getShaderSource()
u16 Client::allocateUnknownNodeId(const std::string &name)
{
errorstream << "Client::allocateUnknownNodeId(): "
- << "Client cannot allocate node IDs" << std::endl;
+ << "Client cannot allocate node IDs" << std::endl;
FATAL_ERROR("Client allocated unknown node");
return CONTENT_IGNORE;
}
-ISoundManager *Client::getSoundManager()
+ISoundManager* Client::getSoundManager()
{
return m_sound;
}
-MtEventManager *Client::getEventManager()
+MtEventManager* Client::getEventManager()
{
return m_event;
}
-ParticleManager *Client::getParticleManager()
+ParticleManager* Client::getParticleManager()
{
return &m_particle_manager;
}
-scene::IAnimatedMesh *Client::getMesh(const std::string &filename, bool cache)
+scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
{
StringMap::const_iterator it = m_mesh_data.find(filename);
if (it == m_mesh_data.end()) {
- errorstream << "Client::getMesh(): Mesh not found: \"" << filename << "\""
- << std::endl;
+ errorstream << "Client::getMesh(): Mesh not found: \"" << filename
+ << "\"" << std::endl;
return NULL;
}
- const std::string &data = it->second;
+ const std::string &data = it->second;
// Create the mesh, remove it from cache and return it
// This allows unique vertex colors and other properties for each instance
Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
- io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
+ io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
*data_rw, data_rw.getSize(), filename.c_str());
FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
@@ -1958,7 +1987,7 @@ scene::IAnimatedMesh *Client::getMesh(const std::string &filename, bool cache)
return mesh;
}
-const std::string *Client::getModFile(std::string filename)
+const std::string* Client::getModFile(std::string filename)
{
// strip dir delimiter from beginning of path
auto pos = filename.find_first_of(':');
@@ -1979,7 +2008,7 @@ bool Client::registerModStorage(ModMetadata *storage)
{
if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
errorstream << "Unable to register same mod storage twice. Storage name: "
- << storage->getModName() << std::endl;
+ << storage->getModName() << std::endl;
return false;
}
@@ -1990,7 +2019,7 @@ bool Client::registerModStorage(ModMetadata *storage)
void Client::unregisterModStorage(const std::string &name)
{
std::unordered_map<std::string, ModMetadata *>::const_iterator it =
- m_mod_storages.find(name);
+ m_mod_storages.find(name);
if (it != m_mod_storages.end()) {
// Save unconditionaly on unregistration
it->second->save(getModStoragePath());
@@ -2040,20 +2069,19 @@ bool Client::sendModChannelMessage(const std::string &channel, const std::string
if (message.size() > STRING_MAX_LEN) {
warningstream << "ModChannel message too long, dropping before sending "
- << " (" << message.size() << " > " << STRING_MAX_LEN
- << ", channel: " << channel << ")" << std::endl;
+ << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
+ << channel << ")" << std::endl;
return false;
}
// @TODO: do some client rate limiting
- NetworkPacket pkt(
- TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
+ NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
pkt << channel << message;
Send(&pkt);
return true;
}
-ModChannel *Client::getModChannel(const std::string &channel)
+ModChannel* Client::getModChannel(const std::string &channel)
{
return m_modchannel_mgr->getModChannel(channel);
}
diff --git a/src/client/client.h b/src/client/client.h
index f00c331ab..7455d78dc 100644
--- a/src/client/client.h
+++ b/src/client/client.h
@@ -49,7 +49,7 @@ class IWritableTextureSource;
class IWritableShaderSource;
class ISoundManager;
class NodeDefManager;
-// class IWritableCraftDefManager;
+//class IWritableCraftDefManager;
class ClientMediaDownloader;
struct MapDrawControl;
class ModChannelMgr;
@@ -60,13 +60,11 @@ class Minimap;
struct MinimapMapblock;
class Camera;
class NetworkPacket;
-namespace con
-{
+namespace con {
class Connection;
}
-enum LocalClientState
-{
+enum LocalClientState {
LC_Created,
LC_Init,
LC_Ready
@@ -90,7 +88,10 @@ public:
n->second++;
}
- void clear() { m_packets.clear(); }
+ void clear()
+ {
+ m_packets.clear();
+ }
u32 sum() const;
void print(std::ostream &o) const;
@@ -110,21 +111,28 @@ public:
NOTE: Nothing is thread-safe here.
*/
- Client(const char *playername, const std::string &password,
- const std::string &address_name, MapDrawControl &control,
- IWritableTextureSource *tsrc, IWritableShaderSource *shsrc,
- IWritableItemDefManager *itemdef, NodeDefManager *nodedef,
- ISoundManager *sound, MtEventManager *event, bool ipv6,
- GameUI *game_ui);
+ Client(
+ const char *playername,
+ const std::string &password,
+ const std::string &address_name,
+ MapDrawControl &control,
+ IWritableTextureSource *tsrc,
+ IWritableShaderSource *shsrc,
+ IWritableItemDefManager *itemdef,
+ NodeDefManager *nodedef,
+ ISoundManager *sound,
+ MtEventManager *event,
+ bool ipv6,
+ GameUI *game_ui
+ );
~Client();
DISABLE_CLASS_COPY(Client);
// Load local mods into memory
void scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
- std::string mod_subpath);
- inline void scanModIntoMemory(
- const std::string &mod_name, const std::string &mod_path)
+ std::string mod_subpath);
+ inline void scanModIntoMemory(const std::string &mod_name, const std::string &mod_path)
{
scanModSubfolder(mod_name, mod_path, "");
}
@@ -134,6 +142,7 @@ public:
*/
void Stop();
+
bool isShutdown();
/*
@@ -154,58 +163,58 @@ public:
* Command Handlers
*/
- void handleCommand(NetworkPacket *pkt);
-
- void handleCommand_Null(NetworkPacket *pkt){};
- void handleCommand_Deprecated(NetworkPacket *pkt);
- void handleCommand_Hello(NetworkPacket *pkt);
- void handleCommand_AuthAccept(NetworkPacket *pkt);
- void handleCommand_AcceptSudoMode(NetworkPacket *pkt);
- void handleCommand_DenySudoMode(NetworkPacket *pkt);
- void handleCommand_AccessDenied(NetworkPacket *pkt);
- void handleCommand_RemoveNode(NetworkPacket *pkt);
- void handleCommand_AddNode(NetworkPacket *pkt);
+ void handleCommand(NetworkPacket* pkt);
+
+ void handleCommand_Null(NetworkPacket* pkt) {};
+ void handleCommand_Deprecated(NetworkPacket* pkt);
+ void handleCommand_Hello(NetworkPacket* pkt);
+ void handleCommand_AuthAccept(NetworkPacket* pkt);
+ void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
+ void handleCommand_DenySudoMode(NetworkPacket* pkt);
+ void handleCommand_AccessDenied(NetworkPacket* pkt);
+ void handleCommand_RemoveNode(NetworkPacket* pkt);
+ void handleCommand_AddNode(NetworkPacket* pkt);
void handleCommand_NodemetaChanged(NetworkPacket *pkt);
- void handleCommand_BlockData(NetworkPacket *pkt);
- void handleCommand_Inventory(NetworkPacket *pkt);
- void handleCommand_TimeOfDay(NetworkPacket *pkt);
+ void handleCommand_BlockData(NetworkPacket* pkt);
+ void handleCommand_Inventory(NetworkPacket* pkt);
+ void handleCommand_TimeOfDay(NetworkPacket* pkt);
void handleCommand_ChatMessage(NetworkPacket *pkt);
- void handleCommand_ActiveObjectRemoveAdd(NetworkPacket *pkt);
- void handleCommand_ActiveObjectMessages(NetworkPacket *pkt);
- void handleCommand_Movement(NetworkPacket *pkt);
+ void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
+ void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
+ void handleCommand_Movement(NetworkPacket* pkt);
void handleCommand_Fov(NetworkPacket *pkt);
- void handleCommand_HP(NetworkPacket *pkt);
- void handleCommand_Breath(NetworkPacket *pkt);
- void handleCommand_MovePlayer(NetworkPacket *pkt);
- void handleCommand_DeathScreen(NetworkPacket *pkt);
- void handleCommand_AnnounceMedia(NetworkPacket *pkt);
- void handleCommand_Media(NetworkPacket *pkt);
- void handleCommand_NodeDef(NetworkPacket *pkt);
- void handleCommand_ItemDef(NetworkPacket *pkt);
- void handleCommand_PlaySound(NetworkPacket *pkt);
- void handleCommand_StopSound(NetworkPacket *pkt);
+ void handleCommand_HP(NetworkPacket* pkt);
+ void handleCommand_Breath(NetworkPacket* pkt);
+ void handleCommand_MovePlayer(NetworkPacket* pkt);
+ void handleCommand_DeathScreen(NetworkPacket* pkt);
+ void handleCommand_AnnounceMedia(NetworkPacket* pkt);
+ void handleCommand_Media(NetworkPacket* pkt);
+ void handleCommand_NodeDef(NetworkPacket* pkt);
+ void handleCommand_ItemDef(NetworkPacket* pkt);
+ void handleCommand_PlaySound(NetworkPacket* pkt);
+ void handleCommand_StopSound(NetworkPacket* pkt);
void handleCommand_FadeSound(NetworkPacket *pkt);
- void handleCommand_Privileges(NetworkPacket *pkt);
- void handleCommand_InventoryFormSpec(NetworkPacket *pkt);
- void handleCommand_DetachedInventory(NetworkPacket *pkt);
- void handleCommand_ShowFormSpec(NetworkPacket *pkt);
- void handleCommand_SpawnParticle(NetworkPacket *pkt);
- void handleCommand_AddParticleSpawner(NetworkPacket *pkt);
- void handleCommand_DeleteParticleSpawner(NetworkPacket *pkt);
- void handleCommand_HudAdd(NetworkPacket *pkt);
- void handleCommand_HudRemove(NetworkPacket *pkt);
- void handleCommand_HudChange(NetworkPacket *pkt);
- void handleCommand_HudSetFlags(NetworkPacket *pkt);
- void handleCommand_HudSetParam(NetworkPacket *pkt);
- void handleCommand_HudSetSky(NetworkPacket *pkt);
- void handleCommand_HudSetSun(NetworkPacket *pkt);
- void handleCommand_HudSetMoon(NetworkPacket *pkt);
- void handleCommand_HudSetStars(NetworkPacket *pkt);
- void handleCommand_CloudParams(NetworkPacket *pkt);
- void handleCommand_OverrideDayNightRatio(NetworkPacket *pkt);
- void handleCommand_LocalPlayerAnimations(NetworkPacket *pkt);
- void handleCommand_EyeOffset(NetworkPacket *pkt);
- void handleCommand_UpdatePlayerList(NetworkPacket *pkt);
+ void handleCommand_Privileges(NetworkPacket* pkt);
+ void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
+ void handleCommand_DetachedInventory(NetworkPacket* pkt);
+ void handleCommand_ShowFormSpec(NetworkPacket* pkt);
+ void handleCommand_SpawnParticle(NetworkPacket* pkt);
+ void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
+ void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
+ void handleCommand_HudAdd(NetworkPacket* pkt);
+ void handleCommand_HudRemove(NetworkPacket* pkt);
+ void handleCommand_HudChange(NetworkPacket* pkt);
+ void handleCommand_HudSetFlags(NetworkPacket* pkt);
+ void handleCommand_HudSetParam(NetworkPacket* pkt);
+ void handleCommand_HudSetSky(NetworkPacket* pkt);
+ void handleCommand_HudSetSun(NetworkPacket* pkt);
+ void handleCommand_HudSetMoon(NetworkPacket* pkt);
+ void handleCommand_HudSetStars(NetworkPacket* pkt);
+ void handleCommand_CloudParams(NetworkPacket* pkt);
+ void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
+ void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
+ void handleCommand_EyeOffset(NetworkPacket* pkt);
+ void handleCommand_UpdatePlayerList(NetworkPacket* pkt);
void handleCommand_ModChannelMsg(NetworkPacket *pkt);
void handleCommand_ModChannelSignal(NetworkPacket *pkt);
void handleCommand_SrpBytesSandB(NetworkPacket *pkt);
@@ -216,30 +225,31 @@ public:
void ProcessData(NetworkPacket *pkt);
- void Send(NetworkPacket *pkt);
+ void Send(NetworkPacket* pkt);
void interact(InteractAction action, const PointedThing &pointed);
- void sendNodemetaFields(
- v3s16 p, const std::string &formname, const StringMap &fields);
- void sendInventoryFields(const std::string &formname, const StringMap &fields);
+ void sendNodemetaFields(v3s16 p, const std::string &formname,
+ const StringMap &fields);
+ void sendInventoryFields(const std::string &formname,
+ const StringMap &fields);
void sendInventoryAction(InventoryAction *a);
void sendChatMessage(const std::wstring &message);
void clearOutChatQueue();
- void sendChangePassword(
- const std::string &oldpassword, const std::string &newpassword);
+ void sendChangePassword(const std::string &oldpassword,
+ const std::string &newpassword);
void sendDamage(u16 damage);
void sendRespawn();
void sendReady();
- ClientEnvironment &getEnv() { return m_env; }
+ ClientEnvironment& getEnv() { return m_env; }
ITextureSource *tsrc() { return getTextureSource(); }
ISoundManager *sound() { return getSoundManager(); }
static const std::string &getBuiltinLuaPath();
static const std::string &getClientModsLuaPath();
const std::vector<ModSpec> &getMods() const override;
- const ModSpec *getModSpec(const std::string &modname) const override;
+ const ModSpec* getModSpec(const std::string &modname) const override;
// Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
void removeNode(v3s16 p);
@@ -258,7 +268,7 @@ public:
bool updateWieldedItem();
/* InventoryManager interface */
- Inventory *getInventory(const InventoryLocation &loc) override;
+ Inventory* getInventory(const InventoryLocation &loc) override;
void inventoryAction(InventoryAction *a) override;
// Send the item number 'item' as player item to the server
@@ -278,40 +288,29 @@ public:
u16 getHP();
bool checkPrivilege(const std::string &priv) const
- {
- return g_settings->getBool("priv_bypass")
- ? true
- : (m_privileges.count(priv) != 0);
- }
+ { return g_settings->getBool("priv_bypass") ? true : (m_privileges.count(priv) != 0); }
const std::unordered_set<std::string> &getPrivilegeList() const
- {
- return m_privileges;
- }
+ { return m_privileges; }
bool getChatMessage(std::wstring &message);
- void typeChatMessage(const std::wstring &message);
+ void typeChatMessage(const std::wstring& message);
- u64 getMapSeed() { return m_map_seed; }
+ u64 getMapSeed(){ return m_map_seed; }
- void addUpdateMeshTask(
- v3s16 blockpos, bool ack_to_server = false, bool urgent = false);
+ void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
// Including blocks at appropriate edges
- void addUpdateMeshTaskWithEdge(
- v3s16 blockpos, bool ack_to_server = false, bool urgent = false);
- void addUpdateMeshTaskForNode(
- v3s16 nodepos, bool ack_to_server = false, bool urgent = false);
+ void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
+ void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
void updateAllMapBlocks();
void updateCameraOffset(v3s16 camera_offset)
- {
- m_mesh_update_thread.m_camera_offset = camera_offset;
- }
+ { m_mesh_update_thread.m_camera_offset = camera_offset; }
bool hasClientEvents() const { return !m_client_event_queue.empty(); }
// Get event from queue. If queue is empty, it triggers an assertion failure.
- ClientEvent *getClientEvent();
+ ClientEvent * getClientEvent();
bool accessDenied() const { return m_access_denied; }
@@ -327,12 +326,17 @@ public:
// disconnect client when CSM failed.
const std::string &accessDeniedReason() const { return m_access_denied_reason; }
- const bool itemdefReceived() const { return m_itemdef_received; }
- const bool nodedefReceived() const { return m_nodedef_received; }
- const bool mediaReceived() const { return !m_media_downloader; }
- const bool activeObjectsReceived() const { return m_activeobjects_received; }
+ const bool itemdefReceived() const
+ { return m_itemdef_received; }
+ const bool nodedefReceived() const
+ { return m_nodedef_received; }
+ const bool mediaReceived() const
+ { return !m_media_downloader; }
+ const bool activeObjectsReceived() const
+ { return m_activeobjects_received; }
- u16 getProtoVersion() { return m_proto_ver; }
+ u16 getProtoVersion()
+ { return m_proto_ver; }
bool connectedToServer();
void confirmRegistration();
@@ -346,29 +350,28 @@ public:
float getRTT();
float getCurRate();
- Minimap *getMinimap() { return m_minimap; }
- void setCamera(Camera *camera) { m_camera = camera; }
+ Minimap* getMinimap() { return m_minimap; }
+ void setCamera(Camera* camera) { m_camera = camera; }
- Camera *getCamera() { return m_camera; }
+ Camera* getCamera () { return m_camera; }
bool shouldShowMinimap() const;
// IGameDef interface
- IItemDefManager *getItemDefManager() override;
- IWritableItemDefManager *getWritableItemDefManager() override;
- const NodeDefManager *getNodeDefManager() override;
- NodeDefManager *getWritableNodeDefManager() override;
- ICraftDefManager *getCraftDefManager() override;
- ITextureSource *getTextureSource();
- virtual IWritableShaderSource *getShaderSource();
+ IItemDefManager* getItemDefManager() override;
+ IWritableItemDefManager* getWritableItemDefManager() override;
+ const NodeDefManager* getNodeDefManager() override;
+ NodeDefManager* getWritableNodeDefManager() override;
+ ICraftDefManager* getCraftDefManager() override;
+ ITextureSource* getTextureSource();
+ virtual IWritableShaderSource* getShaderSource();
u16 allocateUnknownNodeId(const std::string &name) override;
- virtual ISoundManager *getSoundManager();
- MtEventManager *getEventManager();
- virtual ParticleManager *getParticleManager();
- bool checkLocalPrivilege(const std::string &priv) { return checkPrivilege(priv); }
- virtual scene::IAnimatedMesh *getMesh(
- const std::string &filename, bool cache = false);
- const std::string *getModFile(std::string filename);
+ virtual ISoundManager* getSoundManager();
+ MtEventManager* getEventManager();
+ virtual ParticleManager* getParticleManager();
+ bool checkLocalPrivilege(const std::string &priv){ return checkPrivilege(priv); }
+ virtual scene::IAnimatedMesh* getMesh(const std::string &filename, bool cache = false);
+ const std::string* getModFile(std::string filename);
std::string getModStoragePath() const override;
bool registerModStorage(ModMetadata *meta) override;
@@ -377,7 +380,7 @@ public:
// The following set of functions is used by ClientMediaDownloader
// Insert a media file appropriately into the appropriate manager
bool loadMedia(const std::string &data, const std::string &filename,
- bool from_media_push = false);
+ bool from_media_push = false);
// Send a request for conventional media transfer
void request_media(const std::vector<std::string> &file_requests);
@@ -385,7 +388,10 @@ public:
void makeScreenshot();
- inline void pushToChatQueue(ChatMessage *cec) { m_chat_queue.push(cec); }
+ inline void pushToChatQueue(ChatMessage *cec)
+ {
+ m_chat_queue.push(cec);
+ }
ClientScripting *getScript() { return m_script; }
const bool modsLoaded() const { return m_mods_loaded; }
@@ -396,17 +402,26 @@ public:
const Address getServerAddress();
- const std::string &getAddressName() const { return m_address_name; }
+ const std::string &getAddressName() const
+ {
+ return m_address_name;
+ }
- inline u64 getCSMRestrictionFlags() const { return m_csm_restriction_flags; }
+ inline u64 getCSMRestrictionFlags() const
+ {
+ return m_csm_restriction_flags;
+ }
inline bool checkCSMRestrictionFlag(CSMRestrictionFlags flag) const
{
- // return m_csm_restriction_flags & flag;
+ //return m_csm_restriction_flags & flag;
return false;
}
- u32 getCSMNodeRangeLimit() const { return m_csm_restriction_noderange; }
+ u32 getCSMNodeRangeLimit() const
+ {
+ return m_csm_restriction_noderange;
+ }
inline std::unordered_map<u32, u32> &getHUDTranslationMap()
{
@@ -415,19 +430,19 @@ public:
bool joinModChannel(const std::string &channel) override;
bool leaveModChannel(const std::string &channel) override;
- bool sendModChannelMessage(
- const std::string &channel, const std::string &message) override;
+ bool sendModChannelMessage(const std::string &channel,
+ const std::string &message) override;
ModChannel *getModChannel(const std::string &channel) override;
const std::string &getFormspecPrepend() const
{
return m_env.getLocalPlayer()->formspec_prepend;
}
-
+
void sendPlayerPos(v3f pos);
void sendPlayerPos();
MeshUpdateThread m_mesh_update_thread;
-
+
private:
void loadMods();
bool checkBuiltinIntegrity();
@@ -436,11 +451,13 @@ private:
void peerAdded(con::Peer *peer) override;
void deletingPeer(con::Peer *peer, bool timeout) override;
- void initLocalMapSaving(const Address &address, const std::string &hostname,
+ void initLocalMapSaving(const Address &address,
+ const std::string &hostname,
bool is_local_server);
void ReceiveAll();
+
void deleteAuthData();
// helper method shared with clientpackethandler
static AuthMechanism choseAuthMech(const u32 mechs);
@@ -453,7 +470,8 @@ private:
void sendRemovedSounds(std::vector<s32> &soundList);
// Helper function
- inline std::string getPlayerName() { return m_env.getLocalPlayer()->getName(); }
+ inline std::string getPlayerName()
+ { return m_env.getLocalPlayer()->getName(); }
bool canSendChatMessage() const;
@@ -470,6 +488,7 @@ private:
ISoundManager *m_sound;
MtEventManager *m_event;
+
ClientEnvironment m_env;
ParticleManager m_particle_manager;
std::unique_ptr<con::Connection> m_con;
@@ -497,8 +516,8 @@ private:
int m_crack_level = -1;
v3s16 m_crack_pos;
// 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
- // s32 m_daynight_i;
- // u32 m_daynight_ratio;
+ //s32 m_daynight_i;
+ //u32 m_daynight_ratio;
std::queue<std::wstring> m_out_chat_queue;
u32 m_last_chat_message_sent;
float m_chat_message_allowance = 5.0f;
@@ -557,7 +576,7 @@ private:
// Detached inventories
// key = name
- std::unordered_map<std::string, Inventory *> m_detached_inventories;
+ std::unordered_map<std::string, Inventory*> m_detached_inventories;
// Storage for mesh data for creating multiple instances of the same mesh
StringMap m_mesh_data;
diff --git a/src/client/clientenvironment.cpp b/src/client/clientenvironment.cpp
index 2f95177f3..3f82bd316 100644
--- a/src/client/clientenvironment.cpp
+++ b/src/client/clientenvironment.cpp
@@ -45,7 +45,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class CAOShaderConstantSetter : public IShaderConstantSetter
{
public:
- CAOShaderConstantSetter() : m_emissive_color_setting("emissiveColor") {}
+ CAOShaderConstantSetter():
+ m_emissive_color_setting("emissiveColor")
+ {}
~CAOShaderConstantSetter() override = default;
@@ -59,15 +61,15 @@ public:
video::SColorf emissive_color(m_emissive_color);
float as_array[4] = {
- emissive_color.r,
- emissive_color.g,
- emissive_color.b,
- emissive_color.a,
+ emissive_color.r,
+ emissive_color.g,
+ emissive_color.b,
+ emissive_color.a,
};
m_emissive_color_setting.set(as_array, services);
}
- void onSetMaterial(const video::SMaterial &material) override
+ void onSetMaterial(const video::SMaterial& material) override
{
m_emissive_color = material.EmissiveColor;
}
@@ -80,19 +82,25 @@ private:
class CAOShaderConstantSetterFactory : public IShaderConstantSetterFactory
{
public:
- CAOShaderConstantSetterFactory() {}
+ CAOShaderConstantSetterFactory()
+ {}
- virtual IShaderConstantSetter *create() { return new CAOShaderConstantSetter(); }
+ virtual IShaderConstantSetter* create()
+ {
+ return new CAOShaderConstantSetter();
+ }
};
/*
ClientEnvironment
*/
-ClientEnvironment::ClientEnvironment(
- ClientMap *map, ITextureSource *texturesource, Client *client) :
- Environment(client),
- m_map(map), m_texturesource(texturesource), m_client(client)
+ClientEnvironment::ClientEnvironment(ClientMap *map,
+ ITextureSource *texturesource, Client *client):
+ Environment(client),
+ m_map(map),
+ m_texturesource(texturesource),
+ m_client(client)
{
auto *shdrsrc = m_client->getShaderSource();
shdrsrc->addShaderConstantSetterFactory(new CAOShaderConstantSetterFactory());
@@ -112,12 +120,12 @@ ClientEnvironment::~ClientEnvironment()
delete m_local_player;
}
-Map &ClientEnvironment::getMap()
+Map & ClientEnvironment::getMap()
{
return *m_map;
}
-ClientMap &ClientEnvironment::getClientMap()
+ClientMap & ClientEnvironment::getClientMap()
{
return *m_map;
}
@@ -127,7 +135,8 @@ void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
/*
It is a failure if already is a local player
*/
- FATAL_ERROR_IF(m_local_player != NULL, "Local player already allocated");
+ FATAL_ERROR_IF(m_local_player != NULL,
+ "Local player already allocated");
m_local_player = player;
}
@@ -157,21 +166,21 @@ void ClientEnvironment::step(float dtime)
/*
Maximum position increment
*/
- // f32 position_max_increment = 0.05*BS;
- f32 position_max_increment = 0.1 * BS;
+ //f32 position_max_increment = 0.05*BS;
+ f32 position_max_increment = 0.1*BS;
// Maximum time increment (for collision detection etc)
// time = distance / speed
f32 dtime_max_increment = 1;
- if (player_speed > 0.001)
+ if(player_speed > 0.001)
dtime_max_increment = position_max_increment / player_speed;
// Maximum time increment is 10ms or lower
- if (dtime_max_increment > 0.01)
+ if(dtime_max_increment > 0.01)
dtime_max_increment = 0.01;
// Don't allow overly huge dtime
- if (dtime > 0.5)
+ if(dtime > 0.5)
dtime = 0.5;
f32 dtime_downcount = dtime;
@@ -181,19 +190,23 @@ void ClientEnvironment::step(float dtime)
*/
u32 loopcount = 0;
- do {
+ do
+ {
loopcount++;
f32 dtime_part;
- if (dtime_downcount > dtime_max_increment) {
+ if(dtime_downcount > dtime_max_increment)
+ {
dtime_part = dtime_max_increment;
dtime_downcount -= dtime_part;
- } else {
+ }
+ else
+ {
dtime_part = dtime_downcount;
/*
- Setting this to 0 (no -=dtime_part) disables an infinite
- loop when dtime_part is so small that dtime_downcount -=
- dtime_part does nothing
+ Setting this to 0 (no -=dtime_part) disables an infinite loop
+ when dtime_part is so small that dtime_downcount -= dtime_part
+ does nothing
*/
dtime_downcount = 0;
}
@@ -207,40 +220,33 @@ void ClientEnvironment::step(float dtime)
lplayer->applyControl(dtime_part, this);
// Apply physics
- if (!free_move && !is_climbing &&
- !g_settings->getBool("freecam")) {
+ if (!free_move && !is_climbing && ! g_settings->getBool("freecam")) {
// Gravity
v3f speed = lplayer->getSpeed();
if (!lplayer->in_liquid)
speed.Y -= lplayer->movement_gravity *
- lplayer->physics_override_gravity *
- dtime_part * 2.0f;
+ lplayer->physics_override_gravity * dtime_part * 2.0f;
// Liquid floating / sinking
if (lplayer->in_liquid && !lplayer->swimming_vertical &&
!lplayer->swimming_pitch)
- speed.Y -= lplayer->movement_liquid_sink *
- dtime_part * 2.0f;
+ speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
// Liquid resistance
if (lplayer->in_liquid_stable || lplayer->in_liquid) {
- // How much the node's viscosity blocks movement,
- // ranges between 0 and 1. Should match the scale
- // at which viscosity increase affects other
- // liquid attributes.
+ // How much the node's viscosity blocks movement, ranges
+ // between 0 and 1. Should match the scale at which viscosity
+ // increase affects other liquid attributes.
static const f32 viscosity_factor = 0.3f;
- v3f d_wanted = -speed /
- lplayer->movement_liquid_fluidity;
+ v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
f32 dl = d_wanted.getLength();
if (dl > lplayer->movement_liquid_fluidity_smooth)
dl = lplayer->movement_liquid_fluidity_smooth;
- dl *= (lplayer->liquid_viscosity *
- viscosity_factor) +
- (1 - viscosity_factor);
- v3f d = d_wanted.normalize() *
- (dl * dtime_part * 100.0f);
+ dl *= (lplayer->liquid_viscosity * viscosity_factor) +
+ (1 - viscosity_factor);
+ v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
speed += d;
}
@@ -252,15 +258,14 @@ void ClientEnvironment::step(float dtime)
This also does collision detection.
*/
lplayer->move(dtime_part, this, position_max_increment,
- &player_collisions);
+ &player_collisions);
}
} while (dtime_downcount > 0.001);
bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
for (const CollisionInfo &info : player_collisions) {
- v3f speed_diff = info.new_speed - info.old_speed;
- ;
+ v3f speed_diff = info.new_speed - info.old_speed;;
// Handle only fall damage
// (because otherwise walking against something in fast_move kills you)
if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
@@ -268,12 +273,12 @@ void ClientEnvironment::step(float dtime)
// Get rid of other components
speed_diff.X = 0;
speed_diff.Z = 0;
- f32 pre_factor = 1; // 1 hp per node/s
- f32 tolerance = BS * 14; // 5 without damage
- f32 post_factor = 1; // 1 hp per node/s
+ f32 pre_factor = 1; // 1 hp per node/s
+ f32 tolerance = BS*14; // 5 without damage
+ f32 post_factor = 1; // 1 hp per node/s
if (info.type == COLLISION_NODE) {
- const ContentFeatures &f = m_client->ndef()->get(
- m_map->getNode(info.node_p));
+ const ContentFeatures &f = m_client->ndef()->
+ get(m_map->getNode(info.node_p));
// Determine fall damage multiplier
int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
pre_factor = 1.0f + (float)addp / 100.0f;
@@ -284,8 +289,8 @@ void ClientEnvironment::step(float dtime)
u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
if (damage != 0) {
damageLocalPlayer(damage, true);
- m_client->getEventManager()->put(new SimpleTriggerEvent(
- MtEvent::PLAYER_FALLING_DAMAGE));
+ m_client->getEventManager()->put(
+ new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
}
}
}
@@ -314,8 +319,7 @@ void ClientEnvironment::step(float dtime)
*/
bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
- auto cb_state = [this, dtime, update_lighting, day_night_ratio](
- ClientActiveObject *cao) {
+ auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
// Step object
cao->step(dtime, this);
@@ -333,10 +337,11 @@ void ClientEnvironment::step(float dtime)
ClientSimpleObject *simple = *i;
simple->step(dtime);
- if (simple->m_to_be_removed) {
+ if(simple->m_to_be_removed) {
delete simple;
i = m_simple_objects.erase(i);
- } else {
+ }
+ else {
++i;
}
}
@@ -347,18 +352,20 @@ void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
m_simple_objects.push_back(simple);
}
-GenericCAO *ClientEnvironment::getGenericCAO(u16 id)
+GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
{
ClientActiveObject *obj = getActiveObject(id);
if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
- return (GenericCAO *)obj;
+ return (GenericCAO*) obj;
return NULL;
}
-bool isFreeClientActiveObjectId(const u16 id, ClientActiveObjectMap &objects)
+bool isFreeClientActiveObjectId(const u16 id,
+ ClientActiveObjectMap &objects)
{
return id != 0 && objects.find(id) == objects.end();
+
}
u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
@@ -366,8 +373,8 @@ u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
// try to reuse id's as late as possible
static u16 last_used_id = 0;
u16 startid = last_used_id;
- for (;;) {
- last_used_id++;
+ for(;;) {
+ last_used_id ++;
if (isFreeClientActiveObjectId(last_used_id, objects))
return last_used_id;
@@ -389,27 +396,33 @@ u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
return object->getId();
}
-void ClientEnvironment::addActiveObject(u16 id, u8 type, const std::string &init_data)
+void ClientEnvironment::addActiveObject(u16 id, u8 type,
+ const std::string &init_data)
{
- ClientActiveObject *obj = ClientActiveObject::create(
- (ActiveObjectType)type, m_client, this);
- if (obj == NULL) {
- infostream << "ClientEnvironment::addActiveObject(): "
- << "id=" << id << " type=" << type
- << ": Couldn't create object" << std::endl;
+ ClientActiveObject* obj =
+ ClientActiveObject::create((ActiveObjectType) type, m_client, this);
+ if(obj == NULL)
+ {
+ infostream<<"ClientEnvironment::addActiveObject(): "
+ <<"id="<<id<<" type="<<type<<": Couldn't create object"
+ <<std::endl;
return;
}
obj->setId(id);
- try {
+ try
+ {
obj->initialize(init_data);
- } catch (SerializationError &e) {
- errorstream << "ClientEnvironment::addActiveObject():"
- << " id=" << id << " type=" << type
- << ": SerializationError in initialize(): " << e.what()
- << ": init_data=" << serializeJsonString(init_data)
- << std::endl;
+ }
+ catch(SerializationError &e)
+ {
+ errorstream<<"ClientEnvironment::addActiveObject():"
+ <<" id="<<id<<" type="<<type
+ <<": SerializationError in initialize(): "
+ <<e.what()
+ <<": init_data="<<serializeJsonString(init_data)
+ <<std::endl;
}
u16 new_id = addActiveObject(obj);
@@ -425,6 +438,7 @@ void ClientEnvironment::addActiveObject(u16 id, u8 type, const std::string &init
}
}
+
void ClientEnvironment::removeActiveObject(u16 id)
{
// Get current attachment childs to detach them visually
@@ -446,18 +460,18 @@ void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &da
ClientActiveObject *obj = getActiveObject(id);
if (obj == NULL) {
infostream << "ClientEnvironment::processActiveObjectMessage():"
- << " got message for id=" << id << ", which doesn't exist."
- << std::endl;
+ << " got message for id=" << id << ", which doesn't exist."
+ << std::endl;
return;
}
try {
obj->processMessage(data);
} catch (SerializationError &e) {
- errorstream << "ClientEnvironment::processActiveObjectMessage():"
- << " id=" << id << " type=" << obj->getType()
- << " SerializationError in processMessage(): " << e.what()
- << std::endl;
+ errorstream<<"ClientEnvironment::processActiveObjectMessage():"
+ << " id=" << id << " type=" << obj->getType()
+ << " SerializationError in processMessage(): " << e.what()
+ << std::endl;
}
}
@@ -499,12 +513,12 @@ ClientEnvEvent ClientEnvironment::getClientEnvEvent()
}
void ClientEnvironment::getSelectedActiveObjects(
- const core::line3d<f32> &shootline_on_map,
- std::vector<PointedThing> &objects)
+ const core::line3d<f32> &shootline_on_map,
+ std::vector<PointedThing> &objects)
{
std::vector<DistanceSortedActiveObject> allObjects;
- getActiveObjects(shootline_on_map.start, shootline_on_map.getLength() + 10.0f,
- allObjects);
+ getActiveObjects(shootline_on_map.start,
+ shootline_on_map.getLength() + 10.0f, allObjects);
const v3f line_vector = shootline_on_map.getVector();
for (const auto &allObject : allObjects) {
@@ -514,17 +528,15 @@ void ClientEnvironment::getSelectedActiveObjects(
continue;
const v3f &pos = obj->getPosition();
- aabb3f offsetted_box(
- selection_box.MinEdge + pos, selection_box.MaxEdge + pos);
+ aabb3f offsetted_box(selection_box.MinEdge + pos,
+ selection_box.MaxEdge + pos);
v3f current_intersection;
v3s16 current_normal;
if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
- &current_intersection, &current_normal)) {
- objects.emplace_back((s16)obj->getId(), current_intersection,
- current_normal,
- (current_intersection - shootline_on_map.start)
- .getLengthSQ());
+ &current_intersection, &current_normal)) {
+ objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
+ (current_intersection - shootline_on_map.start).getLengthSQ());
}
}
}
diff --git a/src/client/clientenvironment.h b/src/client/clientenvironment.h
index a24ea209a..52d999c99 100644
--- a/src/client/clientenvironment.h
+++ b/src/client/clientenvironment.h
@@ -49,27 +49,25 @@ enum ClientEnvEventType
struct ClientEnvEvent
{
ClientEnvEventType type;
- union
- {
- // struct{
+ union {
+ //struct{
//} none;
- struct
- {
+ struct{
u16 amount;
bool send_to_server;
} player_damage;
};
};
-typedef std::unordered_map<u16, ClientActiveObject *> ClientActiveObjectMap;
+typedef std::unordered_map<u16, ClientActiveObject*> ClientActiveObjectMap;
class ClientEnvironment : public Environment
{
public:
ClientEnvironment(ClientMap *map, ITextureSource *texturesource, Client *client);
~ClientEnvironment();
- Map &getMap();
- ClientMap &getClientMap();
+ Map & getMap();
+ ClientMap & getClientMap();
Client *getGameDef() { return m_client; }
void setScript(ClientScripting *script) { m_script = script; }
@@ -89,13 +87,13 @@ public:
ActiveObjects
*/
- GenericCAO *getGenericCAO(u16 id);
- ClientActiveObject *getActiveObject(u16 id)
+ GenericCAO* getGenericCAO(u16 id);
+ ClientActiveObject* getActiveObject(u16 id)
{
return m_ao_manager.getActiveObject(id);
}
-
- std::unordered_map<u16, ClientActiveObject *> getAllActiveObjects()
+
+ std::unordered_map<u16, ClientActiveObject*> getAllActiveObjects()
{
return m_ao_manager.getAllActiveObjects();
}
@@ -119,7 +117,7 @@ public:
Callbacks for activeobjects
*/
- void damageLocalPlayer(u16 damage, bool handle_hp = true);
+ void damageLocalPlayer(u16 damage, bool handle_hp=true);
/*
Client likes to call these
@@ -127,7 +125,7 @@ public:
// Get all nearby objects
void getActiveObjects(const v3f &origin, f32 max_d,
- std::vector<DistanceSortedActiveObject> &dest)
+ std::vector<DistanceSortedActiveObject> &dest)
{
return m_ao_manager.getActiveObjects(origin, max_d, dest);
}
@@ -137,18 +135,17 @@ public:
// Get event from queue. If queue is empty, it triggers an assertion failure.
ClientEnvEvent getClientEnvEvent();
- virtual void getSelectedActiveObjects(const core::line3d<f32> &shootline_on_map,
- std::vector<PointedThing> &objects);
+ virtual void getSelectedActiveObjects(
+ const core::line3d<f32> &shootline_on_map,
+ std::vector<PointedThing> &objects
+ );
const std::list<std::string> &getPlayerNames() { return m_player_names; }
void addPlayerName(const std::string &name) { m_player_names.push_back(name); }
void removePlayerName(const std::string &name) { m_player_names.remove(name); }
void updateCameraOffset(const v3s16 &camera_offset)
- {
- m_camera_offset = camera_offset;
- }
+ { m_camera_offset = camera_offset; }
v3s16 getCameraOffset() const { return m_camera_offset; }
-
private:
ClientMap *m_map;
LocalPlayer *m_local_player = nullptr;
@@ -156,7 +153,7 @@ private:
Client *m_client;
ClientScripting *m_script = nullptr;
client::ActiveObjectMgr m_ao_manager;
- std::vector<ClientSimpleObject *> m_simple_objects;
+ std::vector<ClientSimpleObject*> m_simple_objects;
std::queue<ClientEnvEvent> m_client_event_queue;
IntervalLimiter m_active_object_light_update_interval;
std::list<std::string> m_player_names;
diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp
index b96c7e7f6..ce16797e6 100644
--- a/src/client/clientlauncher.cpp
+++ b/src/client/clientlauncher.cpp
@@ -36,10 +36,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "network/networkexceptions.h"
#if USE_SOUND
-#include "sound_openal.h"
+ #include "sound_openal.h"
#endif
#ifdef __ANDROID__
-#include "porting.h"
+ #include "porting.h"
#endif
/* mainmenumanager.h
@@ -87,6 +87,7 @@ ClientLauncher::~ClientLauncher()
#endif
}
+
bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
{
/* This function is called when a client must be started.
@@ -94,7 +95,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
* - Singleplayer (address but map provided)
* - Join server (no map but address provided)
* - Local server (for main menu only)
- */
+ */
init_args(start_data, cmd_args);
@@ -130,7 +131,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
This changes the minimum allowed number of vertices in a VBO.
Default is 500.
*/
- // driver->setMinHardwareBufferVertexCount(50);
+ //driver->setMinHardwareBufferVertexCount(50);
// Create game callback for menus
g_gamecallback = new MainGameCallback();
@@ -139,8 +140,8 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
init_input();
- RenderingEngine::get_scene_manager()->getParameters()->setAttribute(
- scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
+ RenderingEngine::get_scene_manager()->getParameters()->
+ setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
guienv = RenderingEngine::get_gui_env();
skin = RenderingEngine::get_gui_env()->getSkin();
@@ -177,8 +178,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
g_fontengine = new FontEngine(g_settings, guienv);
FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
-#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || \
- IRRLICHT_VERSION_MAJOR >= 2
+#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
// Irrlicht 1.8 input colours
skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
@@ -186,13 +186,12 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
// Create the menu clouds
if (!g_menucloudsmgr)
- g_menucloudsmgr = RenderingEngine::get_scene_manager()
- ->createNewSceneManager();
+ g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
if (!g_menuclouds)
g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
g_menuclouds->setHeight(100.0f);
g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
- scene::ICameraSceneNode *camera;
+ scene::ICameraSceneNode* camera;
camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
camera->setFarValue(10000);
@@ -215,17 +214,17 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
bool retval = true;
bool *kill = porting::signal_handler_killstatus();
- while (RenderingEngine::run() && !*kill && !g_gamecallback->shutdown_requested) {
+ while (RenderingEngine::run() && !*kill &&
+ !g_gamecallback->shutdown_requested) {
// Set the window caption
const wchar_t *text = wgettext("Main Menu");
- RenderingEngine::get_raw_device()->setWindowCaption(
- (utf8_to_wide(PROJECT_NAME_C) + L" " +
- utf8_to_wide(g_version_hash) + L" [" +
- text + L"]")
- .c_str());
+ RenderingEngine::get_raw_device()->
+ setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
+ L" " + utf8_to_wide(g_version_hash) +
+ L" [" + text + L"]").c_str());
delete[] text;
- try { // This is used for catching disconnects
+ try { // This is used for catching disconnects
RenderingEngine::get_gui_env()->clear();
@@ -234,11 +233,11 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
custom gui elements directly on the screen.
Otherwise they won't be automatically drawn.
*/
- guiroot = RenderingEngine::get_gui_env()->addStaticText(
- L"", core::rect<s32>(0, 0, 10000, 10000));
+ guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
+ core::rect<s32>(0, 0, 10000, 10000));
- bool game_has_run = launch_game(error_message,
- reconnect_requested, start_data, cmd_args);
+ bool game_has_run = launch_game(error_message, reconnect_requested,
+ start_data, cmd_args);
// Reset the reconnect_requested flag
reconnect_requested = false;
@@ -259,23 +258,26 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
// Break out of menu-game loop to shut down cleanly
if (!RenderingEngine::get_raw_device()->run() || *kill) {
if (!g_settings_path.empty())
- g_settings->updateConfigFile(
- g_settings_path.c_str());
+ g_settings->updateConfigFile(g_settings_path.c_str());
break;
}
RenderingEngine::get_video_driver()->setTextureCreationFlag(
- video::ETCF_CREATE_MIP_MAPS,
- g_settings->getBool("mip_map"));
+ video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
#ifdef HAVE_TOUCHSCREENGUI
- receiver->m_touchscreengui = new TouchScreenGUI(
- RenderingEngine::get_raw_device(), receiver);
+ receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
g_touchscreengui = receiver->m_touchscreengui;
#endif
- the_game(kill, input, start_data, error_message, chat_backend,
- &reconnect_requested);
+ the_game(
+ kill,
+ input,
+ start_data,
+ error_message,
+ chat_backend,
+ &reconnect_requested
+ );
RenderingEngine::get_scene_manager()->clear();
#ifdef HAVE_TOUCHSCREENGUI
@@ -284,7 +286,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
receiver->m_touchscreengui = NULL;
#endif
- } // try
+ } //try
catch (con::PeerNotFoundException &e) {
error_message = gettext("Connection error (timed out?)");
errorstream << error_message << std::endl;
@@ -302,8 +304,8 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
// If no main menu, show error and exit
if (skip_main_menu) {
if (!error_message.empty()) {
- verbosestream << "error_message = " << error_message
- << std::endl;
+ verbosestream << "error_message = "
+ << error_message << std::endl;
retval = false;
}
break;
@@ -337,8 +339,8 @@ void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_ar
list_video_modes = cmd_args.getFlag("videomodes");
- random_input = g_settings->getBool("random_input") ||
- cmd_args.getFlag("random-input");
+ random_input = g_settings->getBool("random_input")
+ || cmd_args.getFlag("random-input");
}
bool ClientLauncher::init_engine()
@@ -370,14 +372,14 @@ void ClientLauncher::init_input()
}
input->joystick.onJoystickConnect(joystick_infos);
} else {
- errorstream << "Could not activate joystick support."
- << std::endl;
+ errorstream << "Could not activate joystick support." << std::endl;
}
}
}
-bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requested,
- GameStartData &start_data, const Settings &cmd_args)
+bool ClientLauncher::launch_game(std::string &error_message,
+ bool reconnect_requested, GameStartData &start_data,
+ const Settings &cmd_args)
{
// Prepare and check the start data to launch a game
std::string error_message_lua = error_message;
@@ -392,8 +394,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
getline(passfile, start_data.password);
} else {
error_message = gettext("Provided password file "
- "failed to open: ") +
- cmd_args.get("password-file");
+ "failed to open: ")
+ + cmd_args.get("password-file");
errorstream << error_message << std::endl;
return false;
}
@@ -408,7 +410,7 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
spec.gameid = getWorldGameId(spec.path, true);
spec.name = _("[--world parameter]");
- if (spec.gameid.empty()) { // Create new
+ if (spec.gameid.empty()) { // Create new
spec.gameid = g_settings->get("default_game");
spec.name += " [new]";
}
@@ -422,11 +424,11 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
// Initialize menu data
// TODO: Re-use existing structs (GameStartData)
MainMenuData menudata;
- menudata.address = start_data.address;
- menudata.name = start_data.name;
- menudata.password = start_data.password;
- menudata.port = itos(start_data.socket_port);
- menudata.script_data.errormessage = error_message_lua;
+ menudata.address = start_data.address;
+ menudata.name = start_data.name;
+ menudata.password = start_data.password;
+ menudata.port = itos(start_data.socket_port);
+ menudata.script_data.errormessage = error_message_lua;
menudata.script_data.reconnect_requested = reconnect_requested;
main_menu(&menudata);
@@ -436,9 +438,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
return false;
if (!menudata.script_data.errormessage.empty()) {
- /* The calling function will pass this back into this function
- * upon the next iteration (if any) causing it to be displayed by
- * the GUI
+ /* The calling function will pass this back into this function upon the
+ * next iteration (if any) causing it to be displayed by the GUI
*/
error_message = menudata.script_data.errormessage;
return false;
@@ -465,7 +466,7 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
server_description = menudata.serverdescription;
start_data.local_server = !menudata.simple_singleplayer_mode &&
- start_data.address.empty();
+ start_data.address.empty();
}
if (!RenderingEngine::run())
@@ -486,9 +487,9 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
g_settings->set("name", start_data.name);
if (!start_data.address.empty()) {
ServerListSpec server;
- server["name"] = server_name;
- server["address"] = start_data.address;
- server["port"] = itos(start_data.socket_port);
+ server["name"] = server_name;
+ server["address"] = start_data.address;
+ server["port"] = itos(start_data.socket_port);
server["description"] = server_description;
ServerList::insert(server);
}
@@ -502,21 +503,21 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
}
auto &worldspec = start_data.world_spec;
- infostream << "Selected world: " << worldspec.name << " [" << worldspec.path
- << "]" << std::endl;
+ infostream << "Selected world: " << worldspec.name
+ << " [" << worldspec.path << "]" << std::endl;
if (start_data.address.empty()) {
// For singleplayer and local server
if (worldspec.path.empty()) {
error_message = gettext("No world selected and no address "
- "provided. Nothing to do.");
+ "provided. Nothing to do.");
errorstream << error_message << std::endl;
return false;
}
if (!fs::PathExists(worldspec.path)) {
- error_message = gettext("Provided world path doesn't exist: ") +
- worldspec.path;
+ error_message = gettext("Provided world path doesn't exist: ")
+ + worldspec.path;
errorstream << error_message << std::endl;
return false;
}
@@ -524,8 +525,8 @@ bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requ
// Load gamespec for required game
start_data.game_spec = findWorldSubgame(worldspec.path);
if (!start_data.game_spec.isValid()) {
- error_message = gettext("Could not find or load game \"") +
- worldspec.gameid + "\"";
+ error_message = gettext("Could not find or load game \"")
+ + worldspec.gameid + "\"";
errorstream << error_message << std::endl;
return false;
}
@@ -600,7 +601,7 @@ void ClientLauncher::speed_tests()
for (u32 i = 0; i < ii; i++) {
tempstring2 += "asd";
}
- for (u32 i = 0; i < ii + 1; i++) {
+ for (u32 i = 0; i < ii+1; i++) {
tempstring += "asd";
if (tempstring == tempstring2)
break;
@@ -609,7 +610,7 @@ void ClientLauncher::speed_tests()
}
infostream << "All of the following tests should take around 100ms each."
- << std::endl;
+ << std::endl;
{
TimeTaker timer("Testing floating-point conversion speed");
@@ -639,7 +640,7 @@ void ClientLauncher::speed_tests()
const s16 ii = 300;
for (s16 y = 0; y < ii; y++) {
for (s16 x = 0; x < ii; x++) {
- map1[v2s16(x, y)] = tempf;
+ map1[v2s16(x, y)] = tempf;
tempf += 1;
}
}
@@ -665,7 +666,7 @@ void ClientLauncher::speed_tests()
}
}
// Do at least 10ms
- while (timer.getTimerTime() < 10);
+ while(timer.getTimerTime() < 10);
u32 dtime = timer.stop();
u32 per_ms = n / dtime;
diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h
index 1828272b1..b280d8e6b 100644
--- a/src/client/clientlauncher.h
+++ b/src/client/clientlauncher.h
@@ -40,7 +40,7 @@ private:
void init_input();
bool launch_game(std::string &error_message, bool reconnect_requested,
- GameStartData &start_data, const Settings &cmd_args);
+ GameStartData &start_data, const Settings &cmd_args);
void main_menu(MainMenuData *menudata);
diff --git a/src/client/clientmap.cpp b/src/client/clientmap.cpp
index dea354c96..d41b66741 100644
--- a/src/client/clientmap.cpp
+++ b/src/client/clientmap.cpp
@@ -26,20 +26,24 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "mapblock.h"
#include "profiler.h"
#include "settings.h"
-#include "camera.h" // CameraModes
+#include "camera.h" // CameraModes
#include "util/basic_macros.h"
#include <algorithm>
#include "client/renderingengine.h"
-ClientMap::ClientMap(Client *client, MapDrawControl &control, s32 id) :
- Map(dout_client, client),
- scene::ISceneNode(
- RenderingEngine::get_scene_manager()->getRootSceneNode(),
- RenderingEngine::get_scene_manager(), id),
- m_client(client), m_control(control)
+ClientMap::ClientMap(
+ Client *client,
+ MapDrawControl &control,
+ s32 id
+):
+ Map(dout_client, client),
+ scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
+ RenderingEngine::get_scene_manager(), id),
+ m_client(client),
+ m_control(control)
{
- m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000, BS * 1000000,
- BS * 1000000, BS * 1000000);
+ m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
+ BS*1000000,BS*1000000,BS*1000000);
/* TODO: Add a callback function so these can be updated when a setting
* changes. At this point in time it doesn't matter (e.g. /set
@@ -50,12 +54,13 @@ ClientMap::ClientMap(Client *client, MapDrawControl &control, s32 id) :
* (as opposed to the this local caching). This can be addressed in
* a later release.
*/
- m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
- m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
+ m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
+ m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
+
}
-MapSector *ClientMap::emergeSector(v2s16 p2d)
+MapSector * ClientMap::emergeSector(v2s16 p2d)
{
// Check that it doesn't exist already
MapSector *sector = getSectorNoGenerate(p2d);
@@ -71,7 +76,8 @@ MapSector *ClientMap::emergeSector(v2s16 p2d)
void ClientMap::OnRegisterSceneNode()
{
- if (IsVisible) {
+ if(IsVisible)
+ {
SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
}
@@ -79,23 +85,29 @@ void ClientMap::OnRegisterSceneNode()
ISceneNode::OnRegisterSceneNode();
}
-void ClientMap::getBlocksInViewRange(
- v3s16 cam_pos_nodes, v3s16 *p_blocks_min, v3s16 *p_blocks_max)
+void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
+ v3s16 *p_blocks_min, v3s16 *p_blocks_max)
{
v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
// Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
// can exceed the range of v3s16 when a large view range is used near the
// world edges.
- v3s32 p_nodes_min(cam_pos_nodes.X - box_nodes_d.X,
- cam_pos_nodes.Y - box_nodes_d.Y, cam_pos_nodes.Z - box_nodes_d.Z);
- v3s32 p_nodes_max(cam_pos_nodes.X + box_nodes_d.X,
- cam_pos_nodes.Y + box_nodes_d.Y, cam_pos_nodes.Z + box_nodes_d.Z);
+ v3s32 p_nodes_min(
+ cam_pos_nodes.X - box_nodes_d.X,
+ cam_pos_nodes.Y - box_nodes_d.Y,
+ cam_pos_nodes.Z - box_nodes_d.Z);
+ v3s32 p_nodes_max(
+ cam_pos_nodes.X + box_nodes_d.X,
+ cam_pos_nodes.Y + box_nodes_d.Y,
+ cam_pos_nodes.Z + box_nodes_d.Z);
// Take a fair amount as we will be dropping more out later
// Umm... these additions are a bit strange but they are needed.
- *p_blocks_min = v3s16(p_nodes_min.X / MAP_BLOCKSIZE - 3,
+ *p_blocks_min = v3s16(
+ p_nodes_min.X / MAP_BLOCKSIZE - 3,
p_nodes_min.Y / MAP_BLOCKSIZE - 3,
p_nodes_min.Z / MAP_BLOCKSIZE - 3);
- *p_blocks_max = v3s16(p_nodes_max.X / MAP_BLOCKSIZE + 1,
+ *p_blocks_max = v3s16(
+ p_nodes_max.X / MAP_BLOCKSIZE + 1,
p_nodes_max.Y / MAP_BLOCKSIZE + 1,
p_nodes_max.Z / MAP_BLOCKSIZE + 1);
}
@@ -134,13 +146,14 @@ void ClientMap::updateDrawList()
bool occlusion_culling_enabled = true;
if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
MapNode n = getNode(cam_pos_nodes);
- if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
+ if (n.getContent() == CONTENT_IGNORE ||
+ m_nodedef->get(n).solidness == 2)
occlusion_culling_enabled = false;
}
// Uncomment to debug occluded blocks in the wireframe mode
// TODO: Include this as a flag for an extended debugging setting
- // if (occlusion_culling_enabled && m_control.show_wireframe)
+ //if (occlusion_culling_enabled && m_control.show_wireframe)
// occlusion_culling_enabled = porting::getTimeS() & 1;
for (const auto &sector_it : m_sectors) {
@@ -177,9 +190,10 @@ void ClientMap::updateDrawList()
float d = 0.0;
if (!isBlockInSight(block->getPos(), camera_position,
- camera_direction, camera_fov, range, &d))
+ camera_direction, camera_fov, range, &d))
continue;
+
/*
Ignore if mesh doesn't exist
*/
@@ -192,9 +206,7 @@ void ClientMap::updateDrawList()
Occlusion culling
*/
if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
- (occlusion_culling_enabled &&
- isBlockOccluded(block,
- cam_pos_nodes))) {
+ (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
blocks_occlusion_culled++;
continue;
}
@@ -221,7 +233,7 @@ void ClientMap::updateDrawList()
struct MeshBufList
{
video::SMaterial m;
- std::vector<scene::IMeshBuffer *> bufs;
+ std::vector<scene::IMeshBuffer*> bufs;
};
struct MeshBufListList
@@ -245,8 +257,8 @@ struct MeshBufListList
std::vector<MeshBufList> &list = lists[layer];
const video::SMaterial &m = buf->getMaterial();
for (MeshBufList &l : list) {
- // comparing a full material is quite expensive so we don't do it
- // if not even first texture is equal
+ // comparing a full material is quite expensive so we don't do it if
+ // not even first texture is equal
if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
continue;
@@ -262,7 +274,7 @@ struct MeshBufListList
}
};
-void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
+void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
{
bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
@@ -297,7 +309,7 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
// For limiting number of mesh animations per frame
u32 mesh_animate_count = 0;
- // u32 mesh_animate_count_far = 0;
+ //u32 mesh_animate_count_far = 0;
/*
Draw the selected MapBlocks
@@ -313,23 +325,22 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
continue;
float d = 0.0;
- if (!isBlockInSight(block->getPos(), camera_position, camera_direction,
- camera_fov, 100000 * BS, &d))
+ if (!isBlockInSight(block->getPos(), camera_position,
+ camera_direction, camera_fov, 100000 * BS, &d))
continue;
// Mesh animation
if (pass == scene::ESNRP_SOLID) {
- // MutexAutoLock lock(block->mesh_mutex);
+ //MutexAutoLock lock(block->mesh_mutex);
MapBlockMesh *mapBlockMesh = block->mesh;
assert(mapBlockMesh);
// Pretty random but this should work somewhat nicely
bool faraway = d >= BS * 50;
if (mapBlockMesh->isAnimationForced() || !faraway ||
- mesh_animate_count < (m_control.range_all ? 200
- : 50)) {
+ mesh_animate_count < (m_control.range_all ? 200 : 50)) {
- bool animated = mapBlockMesh->animate(faraway,
- animation_time, crack, daynight_ratio);
+ bool animated = mapBlockMesh->animate(faraway, animation_time,
+ crack, daynight_ratio);
if (animated)
mesh_animate_count++;
} else {
@@ -341,7 +352,7 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
Get the meshbuffers of the block
*/
{
- // MutexAutoLock lock(block->mesh_mutex);
+ //MutexAutoLock lock(block->mesh_mutex);
MapBlockMesh *mapBlockMesh = block->mesh;
assert(mapBlockMesh);
@@ -354,30 +365,23 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
for (u32 i = 0; i < c; i++) {
scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
- video::SMaterial &material = buf->getMaterial();
- video::IMaterialRenderer *rnd =
- driver->getMaterialRenderer(
- material.MaterialType);
+ video::SMaterial& material = buf->getMaterial();
+ video::IMaterialRenderer* rnd =
+ driver->getMaterialRenderer(material.MaterialType);
bool transparent = (rnd && rnd->isTransparent());
if (transparent == is_transparent_pass) {
if (buf->getVertexCount() == 0)
- errorstream << "Block ["
- << analyze_block(block)
- << "] contains an "
- "empty meshbuf"
- << std::endl;
-
- material.setFlag(
- video::EMF_TRILINEAR_FILTER,
- m_cache_trilinear_filter);
- material.setFlag(
- video::EMF_BILINEAR_FILTER,
- m_cache_bilinear_filter);
- material.setFlag(
- video::EMF_ANISOTROPIC_FILTER,
- m_cache_anistropic_filter);
+ errorstream << "Block [" << analyze_block(block)
+ << "] contains an empty meshbuf" << std::endl;
+
+ material.setFlag(video::EMF_TRILINEAR_FILTER,
+ m_cache_trilinear_filter);
+ material.setFlag(video::EMF_BILINEAR_FILTER,
+ m_cache_bilinear_filter);
+ material.setFlag(video::EMF_ANISOTROPIC_FILTER,
+ m_cache_anistropic_filter);
material.setFlag(video::EMF_WIREFRAME,
- m_control.show_wireframe);
+ m_control.show_wireframe);
drawbufs.add(buf, layer);
}
@@ -393,9 +397,8 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
for (MeshBufList &list : lists) {
// Check and abort if the machine is swapping a lot
if (draw.getTimerTime() > 2000) {
- infostream << "ClientMap::renderMap(): Rendering took "
- ">2s, "
- << "returning." << std::endl;
+ infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
+ "returning." << std::endl;
return;
}
driver->setMaterial(list.m);
@@ -417,9 +420,9 @@ void ClientMap::renderMap(video::IVideoDriver *driver, s32 pass)
}
static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
- float step_multiplier, float start_distance, float end_distance,
- const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
- int *result, bool *sunlight_seen)
+ float step_multiplier, float start_distance, float end_distance,
+ const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
+ int *result, bool *sunlight_seen)
{
int brightness_sum = 0;
int brightness_count = 0;
@@ -435,7 +438,7 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
{
v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
MapNode n = map->getNode(p);
- if (ndef->get(n).param_type == CPT_LIGHT &&
+ if(ndef->get(n).param_type == CPT_LIGHT &&
!ndef->get(n).sunlight_propagates)
allow_allowing_non_sunlight_propagates = true;
}
@@ -443,14 +446,14 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
{
v3s16 p = floatToInt(pf, BS);
MapNode n = map->getNode(p);
- if (n.getContent() == CONTENT_IGNORE) {
- float newd = 2 * BS;
- pf = p0 + dir * 2 * newd;
+ if(n.getContent() == CONTENT_IGNORE){
+ float newd = 2*BS;
+ pf = p0 + dir * 2*newd;
distance = newd;
sunlight_min_d = 0;
}
}
- for (int i = 0; distance < end_distance; i++) {
+ for (int i=0; distance < end_distance; i++) {
pf += dir * step;
distance += step;
step *= step_multiplier;
@@ -465,10 +468,10 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
if (ndef->get(n).param_type != CPT_LIGHT ||
(!ndef->get(n).sunlight_propagates &&
- !allow_non_sunlight_propagates)) {
+ !allow_non_sunlight_propagates)){
nonlight_seen = true;
noncount++;
- if (noncount >= 4)
+ if(noncount >= 4)
break;
continue;
}
@@ -481,7 +484,7 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
brightness_count++;
}
*result = 0;
- if (brightness_count == 0)
+ if(brightness_count == 0)
return false;
*result = brightness_sum / brightness_count;
/*std::cerr<<"Sampled "<<brightness_count<<" points; result="
@@ -489,73 +492,78 @@ static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
return true;
}
-int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, int oldvalue,
- bool *sunlight_seen_result)
+int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
+ int oldvalue, bool *sunlight_seen_result)
{
ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
- static v3f z_directions[50] = {v3f(-100, 0, 0)};
- static f32 z_offsets[sizeof(z_directions) / sizeof(*z_directions)] = {
- -1000,
+ static v3f z_directions[50] = {
+ v3f(-100, 0, 0)
+ };
+ static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
+ -1000,
};
- if (z_directions[0].X < -99) {
- for (u32 i = 0; i < sizeof(z_directions) / sizeof(*z_directions); i++) {
+ if(z_directions[0].X < -99){
+ for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
// Assumes FOV of 72 and 16/9 aspect ratio
- z_directions[i] = v3f(0.02 * myrand_range(-100, 100), 1.0,
- 0.01 * myrand_range(-100, 100))
- .normalize();
- z_offsets[i] = 0.01 * myrand_range(0, 100);
+ z_directions[i] = v3f(
+ 0.02 * myrand_range(-100, 100),
+ 1.0,
+ 0.01 * myrand_range(-100, 100)
+ ).normalize();
+ z_offsets[i] = 0.01 * myrand_range(0,100);
}
}
int sunlight_seen_count = 0;
- float sunlight_min_d = max_d * 0.8;
- if (sunlight_min_d > 35 * BS)
- sunlight_min_d = 35 * BS;
+ float sunlight_min_d = max_d*0.8;
+ if(sunlight_min_d > 35*BS)
+ sunlight_min_d = 35*BS;
std::vector<int> values;
- for (u32 i = 0; i < sizeof(z_directions) / sizeof(*z_directions); i++) {
+ for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
v3f z_dir = z_directions[i];
core::CMatrix4<f32> a;
- a.buildRotateFromTo(v3f(0, 1, 0), z_dir);
+ a.buildRotateFromTo(v3f(0,1,0), z_dir);
v3f dir = m_camera_direction;
a.rotateVect(dir);
int br = 0;
- float step = BS * 1.5;
- if (max_d > 35 * BS)
+ float step = BS*1.5;
+ if(max_d > 35*BS)
step = max_d / 35 * 1.5;
float off = step * z_offsets[i];
bool sunlight_seen_now = false;
- bool ok = getVisibleBrightness(this, m_camera_position, dir, step, 1.0,
- max_d * 0.6 + off, max_d, m_nodedef, daylight_factor,
- sunlight_min_d, &br, &sunlight_seen_now);
- if (sunlight_seen_now)
+ bool ok = getVisibleBrightness(this, m_camera_position, dir,
+ step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
+ sunlight_min_d,
+ &br, &sunlight_seen_now);
+ if(sunlight_seen_now)
sunlight_seen_count++;
- if (!ok)
+ if(!ok)
continue;
values.push_back(br);
// Don't try too much if being in the sun is clear
- if (sunlight_seen_count >= 20)
+ if(sunlight_seen_count >= 20)
break;
}
int brightness_sum = 0;
int brightness_count = 0;
std::sort(values.begin(), values.end());
u32 num_values_to_use = values.size();
- if (num_values_to_use >= 10)
- num_values_to_use -= num_values_to_use / 2;
- else if (num_values_to_use >= 7)
- num_values_to_use -= num_values_to_use / 3;
+ if(num_values_to_use >= 10)
+ num_values_to_use -= num_values_to_use/2;
+ else if(num_values_to_use >= 7)
+ num_values_to_use -= num_values_to_use/3;
u32 first_value_i = (values.size() - num_values_to_use) / 2;
- for (u32 i = first_value_i; i < first_value_i + num_values_to_use; i++) {
+ for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
brightness_sum += values[i];
brightness_count++;
}
int ret = 0;
- if (brightness_count == 0) {
+ if(brightness_count == 0){
MapNode n = getNode(floatToInt(m_camera_position, BS));
- if (m_nodedef->get(n).param_type == CPT_LIGHT) {
+ if(m_nodedef->get(n).param_type == CPT_LIGHT){
ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
} else {
ret = oldvalue;
@@ -578,25 +586,27 @@ void ClientMap::renderPostFx(CameraMode cam_mode)
// - If the player is in a solid node, make everything black.
// - If the player is in liquid, draw a semi-transparent overlay.
// - Do not if player is in third person mode
- const ContentFeatures &features = m_nodedef->get(n);
+ const ContentFeatures& features = m_nodedef->get(n);
video::SColor post_effect_color = features.post_effect_color;
- if (features.solidness == 2 &&
- !((g_settings->getBool("noclip") ||
- g_settings->getBool("freecam")) &&
- m_client->checkLocalPrivilege("noclip")) &&
- cam_mode == CAMERA_MODE_FIRST) {
+ if(features.solidness == 2 && !((g_settings->getBool("noclip") || g_settings->getBool("freecam")) &&
+ m_client->checkLocalPrivilege("noclip")) &&
+ cam_mode == CAMERA_MODE_FIRST)
+ {
post_effect_color = video::SColor(255, 0, 0, 0);
}
- if (post_effect_color.getAlpha() != 0) {
+ if (post_effect_color.getAlpha() != 0)
+ {
// Draw a full-screen rectangle
- video::IVideoDriver *driver = SceneManager->getVideoDriver();
+ video::IVideoDriver* driver = SceneManager->getVideoDriver();
v2u32 ss = driver->getScreenSize();
- core::rect<s32> rect(0, 0, ss.X, ss.Y);
+ core::rect<s32> rect(0,0, ss.X, ss.Y);
driver->draw2DRectangle(post_effect_color, rect);
}
}
void ClientMap::PrintInfo(std::ostream &out)
{
- out << "ClientMap: ";
+ out<<"ClientMap: ";
}
+
+
diff --git a/src/client/clientmap.h b/src/client/clientmap.h
index 23eb561f8..172e3a1d6 100644
--- a/src/client/clientmap.h
+++ b/src/client/clientmap.h
@@ -47,13 +47,23 @@ class ITextureSource;
class ClientMap : public Map, public scene::ISceneNode
{
public:
- ClientMap(Client *client, MapDrawControl &control, s32 id);
+ ClientMap(
+ Client *client,
+ MapDrawControl &control,
+ s32 id
+ );
virtual ~ClientMap() = default;
- s32 mapType() const { return MAPTYPE_CLIENT; }
+ s32 mapType() const
+ {
+ return MAPTYPE_CLIENT;
+ }
- void drop() { ISceneNode::drop(); }
+ void drop()
+ {
+ ISceneNode::drop();
+ }
void updateCamera(const v3f &pos, const v3f &dir, f32 fov, const v3s16 &offset)
{
@@ -66,9 +76,9 @@ public:
/*
Forcefully get a sector from somewhere
*/
- MapSector *emergeSector(v2s16 p);
+ MapSector * emergeSector(v2s16 p);
- // void deSerializeSector(v2s16 p2d, std::istream &is);
+ //void deSerializeSector(v2s16 p2d, std::istream &is);
/*
ISceneNode methods
@@ -78,43 +88,45 @@ public:
virtual void render()
{
- video::IVideoDriver *driver = SceneManager->getVideoDriver();
+ video::IVideoDriver* driver = SceneManager->getVideoDriver();
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
renderMap(driver, SceneManager->getSceneNodeRenderPass());
}
- virtual const aabb3f &getBoundingBox() const { return m_box; }
+ virtual const aabb3f &getBoundingBox() const
+ {
+ return m_box;
+ }
- void getBlocksInViewRange(
- v3s16 cam_pos_nodes, v3s16 *p_blocks_min, v3s16 *p_blocks_max);
+ void getBlocksInViewRange(v3s16 cam_pos_nodes,
+ v3s16 *p_blocks_min, v3s16 *p_blocks_max);
void updateDrawList();
- void renderMap(video::IVideoDriver *driver, s32 pass);
+ void renderMap(video::IVideoDriver* driver, s32 pass);
- int getBackgroundBrightness(float max_d, u32 daylight_factor, int oldvalue,
- bool *sunlight_seen_result);
+ int getBackgroundBrightness(float max_d, u32 daylight_factor,
+ int oldvalue, bool *sunlight_seen_result);
void renderPostFx(CameraMode cam_mode);
// For debug printing
virtual void PrintInfo(std::ostream &out);
- const MapDrawControl &getControl() const { return m_control; }
+ const MapDrawControl & getControl() const { return m_control; }
f32 getCameraFov() const { return m_camera_fov; }
-
private:
Client *m_client;
- aabb3f m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000, BS * 1000000,
- BS * 1000000, BS * 1000000);
+ aabb3f m_box = aabb3f(-BS * 1000000, -BS * 1000000, -BS * 1000000,
+ BS * 1000000, BS * 1000000, BS * 1000000);
MapDrawControl &m_control;
- v3f m_camera_position = v3f(0, 0, 0);
- v3f m_camera_direction = v3f(0, 0, 1);
+ v3f m_camera_position = v3f(0,0,0);
+ v3f m_camera_direction = v3f(0,0,1);
f32 m_camera_fov = M_PI;
v3s16 m_camera_offset;
- std::map<v3s16, MapBlock *> m_drawlist;
+ std::map<v3s16, MapBlock*> m_drawlist;
std::set<v2s16> m_last_drawn_sectors;
diff --git a/src/client/clientmedia.cpp b/src/client/clientmedia.cpp
index 1cf18b84b..8cd3b6bcc 100644
--- a/src/client/clientmedia.cpp
+++ b/src/client/clientmedia.cpp
@@ -48,8 +48,9 @@ bool clientMediaUpdateCache(const std::string &raw_hash, const std::string &file
ClientMediaDownloader
*/
-ClientMediaDownloader::ClientMediaDownloader() :
- m_media_cache(getMediaCacheDir()), m_httpfetch_caller(HTTPFETCH_DISCARD)
+ClientMediaDownloader::ClientMediaDownloader():
+ m_media_cache(getMediaCacheDir()),
+ m_httpfetch_caller(HTTPFETCH_DISCARD)
{
}
@@ -72,21 +73,24 @@ void ClientMediaDownloader::addFile(const std::string &name, const std::string &
// if name was already announced, ignore the new announcement
if (m_files.count(name) != 0) {
errorstream << "Client: ignoring duplicate media announcement "
- << "sent by server: \"" << name << "\"" << std::endl;
+ << "sent by server: \"" << name << "\""
+ << std::endl;
return;
}
// if name is empty or contains illegal characters, ignore the file
if (name.empty() || !string_allowed(name, TEXTURENAME_ALLOWED_CHARS)) {
errorstream << "Client: ignoring illegal file name "
- << "sent by server: \"" << name << "\"" << std::endl;
+ << "sent by server: \"" << name << "\""
+ << std::endl;
return;
}
// length of sha1 must be exactly 20 (160 bits), else ignore the file
if (sha1.size() != 20) {
errorstream << "Client: ignoring illegal SHA1 sent by server: "
- << hex_encode(sha1) << " \"" << name << "\"" << std::endl;
+ << hex_encode(sha1) << " \"" << name << "\""
+ << std::endl;
return;
}
@@ -99,13 +103,13 @@ void ClientMediaDownloader::addFile(const std::string &name, const std::string &
void ClientMediaDownloader::addRemoteServer(const std::string &baseurl)
{
- assert(!m_initial_step_done); // pre-condition
+ assert(!m_initial_step_done); // pre-condition
-#ifdef USE_CURL
+ #ifdef USE_CURL
if (g_settings->getBool("enable_remote_media_server")) {
- infostream << "Client: Adding remote server \"" << baseurl
- << "\" for media download" << std::endl;
+ infostream << "Client: Adding remote server \""
+ << baseurl << "\" for media download" << std::endl;
RemoteServerStatus *remote = new RemoteServerStatus();
remote->baseurl = baseurl;
@@ -113,12 +117,13 @@ void ClientMediaDownloader::addRemoteServer(const std::string &baseurl)
m_remotes.push_back(remote);
}
-#else
+ #else
- infostream << "Client: Ignoring remote server \"" << baseurl
- << "\" because cURL support is not compiled in" << std::endl;
+ infostream << "Client: Ignoring remote server \""
+ << baseurl << "\" because cURL support is not compiled in"
+ << std::endl;
-#endif
+ #endif
}
void ClientMediaDownloader::step(Client *client)
@@ -153,10 +158,9 @@ void ClientMediaDownloader::step(Client *client)
if (m_httpfetch_active == 0) {
if (m_uncached_received_count < m_uncached_count) {
infostream << "Client: Failed to remote-fetch "
- << (m_uncached_count -
- m_uncached_received_count)
- << " files. Requesting them"
- << " the usual way." << std::endl;
+ << (m_uncached_count-m_uncached_received_count)
+ << " files. Requesting them"
+ << " the usual way." << std::endl;
}
startConventionalTransfers(client);
}
@@ -177,8 +181,8 @@ void ClientMediaDownloader::initialStep(Client *client)
// If found in cache, try to load it from there
if (found_in_cache) {
- bool success = checkAndLoad(
- name, sha1, tmp_os.str(), true, client);
+ bool success = checkAndLoad(name, sha1,
+ tmp_os.str(), true, client);
if (success) {
filestatus->received = true;
m_uncached_count--;
@@ -193,8 +197,9 @@ void ClientMediaDownloader::initialStep(Client *client)
bool did = fs::CreateAllDirs(getMediaCacheDir());
if (!did) {
errorstream << "Client: "
- << "Could not create media cache directory: "
- << getMediaCacheDir() << std::endl;
+ << "Could not create media cache directory: "
+ << getMediaCacheDir()
+ << std::endl;
}
}
@@ -205,7 +210,8 @@ void ClientMediaDownloader::initialStep(Client *client)
// reduce the size of the compiled code
if (!USE_CURL || m_uncached_count == 0 || m_remotes.empty()) {
startConventionalTransfers(client);
- } else {
+ }
+ else {
// Otherwise start off by requesting each server's sha1 set
// This is the first time we use httpfetch, so alloc a caller ID
@@ -245,26 +251,27 @@ void ClientMediaDownloader::initialStep(Client *client)
RemoteServerStatus *remote = m_remotes[i];
actionstream << "Client: Contacting remote server \""
- << remote->baseurl << "\"" << std::endl;
+ << remote->baseurl << "\"" << std::endl;
HTTPFetchRequest fetch_request;
- fetch_request.url = remote->baseurl + MTHASHSET_FILE_NAME;
+ fetch_request.url =
+ remote->baseurl + MTHASHSET_FILE_NAME;
fetch_request.caller = m_httpfetch_caller;
fetch_request.request_id = m_httpfetch_next_id; // == i
fetch_request.timeout = m_httpfetch_timeout;
fetch_request.connect_timeout = m_httpfetch_timeout;
fetch_request.post_data = required_hash_set;
fetch_request.extra_headers.emplace_back(
- "Content-Type: application/octet-stream");
+ "Content-Type: application/octet-stream");
// Encapsulate possible IPv6 plain address in []
std::string addr = client->getAddressName();
if (addr.find(':', 0) != std::string::npos)
addr = '[' + addr + ']';
fetch_request.extra_headers.emplace_back(
- std::string("Referer: minetest://") + addr + ":" +
- std::to_string(client->getServerAddress()
- .getPort()));
+ std::string("Referer: minetest://") +
+ addr + ":" +
+ std::to_string(client->getServerAddress().getPort()));
httpfetch_async(fetch_request);
@@ -275,7 +282,8 @@ void ClientMediaDownloader::initialStep(Client *client)
}
}
-void ClientMediaDownloader::remoteHashSetReceived(const HTTPFetchResult &fetch_result)
+void ClientMediaDownloader::remoteHashSetReceived(
+ const HTTPFetchResult &fetch_result)
{
u32 remote_id = fetch_result.request_id;
assert(remote_id < m_remotes.size());
@@ -295,23 +303,25 @@ void ClientMediaDownloader::remoteHashSetReceived(const HTTPFetchResult &fetch_r
// available on this server, add this server
// to the available_remotes array
- for (std::map<std::string, FileStatus *>::iterator it =
- m_files.upper_bound(m_name_bound);
+ for(std::map<std::string, FileStatus*>::iterator
+ it = m_files.upper_bound(m_name_bound);
it != m_files.end(); ++it) {
FileStatus *f = it->second;
if (!f->received && sha1_set.count(f->sha1))
f->available_remotes.push_back(remote_id);
}
- } catch (SerializationError &e) {
- infostream << "Client: Remote server \"" << remote->baseurl
- << "\" sent invalid hash set: " << e.what()
- << std::endl;
+ }
+ catch (SerializationError &e) {
+ infostream << "Client: Remote server \""
+ << remote->baseurl << "\" sent invalid hash set: "
+ << e.what() << std::endl;
}
}
}
void ClientMediaDownloader::remoteMediaReceived(
- const HTTPFetchResult &fetch_result, Client *client)
+ const HTTPFetchResult &fetch_result,
+ Client *client)
{
// Some remote server sent us a file.
// -> decrement number of active fetches
@@ -321,7 +331,7 @@ void ClientMediaDownloader::remoteMediaReceived(
std::string name;
{
std::unordered_map<unsigned long, std::string>::iterator it =
- m_remote_file_transfers.find(fetch_result.request_id);
+ m_remote_file_transfers.find(fetch_result.request_id);
assert(it != m_remote_file_transfers.end());
name = it->second;
m_remote_file_transfers.erase(it);
@@ -341,8 +351,8 @@ void ClientMediaDownloader::remoteMediaReceived(
// If fetch succeeded, try to load media file
if (fetch_result.succeeded) {
- bool success = checkAndLoad(
- name, filestatus->sha1, fetch_result.data, false, client);
+ bool success = checkAndLoad(name, filestatus->sha1,
+ fetch_result.data, false, client);
if (success) {
filestatus->received = true;
assert(m_uncached_received_count < m_uncached_count);
@@ -379,17 +389,19 @@ s32 ClientMediaDownloader::selectRemoteServer(FileStatus *filestatus)
}
}
- filestatus->available_remotes.erase(filestatus->available_remotes.begin() + best);
+ filestatus->available_remotes.erase(
+ filestatus->available_remotes.begin() + best);
return best_remote_id;
+
}
void ClientMediaDownloader::startRemoteMediaTransfers()
{
bool changing_name_bound = true;
- for (std::map<std::string, FileStatus *>::iterator files_iter =
- m_files.upper_bound(m_name_bound);
+ for (std::map<std::string, FileStatus*>::iterator
+ files_iter = m_files.upper_bound(m_name_bound);
files_iter != m_files.end(); ++files_iter) {
// Abort if active fetch limit is exceeded
@@ -405,25 +417,28 @@ void ClientMediaDownloader::startRemoteMediaTransfers()
s32 remote_id = selectRemoteServer(filestatus);
if (remote_id >= 0) {
// Found a server, so start fetching
- RemoteServerStatus *remote = m_remotes[remote_id];
+ RemoteServerStatus *remote =
+ m_remotes[remote_id];
std::string url = remote->baseurl +
- hex_encode(filestatus->sha1);
+ hex_encode(filestatus->sha1);
verbosestream << "Client: "
- << "Requesting remote media file "
- << "\"" << name << "\" "
- << "\"" << url << "\"" << std::endl;
+ << "Requesting remote media file "
+ << "\"" << name << "\" "
+ << "\"" << url << "\"" << std::endl;
HTTPFetchRequest fetch_request;
fetch_request.url = url;
fetch_request.caller = m_httpfetch_caller;
fetch_request.request_id = m_httpfetch_next_id;
fetch_request.timeout = 0; // no data timeout!
- fetch_request.connect_timeout = m_httpfetch_timeout;
+ fetch_request.connect_timeout =
+ m_httpfetch_timeout;
httpfetch_async(fetch_request);
m_remote_file_transfers.insert(std::make_pair(
- m_httpfetch_next_id, name));
+ m_httpfetch_next_id,
+ name));
filestatus->current_remote = remote_id;
remote->active_count++;
@@ -432,21 +447,24 @@ void ClientMediaDownloader::startRemoteMediaTransfers()
}
}
- if (filestatus->received || (filestatus->current_remote < 0 &&
- !m_outstanding_hash_sets)) {
+ if (filestatus->received ||
+ (filestatus->current_remote < 0 &&
+ !m_outstanding_hash_sets)) {
// If we arrive here, we conclusively know that we
// won't fetch this file from a remote server in the
// future. So update the name bound if possible.
if (changing_name_bound)
m_name_bound = name;
- } else
+ }
+ else
changing_name_bound = false;
}
+
}
void ClientMediaDownloader::startConventionalTransfers(Client *client)
{
- assert(m_httpfetch_active == 0); // pre-condition
+ assert(m_httpfetch_active == 0); // pre-condition
if (m_uncached_received_count != m_uncached_count) {
// Some media files have not been received yet, use the
@@ -456,21 +474,24 @@ void ClientMediaDownloader::startConventionalTransfers(Client *client)
if (!file.second->received)
file_requests.push_back(file.first);
}
- assert((s32)file_requests.size() ==
+ assert((s32) file_requests.size() ==
m_uncached_count - m_uncached_received_count);
client->request_media(file_requests);
}
}
void ClientMediaDownloader::conventionalTransferDone(
- const std::string &name, const std::string &data, Client *client)
+ const std::string &name,
+ const std::string &data,
+ Client *client)
{
// Check that file was announced
- std::map<std::string, FileStatus *>::iterator file_iter = m_files.find(name);
+ std::map<std::string, FileStatus*>::iterator
+ file_iter = m_files.find(name);
if (file_iter == m_files.end()) {
errorstream << "Client: server sent media file that was"
- << "not announced, ignoring it: \"" << name << "\""
- << std::endl;
+ << "not announced, ignoring it: \"" << name << "\""
+ << std::endl;
return;
}
FileStatus *filestatus = file_iter->second;
@@ -479,7 +500,8 @@ void ClientMediaDownloader::conventionalTransferDone(
// Check that file hasn't already been received
if (filestatus->received) {
errorstream << "Client: server sent media file that we already"
- << "received, ignoring it: \"" << name << "\"" << std::endl;
+ << "received, ignoring it: \"" << name << "\""
+ << std::endl;
return;
}
@@ -495,7 +517,8 @@ void ClientMediaDownloader::conventionalTransferDone(
checkAndLoad(name, filestatus->sha1, data, false, client);
}
-bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::string &sha1,
+bool ClientMediaDownloader::checkAndLoad(
+ const std::string &name, const std::string &sha1,
const std::string &data, bool is_from_cache, Client *client)
{
const char *cached_or_received = is_from_cache ? "cached" : "received";
@@ -508,16 +531,18 @@ bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::str
SHA1 data_sha1_calculator;
data_sha1_calculator.addBytes(data.c_str(), data.size());
unsigned char *data_tmpdigest = data_sha1_calculator.getDigest();
- data_sha1.assign((char *)data_tmpdigest, 20);
+ data_sha1.assign((char*) data_tmpdigest, 20);
free(data_tmpdigest);
}
// Check that received file matches announced checksum
if (data_sha1 != sha1) {
std::string data_sha1_hex = hex_encode(data_sha1);
- infostream << "Client: " << cached_or_received_uc << " media file "
- << sha1_hex << " \"" << name << "\" "
- << "mismatches actual checksum " << data_sha1_hex << std::endl;
+ infostream << "Client: "
+ << cached_or_received_uc << " media file "
+ << sha1_hex << " \"" << name << "\" "
+ << "mismatches actual checksum " << data_sha1_hex
+ << std::endl;
return false;
}
@@ -525,15 +550,16 @@ bool ClientMediaDownloader::checkAndLoad(const std::string &name, const std::str
bool success = client->loadMedia(data, name);
if (!success) {
infostream << "Client: "
- << "Failed to load " << cached_or_received
- << " media: " << sha1_hex << " \"" << name << "\""
- << std::endl;
+ << "Failed to load " << cached_or_received << " media: "
+ << sha1_hex << " \"" << name << "\""
+ << std::endl;
return false;
}
verbosestream << "Client: "
- << "Loaded " << cached_or_received << " media: " << sha1_hex
- << " \"" << name << "\"" << std::endl;
+ << "Loaded " << cached_or_received << " media: "
+ << sha1_hex << " \"" << name << "\""
+ << std::endl;
// Update cache (unless we just loaded the file from the cache)
if (!is_from_cache)
@@ -560,15 +586,15 @@ std::string ClientMediaDownloader::serializeRequiredHashSet()
std::ostringstream os(std::ios::binary);
writeU32(os, MTHASHSET_FILE_SIGNATURE); // signature
- writeU16(os, 1); // version
+ writeU16(os, 1); // version
// Write list of hashes of files that have not been
// received (found in cache) yet
- for (std::map<std::string, FileStatus *>::iterator it = m_files.begin();
+ for (std::map<std::string, FileStatus*>::iterator
+ it = m_files.begin();
it != m_files.end(); ++it) {
if (!it->second->received) {
- FATAL_ERROR_IF(it->second->sha1.size() != 20,
- "Invalid SHA1 size");
+ FATAL_ERROR_IF(it->second->sha1.size() != 20, "Invalid SHA1 size");
os << it->second->sha1;
}
}
@@ -576,26 +602,29 @@ std::string ClientMediaDownloader::serializeRequiredHashSet()
return os.str();
}
-void ClientMediaDownloader::deSerializeHashSet(
- const std::string &data, std::set<std::string> &result)
+void ClientMediaDownloader::deSerializeHashSet(const std::string &data,
+ std::set<std::string> &result)
{
if (data.size() < 6 || data.size() % 20 != 6) {
- throw SerializationError("ClientMediaDownloader::deSerializeHashSet: "
- "invalid hash set file size");
+ throw SerializationError(
+ "ClientMediaDownloader::deSerializeHashSet: "
+ "invalid hash set file size");
}
- const u8 *data_cstr = (const u8 *)data.c_str();
+ const u8 *data_cstr = (const u8*) data.c_str();
u32 signature = readU32(&data_cstr[0]);
if (signature != MTHASHSET_FILE_SIGNATURE) {
- throw SerializationError("ClientMediaDownloader::deSerializeHashSet: "
- "invalid hash set file signature");
+ throw SerializationError(
+ "ClientMediaDownloader::deSerializeHashSet: "
+ "invalid hash set file signature");
}
u16 version = readU16(&data_cstr[4]);
if (version != 1) {
- throw SerializationError("ClientMediaDownloader::deSerializeHashSet: "
- "unsupported hash set file version");
+ throw SerializationError(
+ "ClientMediaDownloader::deSerializeHashSet: "
+ "unsupported hash set file version");
}
for (u32 pos = 6; pos < data.size(); pos += 20) {
diff --git a/src/client/clientmedia.h b/src/client/clientmedia.h
index 6a52c551d..5a918535b 100644
--- a/src/client/clientmedia.h
+++ b/src/client/clientmedia.h
@@ -35,7 +35,8 @@ struct HTTPFetchResult;
// Store file into media cache (unless it exists already)
// Validating the hash is responsibility of the caller
-bool clientMediaUpdateCache(const std::string &raw_hash, const std::string &filedata);
+bool clientMediaUpdateCache(const std::string &raw_hash,
+ const std::string &filedata);
class ClientMediaDownloader
{
@@ -43,21 +44,22 @@ public:
ClientMediaDownloader();
~ClientMediaDownloader();
- float getProgress() const
- {
+ float getProgress() const {
if (m_uncached_count >= 1)
- return 1.0f * m_uncached_received_count / m_uncached_count;
+ return 1.0f * m_uncached_received_count /
+ m_uncached_count;
return 0.0f;
}
- bool isStarted() const { return m_initial_step_done; }
+ bool isStarted() const {
+ return m_initial_step_done;
+ }
// If this returns true, the downloader is done and can be deleted
- bool isDone() const
- {
+ bool isDone() const {
return m_initial_step_done &&
- m_uncached_received_count == m_uncached_count;
+ m_uncached_received_count == m_uncached_count;
}
// Add a file to the list of required file (but don't fetch it yet)
@@ -80,42 +82,44 @@ public:
// Must be called for each file received through TOCLIENT_MEDIA
void conventionalTransferDone(
- const std::string &name, const std::string &data, Client *client);
+ const std::string &name,
+ const std::string &data,
+ Client *client);
private:
- struct FileStatus
- {
+ struct FileStatus {
bool received;
std::string sha1;
s32 current_remote;
std::vector<s32> available_remotes;
};
- struct RemoteServerStatus
- {
+ struct RemoteServerStatus {
std::string baseurl;
s32 active_count;
};
void initialStep(Client *client);
void remoteHashSetReceived(const HTTPFetchResult &fetch_result);
- void remoteMediaReceived(const HTTPFetchResult &fetch_result, Client *client);
+ void remoteMediaReceived(const HTTPFetchResult &fetch_result,
+ Client *client);
s32 selectRemoteServer(FileStatus *filestatus);
void startRemoteMediaTransfers();
void startConventionalTransfers(Client *client);
bool checkAndLoad(const std::string &name, const std::string &sha1,
- const std::string &data, bool is_from_cache, Client *client);
+ const std::string &data, bool is_from_cache,
+ Client *client);
std::string serializeRequiredHashSet();
- static void deSerializeHashSet(
- const std::string &data, std::set<std::string> &result);
+ static void deSerializeHashSet(const std::string &data,
+ std::set<std::string> &result);
// Maps filename to file status
- std::map<std::string, FileStatus *> m_files;
+ std::map<std::string, FileStatus*> m_files;
// Array of remote media servers
- std::vector<RemoteServerStatus *> m_remotes;
+ std::vector<RemoteServerStatus*> m_remotes;
// Filesystem-based media cache
FileCache m_media_cache;
@@ -144,4 +148,5 @@ private:
// don't need to be looked at again
// (use m_files.upper_bound(m_name_bound) to get an iterator)
std::string m_name_bound = "";
+
};
diff --git a/src/client/clientobject.cpp b/src/client/clientobject.cpp
index af8b35da1..f4b69201b 100644
--- a/src/client/clientobject.cpp
+++ b/src/client/clientobject.cpp
@@ -25,8 +25,11 @@ with this program; if not, write to the Free Software Foundation, Inc.,
ClientActiveObject
*/
-ClientActiveObject::ClientActiveObject(u16 id, Client *client, ClientEnvironment *env) :
- ActiveObject(id), m_client(client), m_env(env)
+ClientActiveObject::ClientActiveObject(u16 id, Client *client,
+ ClientEnvironment *env):
+ ActiveObject(id),
+ m_client(client),
+ m_env(env)
{
}
@@ -35,15 +38,15 @@ ClientActiveObject::~ClientActiveObject()
removeFromScene(true);
}
-ClientActiveObject *ClientActiveObject::create(
- ActiveObjectType type, Client *client, ClientEnvironment *env)
+ClientActiveObject* ClientActiveObject::create(ActiveObjectType type,
+ Client *client, ClientEnvironment *env)
{
// Find factory function
auto n = m_types.find(type);
if (n == m_types.end()) {
// If factory is not found, just return.
- warningstream << "ClientActiveObject: No factory for type=" << (int)type
- << std::endl;
+ warningstream << "ClientActiveObject: No factory for type="
+ << (int)type << std::endl;
return NULL;
}
@@ -59,3 +62,5 @@ void ClientActiveObject::registerType(u16 type, Factory f)
return;
m_types[type] = f;
}
+
+
diff --git a/src/client/clientobject.h b/src/client/clientobject.h
index 7b451eb36..4a1743d72 100644
--- a/src/client/clientobject.h
+++ b/src/client/clientobject.h
@@ -23,11 +23,13 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "activeobject.h"
#include <ISceneNode.h>
#include <IMeshSceneNode.h>
+#include <IAnimatedMeshSceneNode.h>
+#include <IDummyTransformationSceneNode.h>
+#include <IBillboardSceneNode.h>
#include <unordered_map>
#include <unordered_set>
-
class ClientEnvironment;
class ITextureSource;
class Client;
@@ -51,20 +53,16 @@ public:
virtual bool getSelectionBox(aabb3f *toset) const { return false; }
virtual bool collideWithObjects() const { return false; }
virtual const v3f getPosition() const { return v3f(0.0f); }
- virtual scene::ISceneNode *getSceneNode() const { return NULL; }
+ virtual scene::ISceneNode *getSceneNode() const
+ { return NULL; }
virtual scene::IAnimatedMeshSceneNode *getAnimatedMeshSceneNode() const
- {
- return NULL;
- }
+ { return NULL; }
virtual bool isLocalPlayer() const { return false; }
virtual ClientActiveObject *getParent() const { return nullptr; };
virtual const std::unordered_set<int> &getAttachmentChildIds() const
- {
- static std::unordered_set<int> rv;
- return rv;
- }
- virtual void updateAttachments(){};
+ { static std::unordered_set<int> rv; return rv; }
+ virtual void updateAttachments() {};
virtual bool doShowSelectionBox() { return true; }
@@ -84,15 +82,12 @@ public:
virtual void initialize(const std::string &data) {}
// Create a certain type of ClientActiveObject
- static ClientActiveObject *create(
- ActiveObjectType type, Client *client, ClientEnvironment *env);
+ static ClientActiveObject *create(ActiveObjectType type, Client *client,
+ ClientEnvironment *env);
// If returns true, punch will not be sent to the server
virtual bool directReportPunch(v3f dir, const ItemStack *punchitem = nullptr,
- float time_from_last_punch = 1000000)
- {
- return false;
- }
+ float time_from_last_punch = 1000000) { return false; }
protected:
// Used for creating objects based on type
@@ -100,7 +95,6 @@ protected:
static void registerType(u16 type, Factory f);
Client *m_client;
ClientEnvironment *m_env;
-
private:
// Used for creating objects based on type
static std::unordered_map<u16, Factory> m_types;
@@ -117,7 +111,7 @@ public:
d = a_d;
}
- bool operator<(const DistanceSortedActiveObject &other) const
+ bool operator < (const DistanceSortedActiveObject &other) const
{
return d < other.d;
}
diff --git a/src/client/clouds.cpp b/src/client/clouds.cpp
index e59eb8b4d..887a62f25 100644
--- a/src/client/clouds.cpp
+++ b/src/client/clouds.cpp
@@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "settings.h"
#include <cmath>
+
// Menu clouds are created later
class Clouds;
Clouds *g_menuclouds = NULL;
@@ -39,43 +40,48 @@ static void cloud_3d_setting_changed(const std::string &settingname, void *data)
((Clouds *)data)->readSettings();
}
-Clouds::Clouds(scene::ISceneManager *mgr, s32 id, u32 seed) :
- scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), m_seed(seed)
+Clouds::Clouds(scene::ISceneManager* mgr,
+ s32 id,
+ u32 seed
+):
+ scene::ISceneNode(mgr->getRootSceneNode(), mgr, id),
+ m_seed(seed)
{
m_material.setFlag(video::EMF_LIGHTING, false);
- // m_material.setFlag(video::EMF_BACK_FACE_CULLING, false);
+ //m_material.setFlag(video::EMF_BACK_FACE_CULLING, false);
m_material.setFlag(video::EMF_BACK_FACE_CULLING, true);
m_material.setFlag(video::EMF_BILINEAR_FILTER, false);
m_material.setFlag(video::EMF_FOG_ENABLE, true);
m_material.setFlag(video::EMF_ANTI_ALIASING, true);
- // m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
+ //m_material.MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
m_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
- m_params.height = 120;
- m_params.density = 0.4f;
- m_params.thickness = 16.0f;
- m_params.color_bright = video::SColor(229, 240, 240, 255);
+ m_params.height = 120;
+ m_params.density = 0.4f;
+ m_params.thickness = 16.0f;
+ m_params.color_bright = video::SColor(229, 240, 240, 255);
m_params.color_ambient = video::SColor(255, 0, 0, 0);
- m_params.speed = v2f(0.0f, -2.0f);
+ m_params.speed = v2f(0.0f, -2.0f);
readSettings();
- g_settings->registerChangedCallback(
- "enable_3d_clouds", &cloud_3d_setting_changed, this);
+ g_settings->registerChangedCallback("enable_3d_clouds",
+ &cloud_3d_setting_changed, this);
updateBox();
}
Clouds::~Clouds()
{
- g_settings->deregisterChangedCallback(
- "enable_3d_clouds", &cloud_3d_setting_changed, this);
+ g_settings->deregisterChangedCallback("enable_3d_clouds",
+ &cloud_3d_setting_changed, this);
}
void Clouds::OnRegisterSceneNode()
{
- if (IsVisible) {
+ if(IsVisible)
+ {
SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
- // SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
+ //SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
}
ISceneNode::OnRegisterSceneNode();
@@ -87,10 +93,10 @@ void Clouds::render()
if (m_params.density <= 0.0f)
return; // no need to do anything
- video::IVideoDriver *driver = SceneManager->getVideoDriver();
+ video::IVideoDriver* driver = SceneManager->getVideoDriver();
- if (SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT)
- // if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID)
+ if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT)
+ //if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID)
return;
ScopeProfiler sp(g_profiler, "Clouds::render()", SPT_AVG);
@@ -115,14 +121,15 @@ void Clouds::render()
v2f center_of_drawing_in_noise_f = -cloud_origin_from_camera_f;
// The integer center point of drawing in the noise
v2s16 center_of_drawing_in_noise_i(
- std::floor(center_of_drawing_in_noise_f.X / cloud_size),
- std::floor(center_of_drawing_in_noise_f.Y / cloud_size));
+ std::floor(center_of_drawing_in_noise_f.X / cloud_size),
+ std::floor(center_of_drawing_in_noise_f.Y / cloud_size)
+ );
// The world position of the integer center point of drawing in the noise
- v2f world_center_of_drawing_in_noise_f =
- v2f(center_of_drawing_in_noise_i.X * cloud_size,
- center_of_drawing_in_noise_i.Y * cloud_size) +
- m_origin;
+ v2f world_center_of_drawing_in_noise_f = v2f(
+ center_of_drawing_in_noise_i.X * cloud_size,
+ center_of_drawing_in_noise_i.Y * cloud_size
+ ) + m_origin;
/*video::SColor c_top(128,b*240,b*240,b*255);
video::SColor c_side_1(128,b*230,b*230,b*255);
@@ -147,185 +154,185 @@ void Clouds::render()
video::SColor c_bottom = c_bottom_f.toSColor();
// Get fog parameters for setting them back later
- video::SColor fog_color(0, 0, 0, 0);
+ video::SColor fog_color(0,0,0,0);
video::E_FOG_TYPE fog_type = video::EFT_FOG_LINEAR;
f32 fog_start = 0;
f32 fog_end = 0;
f32 fog_density = 0;
bool fog_pixelfog = false;
bool fog_rangefog = false;
- driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog,
- fog_rangefog);
+ driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density,
+ fog_pixelfog, fog_rangefog);
// Set our own fog
driver->setFog(fog_color, fog_type, cloud_full_radius * 0.5,
- cloud_full_radius * 1.2, fog_density, fog_pixelfog, fog_rangefog);
+ cloud_full_radius*1.2, fog_density, fog_pixelfog, fog_rangefog);
// Read noise
bool *grid = new bool[m_cloud_radius_i * 2 * m_cloud_radius_i * 2];
- for (s16 zi = -m_cloud_radius_i; zi < m_cloud_radius_i; zi++) {
- u32 si = (zi + m_cloud_radius_i) * m_cloud_radius_i * 2 +
- m_cloud_radius_i;
+
+ for(s16 zi = -m_cloud_radius_i; zi < m_cloud_radius_i; zi++) {
+ u32 si = (zi + m_cloud_radius_i) * m_cloud_radius_i * 2 + m_cloud_radius_i;
for (s16 xi = -m_cloud_radius_i; xi < m_cloud_radius_i; xi++) {
u32 i = si + xi;
- grid[i] = gridFilled(xi + center_of_drawing_in_noise_i.X,
- zi + center_of_drawing_in_noise_i.Y);
+ grid[i] = gridFilled(
+ xi + center_of_drawing_in_noise_i.X,
+ zi + center_of_drawing_in_noise_i.Y
+ );
}
}
-#define GETINDEX(x, z, radius) (((z) + (radius)) * (radius)*2 + (x) + (radius))
-#define INAREA(x, z, radius) \
+#define GETINDEX(x, z, radius) (((z)+(radius))*(radius)*2 + (x)+(radius))
+#define INAREA(x, z, radius) \
((x) >= -(radius) && (x) < (radius) && (z) >= -(radius) && (z) < (radius))
- for (s16 zi0 = -m_cloud_radius_i; zi0 < m_cloud_radius_i; zi0++)
- for (s16 xi0 = -m_cloud_radius_i; xi0 < m_cloud_radius_i; xi0++) {
- s16 zi = zi0;
- s16 xi = xi0;
- // Draw from front to back (needed for transparency)
- /*if(zi <= 0)
- zi = -m_cloud_radius_i - zi;
- if(xi <= 0)
- xi = -m_cloud_radius_i - xi;*/
- // Draw from back to front
- if (zi >= 0)
- zi = m_cloud_radius_i - zi - 1;
- if (xi >= 0)
- xi = m_cloud_radius_i - xi - 1;
-
- u32 i = GETINDEX(xi, zi, m_cloud_radius_i);
-
- if (!grid[i])
- continue;
-
- v2f p0 = v2f(xi, zi) * cloud_size +
- world_center_of_drawing_in_noise_f;
-
- video::S3DVertex v[4] = {
- video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 0, 1),
- video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 1, 1),
- video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 1, 0),
- video::S3DVertex(0, 0, 0, 0, 0, 0, c_top, 0, 0)};
-
- /*if(zi <= 0 && xi <= 0){
- v[0].Color.setBlue(255);
- v[1].Color.setBlue(255);
- v[2].Color.setBlue(255);
- v[3].Color.setBlue(255);
- }*/
-
- f32 rx = cloud_size / 2.0f;
- // if clouds are flat, the top layer should be at the given height
- f32 ry = m_enable_3d ? m_params.thickness * BS : 0.0f;
- f32 rz = cloud_size / 2;
-
- for (int i = 0; i < num_faces_to_draw; i++) {
- switch (i) {
- case 0: // top
- for (video::S3DVertex &vertex : v) {
- vertex.Normal.set(0, 1, 0);
- }
- v[0].Pos.set(-rx, ry, -rz);
- v[1].Pos.set(-rx, ry, rz);
- v[2].Pos.set(rx, ry, rz);
- v[3].Pos.set(rx, ry, -rz);
- break;
- case 1: // back
- if (INAREA(xi, zi - 1, m_cloud_radius_i)) {
- u32 j = GETINDEX(xi, zi - 1,
- m_cloud_radius_i);
- if (grid[j])
- continue;
- }
- for (video::S3DVertex &vertex : v) {
- vertex.Color = c_side_1;
- vertex.Normal.set(0, 0, -1);
- }
- v[0].Pos.set(-rx, ry, -rz);
- v[1].Pos.set(rx, ry, -rz);
- v[2].Pos.set(rx, 0, -rz);
- v[3].Pos.set(-rx, 0, -rz);
- break;
- case 2: // right
- if (INAREA(xi + 1, zi, m_cloud_radius_i)) {
- u32 j = GETINDEX(xi + 1, zi,
- m_cloud_radius_i);
- if (grid[j])
- continue;
- }
- for (video::S3DVertex &vertex : v) {
- vertex.Color = c_side_2;
- vertex.Normal.set(1, 0, 0);
- }
- v[0].Pos.set(rx, ry, -rz);
- v[1].Pos.set(rx, ry, rz);
- v[2].Pos.set(rx, 0, rz);
- v[3].Pos.set(rx, 0, -rz);
- break;
- case 3: // front
- if (INAREA(xi, zi + 1, m_cloud_radius_i)) {
- u32 j = GETINDEX(xi, zi + 1,
- m_cloud_radius_i);
- if (grid[j])
- continue;
- }
- for (video::S3DVertex &vertex : v) {
- vertex.Color = c_side_1;
- vertex.Normal.set(0, 0, -1);
- }
- v[0].Pos.set(rx, ry, rz);
- v[1].Pos.set(-rx, ry, rz);
- v[2].Pos.set(-rx, 0, rz);
- v[3].Pos.set(rx, 0, rz);
- break;
- case 4: // left
- if (INAREA(xi - 1, zi, m_cloud_radius_i)) {
- u32 j = GETINDEX(xi - 1, zi,
- m_cloud_radius_i);
- if (grid[j])
- continue;
- }
- for (video::S3DVertex &vertex : v) {
- vertex.Color = c_side_2;
- vertex.Normal.set(-1, 0, 0);
- }
- v[0].Pos.set(-rx, ry, rz);
- v[1].Pos.set(-rx, ry, -rz);
- v[2].Pos.set(-rx, 0, -rz);
- v[3].Pos.set(-rx, 0, rz);
- break;
- case 5: // bottom
- for (video::S3DVertex &vertex : v) {
- vertex.Color = c_bottom;
- vertex.Normal.set(0, -1, 0);
- }
- v[0].Pos.set(rx, 0, rz);
- v[1].Pos.set(-rx, 0, rz);
- v[2].Pos.set(-rx, 0, -rz);
- v[3].Pos.set(rx, 0, -rz);
- break;
+ for (s16 zi0= -m_cloud_radius_i; zi0 < m_cloud_radius_i; zi0++)
+ for (s16 xi0= -m_cloud_radius_i; xi0 < m_cloud_radius_i; xi0++)
+ {
+ s16 zi = zi0;
+ s16 xi = xi0;
+ // Draw from front to back (needed for transparency)
+ /*if(zi <= 0)
+ zi = -m_cloud_radius_i - zi;
+ if(xi <= 0)
+ xi = -m_cloud_radius_i - xi;*/
+ // Draw from back to front
+ if(zi >= 0)
+ zi = m_cloud_radius_i - zi - 1;
+ if(xi >= 0)
+ xi = m_cloud_radius_i - xi - 1;
+
+ u32 i = GETINDEX(xi, zi, m_cloud_radius_i);
+
+ if (!grid[i])
+ continue;
+
+ v2f p0 = v2f(xi,zi)*cloud_size + world_center_of_drawing_in_noise_f;
+
+ video::S3DVertex v[4] = {
+ video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 1),
+ video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 1),
+ video::S3DVertex(0,0,0, 0,0,0, c_top, 1, 0),
+ video::S3DVertex(0,0,0, 0,0,0, c_top, 0, 0)
+ };
+
+ /*if(zi <= 0 && xi <= 0){
+ v[0].Color.setBlue(255);
+ v[1].Color.setBlue(255);
+ v[2].Color.setBlue(255);
+ v[3].Color.setBlue(255);
+ }*/
+
+ f32 rx = cloud_size / 2.0f;
+ // if clouds are flat, the top layer should be at the given height
+ f32 ry = m_enable_3d ? m_params.thickness * BS : 0.0f;
+ f32 rz = cloud_size / 2;
+
+ for(int i=0; i<num_faces_to_draw; i++)
+ {
+ switch(i)
+ {
+ case 0: // top
+ for (video::S3DVertex &vertex : v) {
+ vertex.Normal.set(0,1,0);
+ }
+ v[0].Pos.set(-rx, ry,-rz);
+ v[1].Pos.set(-rx, ry, rz);
+ v[2].Pos.set( rx, ry, rz);
+ v[3].Pos.set( rx, ry,-rz);
+ break;
+ case 1: // back
+ if (INAREA(xi, zi - 1, m_cloud_radius_i)) {
+ u32 j = GETINDEX(xi, zi - 1, m_cloud_radius_i);
+ if(grid[j])
+ continue;
+ }
+ for (video::S3DVertex &vertex : v) {
+ vertex.Color = c_side_1;
+ vertex.Normal.set(0,0,-1);
+ }
+ v[0].Pos.set(-rx, ry,-rz);
+ v[1].Pos.set( rx, ry,-rz);
+ v[2].Pos.set( rx, 0,-rz);
+ v[3].Pos.set(-rx, 0,-rz);
+ break;
+ case 2: //right
+ if (INAREA(xi + 1, zi, m_cloud_radius_i)) {
+ u32 j = GETINDEX(xi+1, zi, m_cloud_radius_i);
+ if(grid[j])
+ continue;
+ }
+ for (video::S3DVertex &vertex : v) {
+ vertex.Color = c_side_2;
+ vertex.Normal.set(1,0,0);
+ }
+ v[0].Pos.set( rx, ry,-rz);
+ v[1].Pos.set( rx, ry, rz);
+ v[2].Pos.set( rx, 0, rz);
+ v[3].Pos.set( rx, 0,-rz);
+ break;
+ case 3: // front
+ if (INAREA(xi, zi + 1, m_cloud_radius_i)) {
+ u32 j = GETINDEX(xi, zi + 1, m_cloud_radius_i);
+ if(grid[j])
+ continue;
}
+ for (video::S3DVertex &vertex : v) {
+ vertex.Color = c_side_1;
+ vertex.Normal.set(0,0,-1);
+ }
+ v[0].Pos.set( rx, ry, rz);
+ v[1].Pos.set(-rx, ry, rz);
+ v[2].Pos.set(-rx, 0, rz);
+ v[3].Pos.set( rx, 0, rz);
+ break;
+ case 4: // left
+ if (INAREA(xi-1, zi, m_cloud_radius_i)) {
+ u32 j = GETINDEX(xi-1, zi, m_cloud_radius_i);
+ if(grid[j])
+ continue;
+ }
+ for (video::S3DVertex &vertex : v) {
+ vertex.Color = c_side_2;
+ vertex.Normal.set(-1,0,0);
+ }
+ v[0].Pos.set(-rx, ry, rz);
+ v[1].Pos.set(-rx, ry,-rz);
+ v[2].Pos.set(-rx, 0,-rz);
+ v[3].Pos.set(-rx, 0, rz);
+ break;
+ case 5: // bottom
+ for (video::S3DVertex &vertex : v) {
+ vertex.Color = c_bottom;
+ vertex.Normal.set(0,-1,0);
+ }
+ v[0].Pos.set( rx, 0, rz);
+ v[1].Pos.set(-rx, 0, rz);
+ v[2].Pos.set(-rx, 0,-rz);
+ v[3].Pos.set( rx, 0,-rz);
+ break;
+ }
- v3f pos(p0.X, m_params.height * BS, p0.Y);
- pos -= intToFloat(m_camera_offset, BS);
+ v3f pos(p0.X, m_params.height * BS, p0.Y);
+ pos -= intToFloat(m_camera_offset, BS);
- for (video::S3DVertex &vertex : v)
- vertex.Pos += pos;
- u16 indices[] = {0, 1, 2, 2, 3, 0};
- driver->drawVertexPrimitiveList(v, 4, indices, 2,
- video::EVT_STANDARD, scene::EPT_TRIANGLES,
- video::EIT_16BIT);
- }
+ for (video::S3DVertex &vertex : v)
+ vertex.Pos += pos;
+ u16 indices[] = {0,1,2,2,3,0};
+ driver->drawVertexPrimitiveList(v, 4, indices, 2,
+ video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT);
}
+ }
delete[] grid;
// Restore fog settings
- driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog,
- fog_rangefog);
+ driver->setFog(fog_color, fog_type, fog_start, fog_end, fog_density,
+ fog_pixelfog, fog_rangefog);
}
void Clouds::step(float dtime)
@@ -337,17 +344,11 @@ void Clouds::update(const v3f &camera_p, const video::SColorf &color_diffuse)
{
m_camera_pos = camera_p;
m_color.r = MYMIN(MYMAX(color_diffuse.r * m_params.color_bright.getRed(),
- m_params.color_ambient.getRed()),
- 255) /
- 255.0f;
+ m_params.color_ambient.getRed()), 255) / 255.0f;
m_color.g = MYMIN(MYMAX(color_diffuse.g * m_params.color_bright.getGreen(),
- m_params.color_ambient.getGreen()),
- 255) /
- 255.0f;
+ m_params.color_ambient.getGreen()), 255) / 255.0f;
m_color.b = MYMIN(MYMAX(color_diffuse.b * m_params.color_bright.getBlue(),
- m_params.color_ambient.getBlue()),
- 255) /
- 255.0f;
+ m_params.color_ambient.getBlue()), 255) / 255.0f;
m_color.a = m_params.color_bright.getAlpha() / 255.0f;
// is the camera inside the cloud mesh?
@@ -357,10 +358,8 @@ void Clouds::update(const v3f &camera_p, const video::SColorf &color_diffuse)
if (camera_height >= m_box.MinEdge.Y &&
camera_height <= m_box.MaxEdge.Y) {
v2f camera_in_noise;
- camera_in_noise.X = floor(
- (camera_p.X - m_origin.X) / cloud_size + 0.5);
- camera_in_noise.Y = floor(
- (camera_p.Z - m_origin.Y) / cloud_size + 0.5);
+ camera_in_noise.X = floor((camera_p.X - m_origin.X) / cloud_size + 0.5);
+ camera_in_noise.Y = floor((camera_p.Z - m_origin.Y) / cloud_size + 0.5);
bool filled = gridFilled(camera_in_noise.X, camera_in_noise.Y);
m_camera_inside_cloud = filled;
}
@@ -376,8 +375,10 @@ void Clouds::readSettings()
bool Clouds::gridFilled(int x, int y) const
{
float cloud_size_noise = cloud_size / (BS * 200.f);
- float noise = noise2d_perlin((float)x * cloud_size_noise,
- (float)y * cloud_size_noise, m_seed, 3, 0.5);
+ float noise = noise2d_perlin(
+ (float)x * cloud_size_noise,
+ (float)y * cloud_size_noise,
+ m_seed, 3, 0.5);
// normalize to 0..1 (given 3 octaves)
static constexpr const float noise_bound = 1.0f + 0.5f + 0.25f;
float density = noise / noise_bound * 0.5f + 0.5f;
diff --git a/src/client/clouds.h b/src/client/clouds.h
index ba371de7d..a4d810faa 100644
--- a/src/client/clouds.h
+++ b/src/client/clouds.h
@@ -29,19 +29,16 @@ class Clouds;
extern Clouds *g_menuclouds;
// Scene manager used for menu clouds
-namespace irr
-{
-namespace scene
-{
-class ISceneManager;
-}
-}
+namespace irr{namespace scene{class ISceneManager;}}
extern irr::scene::ISceneManager *g_menucloudsmgr;
class Clouds : public scene::ISceneNode
{
public:
- Clouds(scene::ISceneManager *mgr, s32 id, u32 seed);
+ Clouds(scene::ISceneManager* mgr,
+ s32 id,
+ u32 seed
+ );
~Clouds();
@@ -53,11 +50,20 @@ public:
virtual void render();
- virtual const aabb3f &getBoundingBox() const { return m_box; }
+ virtual const aabb3f &getBoundingBox() const
+ {
+ return m_box;
+ }
- virtual u32 getMaterialCount() const { return 1; }
+ virtual u32 getMaterialCount() const
+ {
+ return 1;
+ }
- virtual video::SMaterial &getMaterial(u32 i) { return m_material; }
+ virtual video::SMaterial& getMaterial(u32 i)
+ {
+ return m_material;
+ }
/*
Other stuff
@@ -97,7 +103,10 @@ public:
updateBox();
}
- void setSpeed(v2f speed) { m_params.speed = speed; }
+ void setSpeed(v2f speed)
+ {
+ m_params.speed = speed;
+ }
void setThickness(float thickness)
{
@@ -112,12 +121,10 @@ public:
private:
void updateBox()
{
- float height_bs = m_params.height * BS;
+ float height_bs = m_params.height * BS;
float thickness_bs = m_params.thickness * BS;
- m_box = aabb3f(-BS * 1000000.0f, height_bs - BS * m_camera_offset.Y,
- -BS * 1000000.0f, BS * 1000000.0f,
- height_bs + thickness_bs - BS * m_camera_offset.Y,
- BS * 1000000.0f);
+ m_box = aabb3f(-BS * 1000000.0f, height_bs - BS * m_camera_offset.Y, -BS * 1000000.0f,
+ BS * 1000000.0f, height_bs + thickness_bs - BS * m_camera_offset.Y, BS * 1000000.0f);
}
bool gridFilled(int x, int y) const;
@@ -133,4 +140,5 @@ private:
video::SColorf m_color = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f);
CloudParams m_params;
bool m_camera_inside_cloud = false;
+
};
diff --git a/src/client/content_cao.cpp b/src/client/content_cao.cpp
index 36a47d57c..cf671d5ca 100644
--- a/src/client/content_cao.cpp
+++ b/src/client/content_cao.cpp
@@ -53,7 +53,8 @@ struct ToolCapabilities;
std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
-template <typename T> void SmoothTranslator<T>::init(T current)
+template<typename T>
+void SmoothTranslator<T>::init(T current)
{
val_old = current;
val_current = current;
@@ -63,9 +64,8 @@ template <typename T> void SmoothTranslator<T>::init(T current)
aim_is_end = true;
}
-template <typename T>
-void SmoothTranslator<T>::update(
- T new_target, bool is_end_position, float update_interval)
+template<typename T>
+void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
{
aim_is_end = is_end_position;
val_old = val_current;
@@ -81,7 +81,8 @@ void SmoothTranslator<T>::update(
anim_time_counter = 0;
}
-template <typename T> void SmoothTranslator<T>::translate(f32 dtime)
+template<typename T>
+void SmoothTranslator<T>::translate(f32 dtime)
{
anim_time_counter = anim_time_counter + dtime;
T val_diff = val_target - val_old;
@@ -109,7 +110,8 @@ void SmoothTranslatorWrapped::translate(f32 dtime)
// Move a bit less than should, to avoid oscillation
moveratio = std::min(moveratio * 0.8f, move_end);
- wrappedApproachShortest(val_current, val_target, val_diff * moveratio, 360.f);
+ wrappedApproachShortest(val_current, val_target,
+ val_diff * moveratio, 360.f);
}
void SmoothTranslatorWrappedv3f::translate(f32 dtime)
@@ -137,26 +139,26 @@ void SmoothTranslatorWrappedv3f::translate(f32 dtime)
// Move a bit less than should, to avoid oscillation
moveratio = std::min(moveratio * 0.8f, move_end);
- wrappedApproachShortest(
- val_current.X, val_target.X, val_diff_v3f.X * moveratio, 360.f);
+ wrappedApproachShortest(val_current.X, val_target.X,
+ val_diff_v3f.X * moveratio, 360.f);
- wrappedApproachShortest(
- val_current.Y, val_target.Y, val_diff_v3f.Y * moveratio, 360.f);
+ wrappedApproachShortest(val_current.Y, val_target.Y,
+ val_diff_v3f.Y * moveratio, 360.f);
- wrappedApproachShortest(
- val_current.Z, val_target.Z, val_diff_v3f.Z * moveratio, 360.f);
+ wrappedApproachShortest(val_current.Z, val_target.Z,
+ val_diff_v3f.Z * moveratio, 360.f);
}
/*
Other stuff
*/
-static void setBillboardTextureMatrix(
- scene::IBillboardSceneNode *bill, float txs, float tys, int col, int row)
+static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
+ float txs, float tys, int col, int row)
{
- video::SMaterial &material = bill->getMaterial(0);
- core::matrix4 &matrix = material.getTextureMatrix(0);
- matrix.setTextureTranslate(txs * col, tys * row);
+ video::SMaterial& material = bill->getMaterial(0);
+ core::matrix4& matrix = material.getTextureMatrix(0);
+ matrix.setTextureTranslate(txs*col, tys*row);
matrix.setTextureScale(txs, tys);
}
@@ -179,9 +181,12 @@ public:
TestCAO(Client *client, ClientEnvironment *env);
virtual ~TestCAO() = default;
- ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; }
+ ActiveObjectType getType() const
+ {
+ return ACTIVEOBJECT_TYPE_TEST;
+ }
- static ClientActiveObject *create(Client *client, ClientEnvironment *env);
+ static ClientActiveObject* create(Client *client, ClientEnvironment *env);
void addToScene(ITextureSource *tsrc);
void removeFromScene(bool permanent);
@@ -193,7 +198,6 @@ public:
void processMessage(const std::string &data);
bool getCollisionBox(aabb3f *toset) const { return false; }
-
private:
scene::IMeshSceneNode *m_node;
v3f m_position;
@@ -202,38 +206,40 @@ private:
// Prototype
TestCAO proto_TestCAO(NULL, NULL);
-TestCAO::TestCAO(Client *client, ClientEnvironment *env) :
- ClientActiveObject(0, client, env), m_node(NULL),
- m_position(v3f(0, 10 * BS, 0))
+TestCAO::TestCAO(Client *client, ClientEnvironment *env):
+ ClientActiveObject(0, client, env),
+ m_node(NULL),
+ m_position(v3f(0,10*BS,0))
{
ClientActiveObject::registerType(getType(), create);
}
-ClientActiveObject *TestCAO::create(Client *client, ClientEnvironment *env)
+ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
{
return new TestCAO(client, env);
}
void TestCAO::addToScene(ITextureSource *tsrc)
{
- if (m_node != NULL)
+ if(m_node != NULL)
return;
- // video::IVideoDriver* driver = smgr->getVideoDriver();
+ //video::IVideoDriver* driver = smgr->getVideoDriver();
scene::SMesh *mesh = new scene::SMesh();
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
- video::SColor c(255, 255, 255, 255);
- video::S3DVertex vertices[4] = {
- video::S3DVertex(-BS / 2, -BS / 4, 0, 0, 0, 0, c, 0, 1),
- video::S3DVertex(BS / 2, -BS / 4, 0, 0, 0, 0, c, 1, 1),
- video::S3DVertex(BS / 2, BS / 4, 0, 0, 0, 0, c, 1, 0),
- video::S3DVertex(-BS / 2, BS / 4, 0, 0, 0, 0, c, 0, 0),
+ video::SColor c(255,255,255,255);
+ video::S3DVertex vertices[4] =
+ {
+ video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
+ video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
+ video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
+ video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
};
- u16 indices[] = {0, 1, 2, 2, 3, 0};
+ u16 indices[] = {0,1,2,2,3,0};
buf->append(vertices, 4, indices, 6);
// Set material
- buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
+ buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
@@ -266,14 +272,15 @@ void TestCAO::updateNodePos()
return;
m_node->setPosition(m_position);
- // m_node->setRotation(v3f(0, 45, 0));
+ //m_node->setRotation(v3f(0, 45, 0));
}
void TestCAO::step(float dtime, ClientEnvironment *env)
{
- if (m_node) {
+ if(m_node)
+ {
v3f rot = m_node->getRotation();
- // infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
+ //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
rot.Y += dtime * 180;
m_node->setRotation(rot);
}
@@ -281,15 +288,16 @@ void TestCAO::step(float dtime, ClientEnvironment *env)
void TestCAO::processMessage(const std::string &data)
{
- infostream << "TestCAO: Got data: " << data << std::endl;
+ infostream<<"TestCAO: Got data: "<<data<<std::endl;
std::istringstream is(data, std::ios::binary);
u16 cmd;
- is >> cmd;
- if (cmd == 0) {
+ is>>cmd;
+ if(cmd == 0)
+ {
v3f newpos;
- is >> newpos.X;
- is >> newpos.Y;
- is >> newpos.Z;
+ is>>newpos.X;
+ is>>newpos.Y;
+ is>>newpos.Z;
m_position = newpos;
updateNodePos();
}
@@ -301,7 +309,7 @@ void TestCAO::processMessage(const std::string &data)
#include "clientobject.h"
-GenericCAO::GenericCAO(Client *client, ClientEnvironment *env) :
+GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
ClientActiveObject(0, client, env)
{
if (client == NULL) {
@@ -313,8 +321,9 @@ GenericCAO::GenericCAO(Client *client, ClientEnvironment *env) :
bool GenericCAO::getCollisionBox(aabb3f *toset) const
{
- if (m_prop.physical) {
- // update collision box
+ if (m_prop.physical)
+ {
+ //update collision box
toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
@@ -334,7 +343,7 @@ bool GenericCAO::collideWithObjects() const
void GenericCAO::initialize(const std::string &data)
{
- infostream << "GenericCAO: Got init data" << std::endl;
+ infostream<<"GenericCAO: Got init data"<<std::endl;
processInitData(data);
if (m_is_player) {
@@ -356,7 +365,8 @@ void GenericCAO::processInitData(const std::string &data)
const u8 version = readU8(is);
if (version < 1) {
- errorstream << "GenericCAO: Unsupported init data version" << std::endl;
+ errorstream << "GenericCAO: Unsupported init data version"
+ << std::endl;
return;
}
@@ -388,8 +398,8 @@ GenericCAO::~GenericCAO()
bool GenericCAO::getSelectionBox(aabb3f *toset) const
{
- if (!m_prop.is_visible || !m_is_visible || m_is_local_player ||
- !m_prop.pointable) {
+ if (!m_prop.is_visible || !m_is_visible || m_is_local_player
+ || !m_prop.pointable) {
return false;
}
*toset = m_selection_box;
@@ -405,7 +415,7 @@ const v3f GenericCAO::getPosition() const
if (m_matrixnode) {
v3s16 camera_offset = m_env->getCameraOffset();
return m_matrixnode->getAbsolutePosition() +
- intToFloat(camera_offset, BS);
+ intToFloat(camera_offset, BS);
}
return m_position;
@@ -451,8 +461,7 @@ void GenericCAO::setChildrenVisible(bool toset)
}
}
-void GenericCAO::setAttachment(
- int parent_id, const std::string &bone, v3f position, v3f rotation)
+void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
{
int old_parent = m_attachment_parent_id;
m_attachment_parent_id = parent_id;
@@ -470,12 +479,12 @@ void GenericCAO::setAttachment(
if (parent)
parent->addAttachmentChild(m_id);
}
-
+
updateAttachments();
}
-void GenericCAO::getAttachment(
- int *parent_id, std::string *bone, v3f *position, v3f *rotation) const
+void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
+ v3f *rotation) const
{
*parent_id = m_attachment_parent_id;
*bone = m_attachment_bone;
@@ -514,10 +523,10 @@ void GenericCAO::removeAttachmentChild(int child_id)
m_attachment_child_ids.erase(child_id);
}
-ClientActiveObject *GenericCAO::getParent() const
+ClientActiveObject* GenericCAO::getParent() const
{
- return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id)
- : nullptr;
+ return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
+ nullptr;
}
void GenericCAO::removeFromScene(bool permanent)
@@ -535,7 +544,7 @@ void GenericCAO::removeFromScene(bool permanent)
m_meshnode->remove();
m_meshnode->drop();
m_meshnode = nullptr;
- } else if (m_animated_meshnode) {
+ } else if (m_animated_meshnode) {
m_animated_meshnode->remove();
m_animated_meshnode->drop();
m_animated_meshnode = nullptr;
@@ -581,30 +590,26 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
MaterialType material_type;
if (m_prop.shaded && m_prop.glow == 0)
- material_type = (m_prop.use_texture_alpha) ? TILE_MATERIAL_ALPHA
- : TILE_MATERIAL_BASIC;
+ material_type = (m_prop.use_texture_alpha) ?
+ TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
else
- material_type = (m_prop.use_texture_alpha)
- ? TILE_MATERIAL_PLAIN_ALPHA
- : TILE_MATERIAL_PLAIN;
+ material_type = (m_prop.use_texture_alpha) ?
+ TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
- u32 shader_id = shader_source->getShader(
- "object_shader", material_type, NDT_NORMAL);
+ u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
m_material_type = shader_source->getShaderInfo(shader_id).material;
} else {
- m_material_type =
- (m_prop.use_texture_alpha)
- ? video::EMT_TRANSPARENT_ALPHA_CHANNEL
- : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
+ m_material_type = (m_prop.use_texture_alpha) ?
+ video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
}
auto grabMatrixNode = [this] {
- m_matrixnode = RenderingEngine::get_scene_manager()
- ->addDummyTransformationSceneNode();
+ m_matrixnode = RenderingEngine::get_scene_manager()->
+ addDummyTransformationSceneNode();
m_matrixnode->grab();
};
- auto setSceneNodeMaterial = [this](scene::ISceneNode *node) {
+ auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
node->setMaterialFlag(video::EMF_LIGHTING, false);
node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
@@ -618,22 +623,21 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
if (m_prop.visual == "sprite") {
grabMatrixNode();
- m_spritenode = RenderingEngine::get_scene_manager()
- ->addBillboardSceneNode(m_matrixnode,
- v2f(1, 1), v3f(0, 0, 0),
- -1);
+ m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
+ m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
m_spritenode->grab();
- m_spritenode->setMaterialTexture(
- 0, tsrc->getTextureForMesh("unknown_node.png"));
+ m_spritenode->setMaterialTexture(0,
+ tsrc->getTextureForMesh("unknown_node.png"));
setSceneNodeMaterial(m_spritenode);
- m_spritenode->setSize(
- v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
+ m_spritenode->setSize(v2f(m_prop.visual_size.X,
+ m_prop.visual_size.Y) * BS);
{
const float txs = 1.0 / 1;
const float tys = 1.0 / 1;
- setBillboardTextureMatrix(m_spritenode, txs, tys, 0, 0);
+ setBillboardTextureMatrix(m_spritenode,
+ txs, tys, 0, 0);
}
} else if (m_prop.visual == "upright_sprite") {
grabMatrixNode();
@@ -645,17 +649,17 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
{ // Front
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
video::S3DVertex vertices[4] = {
- video::S3DVertex(-dx, -dy, 0, 0, 0, 1, c, 1, 1),
- video::S3DVertex(dx, -dy, 0, 0, 0, 1, c, 0, 1),
- video::S3DVertex(dx, dy, 0, 0, 0, 1, c, 0, 0),
- video::S3DVertex(-dx, dy, 0, 0, 0, 1, c, 1, 0),
+ video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
+ video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
+ video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
+ video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
};
if (m_is_player) {
// Move minimal Y position to 0 (feet position)
for (video::S3DVertex &vertex : vertices)
vertex.Pos.Y += dy;
}
- u16 indices[] = {0, 1, 2, 2, 3, 0};
+ u16 indices[] = {0,1,2,2,3,0};
buf->append(vertices, 4, indices, 6);
// Set material
buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
@@ -665,10 +669,8 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
if (m_enable_shaders) {
buf->getMaterial().EmissiveColor = c;
- buf->getMaterial().setFlag(
- video::EMF_GOURAUD_SHADING, false);
- buf->getMaterial().setFlag(
- video::EMF_NORMALIZE_NORMALS, true);
+ buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
+ buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
}
// Add to mesh
@@ -678,17 +680,17 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
{ // Back
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
video::S3DVertex vertices[4] = {
- video::S3DVertex(dx, -dy, 0, 0, 0, -1, c, 1, 1),
- video::S3DVertex(-dx, -dy, 0, 0, 0, -1, c, 0, 1),
- video::S3DVertex(-dx, dy, 0, 0, 0, -1, c, 0, 0),
- video::S3DVertex(dx, dy, 0, 0, 0, -1, c, 1, 0),
+ video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
+ video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
+ video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
+ video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
};
if (m_is_player) {
// Move minimal Y position to 0 (feet position)
for (video::S3DVertex &vertex : vertices)
vertex.Pos.Y += dy;
}
- u16 indices[] = {0, 1, 2, 2, 3, 0};
+ u16 indices[] = {0,1,2,2,3,0};
buf->append(vertices, 4, indices, 6);
// Set material
buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
@@ -698,18 +700,16 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
if (m_enable_shaders) {
buf->getMaterial().EmissiveColor = c;
- buf->getMaterial().setFlag(
- video::EMF_GOURAUD_SHADING, false);
- buf->getMaterial().setFlag(
- video::EMF_NORMALIZE_NORMALS, true);
+ buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
+ buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
}
// Add to mesh
mesh->addMeshBuffer(buf);
buf->drop();
}
- m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(
- mesh, m_matrixnode);
+ m_meshnode = RenderingEngine::get_scene_manager()->
+ addMeshSceneNode(mesh, m_matrixnode);
m_meshnode->grab();
mesh->drop();
// Set it to use the materials of the meshbuffers directly.
@@ -717,54 +717,47 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
m_meshnode->setReadOnlyMaterials(true);
} else if (m_prop.visual == "cube") {
grabMatrixNode();
- scene::IMesh *mesh = createCubeMesh(v3f(BS, BS, BS));
- m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(
- mesh, m_matrixnode);
+ scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
+ m_meshnode = RenderingEngine::get_scene_manager()->
+ addMeshSceneNode(mesh, m_matrixnode);
m_meshnode->grab();
mesh->drop();
m_meshnode->setScale(m_prop.visual_size);
- m_meshnode->setMaterialFlag(
- video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
+ m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
+ m_prop.backface_culling);
setSceneNodeMaterial(m_meshnode);
} else if (m_prop.visual == "mesh") {
grabMatrixNode();
scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
if (mesh) {
- m_animated_meshnode =
- RenderingEngine::get_scene_manager()
- ->addAnimatedMeshSceneNode(mesh,
- m_matrixnode);
+ m_animated_meshnode = RenderingEngine::get_scene_manager()->
+ addAnimatedMeshSceneNode(mesh, m_matrixnode);
m_animated_meshnode->grab();
mesh->drop(); // The scene node took hold of it
if (!checkMeshNormals(mesh)) {
- infostream << "GenericCAO: recalculating normals for "
- "mesh "
- << m_prop.mesh << std::endl;
- m_smgr->getMeshManipulator()->recalculateNormals(
- mesh, true, false);
+ infostream << "GenericCAO: recalculating normals for mesh "
+ << m_prop.mesh << std::endl;
+ m_smgr->getMeshManipulator()->
+ recalculateNormals(mesh, true, false);
}
- m_animated_meshnode
- ->animateJoints(); // Needed for some animations
+ m_animated_meshnode->animateJoints(); // Needed for some animations
m_animated_meshnode->setScale(m_prop.visual_size);
// set vertex colors to ensure alpha is set
- setMeshColor(m_animated_meshnode->getMesh(),
- video::SColor(0xFFFFFFFF));
+ setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
- setAnimatedMeshColor(
- m_animated_meshnode, video::SColor(0xFFFFFFFF));
+ setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
setSceneNodeMaterial(m_animated_meshnode);
m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
- m_prop.backface_culling);
+ m_prop.backface_culling);
} else
- errorstream << "GenericCAO::addToScene(): Could not load mesh "
- << m_prop.mesh << std::endl;
+ errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
} else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
grabMatrixNode();
ItemStack item;
@@ -773,24 +766,24 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
infostream << "textures: " << m_prop.textures.size() << std::endl;
if (!m_prop.textures.empty()) {
infostream << "textures[0]: " << m_prop.textures[0]
- << std::endl;
+ << std::endl;
IItemDefManager *idef = m_client->idef();
item = ItemStack(m_prop.textures[0], 1, 0, idef);
}
} else {
- infostream << "serialized form: " << m_prop.wield_item
- << std::endl;
+ infostream << "serialized form: " << m_prop.wield_item << std::endl;
item.deSerialize(m_prop.wield_item, m_client->idef());
}
m_wield_meshnode = new WieldMeshSceneNode(
- RenderingEngine::get_scene_manager(), -1);
- m_wield_meshnode->setItem(item, m_client, (m_prop.visual == "wielditem"));
+ RenderingEngine::get_scene_manager(), -1);
+ m_wield_meshnode->setItem(item, m_client,
+ (m_prop.visual == "wielditem"));
m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
} else {
- infostream << "GenericCAO::addToScene(): \"" << m_prop.visual
- << "\" not supported" << std::endl;
+ infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
+ <<"\" not supported"<<std::endl;
}
/* don't update while punch texture modifier is active */
@@ -811,7 +804,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc)
}
void GenericCAO::updateLight(u32 day_night_ratio)
-{
+{
if (m_glow < 0)
return;
@@ -820,15 +813,14 @@ void GenericCAO::updateLight(u32 day_night_ratio)
if (g_settings->getBool("fullbright"))
light_at_pos = 255;
-
+
v3s16 pos[3];
u16 npos = getLightPosition(pos);
for (u16 i = 0; i < npos; i++) {
bool this_ok;
MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
if (this_ok) {
- u8 this_light = n.getLightBlend(
- day_night_ratio, m_client->ndef());
+ u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
light_at_pos = MYMAX(light_at_pos, this_light);
pos_ok = true;
}
@@ -899,8 +891,7 @@ u16 GenericCAO::getLightPosition(v3s16 *pos)
void GenericCAO::updateNametag()
{
- if (m_is_local_player &&
- !g_settings->getBool("freecam")) // No nametag for local player
+ if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
return;
if (m_prop.nametag.empty()) {
@@ -920,8 +911,8 @@ void GenericCAO::updateNametag()
pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
if (!m_nametag) {
// Add nametag
- m_nametag = m_client->getCamera()->addNametag(
- node, m_prop.nametag, m_prop.nametag_color, pos);
+ m_nametag = m_client->getCamera()->addNametag(node,
+ m_prop.nametag, m_prop.nametag_color, pos);
} else {
// Update nametag
m_nametag->nametag_text = m_prop.nametag;
@@ -939,11 +930,11 @@ void GenericCAO::updateNodePos()
if (node) {
v3s16 camera_offset = m_env->getCameraOffset();
- v3f pos = pos_translator.val_current - intToFloat(camera_offset, BS);
+ v3f pos = pos_translator.val_current -
+ intToFloat(camera_offset, BS);
getPosRotMatrix().setTranslation(pos);
if (node != m_spritenode) { // rotate if not a sprite
- v3f rot = m_is_local_player ? -m_rotation
- : -rot_translator.val_current;
+ v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
setPitchYawRoll(getPosRotMatrix(), rot);
}
}
@@ -956,7 +947,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
LocalPlayer *player = m_env->getLocalPlayer();
m_position = player->getLegitPosition();
pos_translator.val_current = m_position;
- if (!g_settings->getBool("freecam")) {
+ if (! g_settings->getBool("freecam")) {
m_rotation.Y = wrapDegrees_0_360(player->getYaw());
rot_translator.val_current = m_rotation;
}
@@ -964,43 +955,39 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
if (m_is_visible) {
int old_anim = player->last_animation;
float old_anim_speed = player->last_animation_speed;
- m_velocity = v3f(0, 0, 0);
- m_acceleration = v3f(0, 0, 0);
+ m_velocity = v3f(0,0,0);
+ m_acceleration = v3f(0,0,0);
const PlayerControl &controls = player->getPlayerControl();
bool walking = false;
- if ((controls.up || controls.down || controls.left ||
- controls.right ||
- controls.forw_move_joystick_axis != 0.f ||
- controls.sidew_move_joystick_axis != 0.f) &&
- !g_settings->getBool("freecam"))
+ if ((controls.up || controls.down || controls.left || controls.right ||
+ controls.forw_move_joystick_axis != 0.f ||
+ controls.sidew_move_joystick_axis != 0.f) && ! g_settings->getBool("freecam"))
walking = true;
f32 new_speed = player->local_animation_speed;
- v2s32 new_anim = v2s32(0, 0);
+ v2s32 new_anim = v2s32(0,0);
bool allow_update = false;
// increase speed if using fast or flying fast
- if ((g_settings->getBool("fast_move") &&
- m_client->checkLocalPrivilege("fast")) &&
+ if((g_settings->getBool("fast_move") &&
+ m_client->checkLocalPrivilege("fast")) &&
(controls.aux1 ||
- (!player->touching_ground &&
- g_settings->getBool(
- "free_move") &&
- m_client->checkLocalPrivilege(
- "fly"))))
- new_speed *= 1.5;
+ (!player->touching_ground &&
+ g_settings->getBool("free_move") &&
+ m_client->checkLocalPrivilege("fly"))))
+ new_speed *= 1.5;
// slowdown speed if sneeking
- if (controls.sneak && walking && !g_settings->getBool("no_slow"))
+ if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
new_speed /= 2;
if (walking && (controls.LMB || controls.RMB)) {
new_anim = player->local_animations[3];
player->last_animation = WD_ANIM;
- } else if (walking) {
+ } else if(walking) {
new_anim = player->local_animations[1];
player->last_animation = WALK_ANIM;
- } else if (controls.LMB || controls.RMB) {
+ } else if(controls.LMB || controls.RMB) {
new_anim = player->local_animations[2];
player->last_animation = DIG_ANIM;
}
@@ -1023,9 +1010,10 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
// Update local player animations
if ((player->last_animation != old_anim ||
- m_animation_speed != old_anim_speed) &&
- player->last_animation != NO_ANIM && allow_update)
- updateAnimation();
+ m_animation_speed != old_anim_speed) &&
+ player->last_animation != NO_ANIM && allow_update)
+ updateAnimation();
+
}
}
@@ -1038,20 +1026,17 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
ClientActiveObject *obj = m_env->getActiveObject(cao_id);
if (obj) {
scene::ISceneNode *child_node = obj->getSceneNode();
- // The node's parent is always an
- // IDummyTraformationSceneNode, so we need to reparent
- // that one instead.
+ // The node's parent is always an IDummyTraformationSceneNode,
+ // so we need to reparent that one instead.
if (child_node)
- child_node->getParent()->setParent(
- m_smgr->getRootSceneNode());
+ child_node->getParent()->setParent(m_smgr->getRootSceneNode());
}
}
removeFromScene(false);
addToScene(m_client->tsrc());
- // Attachments, part 2: Now that the parent has been refreshed, put its
- // attachments back
+ // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
for (u16 cao_id : m_attachment_child_ids) {
ClientActiveObject *obj = m_env->getActiveObject(cao_id);
if (obj)
@@ -1064,31 +1049,31 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
if (node)
node->setVisible(m_is_visible);
- if (getParent() !=
- NULL) // Attachments should be glued to their parent by Irrlicht
+ if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
{
// Set these for later
m_position = getPosition();
- m_velocity = v3f(0, 0, 0);
- m_acceleration = v3f(0, 0, 0);
+ m_velocity = v3f(0,0,0);
+ m_acceleration = v3f(0,0,0);
pos_translator.val_current = m_position;
pos_translator.val_target = m_position;
} else {
rot_translator.translate(dtime);
v3f lastpos = pos_translator.val_current;
- if (m_prop.physical) {
+ if(m_prop.physical)
+ {
aabb3f box = m_prop.collisionbox;
box.MinEdge *= BS;
box.MaxEdge *= BS;
collisionMoveResult moveresult;
- f32 pos_max_d = BS * 0.125; // Distance per iteration
+ f32 pos_max_d = BS*0.125; // Distance per iteration
v3f p_pos = m_position;
v3f p_velocity = m_velocity;
- moveresult = collisionMoveSimple(env, env->getGameDef(),
- pos_max_d, box, m_prop.stepheight, dtime, &p_pos,
- &p_velocity, m_acceleration, this,
- m_prop.collideWithObjects);
+ moveresult = collisionMoveSimple(env,env->getGameDef(),
+ pos_max_d, box, m_prop.stepheight, dtime,
+ &p_pos, &p_velocity, m_acceleration,
+ this, m_prop.collideWithObjects);
// Apply results
m_position = p_pos;
m_velocity = p_velocity;
@@ -1096,8 +1081,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
bool is_end_position = moveresult.collides;
pos_translator.update(m_position, is_end_position, dtime);
} else {
- m_position += dtime * m_velocity +
- 0.5 * dtime * dtime * m_acceleration;
+ m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
m_velocity += dtime * m_acceleration;
pos_translator.update(m_position, pos_translator.aim_is_end,
pos_translator.anim_time);
@@ -1111,62 +1095,56 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
m_step_distance_counter = 0.0f;
if (!m_is_local_player && m_prop.makes_footstep_sound) {
const NodeDefManager *ndef = m_client->ndef();
- v3s16 p = floatToInt(
- getPosition() + v3f(0.0f,
- (m_prop.collisionbox.MinEdge.Y -
- 0.5f) *
- BS,
- 0.0f),
- BS);
+ v3s16 p = floatToInt(getPosition() +
+ v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
MapNode n = m_env->getMap().getNode(p);
SimpleSoundSpec spec = ndef->get(n).sound_footstep;
// Reduce footstep gain, as non-local-player footsteps are
// somehow louder.
spec.gain *= 0.6f;
- m_client->sound()->playSoundAt(
- spec, false, getPosition());
+ m_client->sound()->playSoundAt(spec, false, getPosition());
}
}
}
m_anim_timer += dtime;
- if (m_anim_timer >= m_anim_framelength) {
+ if(m_anim_timer >= m_anim_framelength)
+ {
m_anim_timer -= m_anim_framelength;
m_anim_frame++;
- if (m_anim_frame >= m_anim_num_frames)
+ if(m_anim_frame >= m_anim_num_frames)
m_anim_frame = 0;
}
updateTexturePos();
- if (m_reset_textures_timer >= 0) {
+ if(m_reset_textures_timer >= 0)
+ {
m_reset_textures_timer -= dtime;
- if (m_reset_textures_timer <= 0) {
+ if(m_reset_textures_timer <= 0) {
m_reset_textures_timer = -1;
updateTextures(m_previous_texture_modifier);
}
}
if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
- // This is the child node's rotation. It is only used for
- // automatic_rotate.
+ // This is the child node's rotation. It is only used for automatic_rotate.
v3f local_rot = node->getRotation();
- local_rot.Y = modulo360f(
- local_rot.Y -
- dtime * core::RADTODEG * m_prop.automatic_rotate);
+ local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
+ m_prop.automatic_rotate);
node->setRotation(local_rot);
}
if (!getParent() && m_prop.automatic_face_movement_dir &&
(fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
- float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI +
- m_prop.automatic_face_movement_dir_offset;
+ float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
+ + m_prop.automatic_face_movement_dir_offset;
float max_rotation_per_sec =
m_prop.automatic_face_movement_max_rotation_per_sec;
if (max_rotation_per_sec > 0) {
wrappedApproachShortest(m_rotation.Y, target_yaw,
- dtime * max_rotation_per_sec, 360.f);
+ dtime * max_rotation_per_sec, 360.f);
} else {
// Negative values of max_rotation_per_sec mean disabled.
m_rotation.Y = target_yaw;
@@ -1191,13 +1169,14 @@ void GenericCAO::step(float dtime, ClientEnvironment *env)
void GenericCAO::updateTexturePos()
{
- if (m_spritenode) {
- scene::ICameraSceneNode *camera =
+ if(m_spritenode)
+ {
+ scene::ICameraSceneNode* camera =
m_spritenode->getSceneManager()->getActiveCamera();
- if (!camera)
+ if(!camera)
return;
- v3f cam_to_entity = m_spritenode->getAbsolutePosition() -
- camera->getAbsolutePosition();
+ v3f cam_to_entity = m_spritenode->getAbsolutePosition()
+ - camera->getAbsolutePosition();
cam_to_entity.normalize();
int row = m_tx_basepos.Y;
@@ -1209,17 +1188,17 @@ void GenericCAO::updateTexturePos()
else if (cam_to_entity.Y < -0.75)
col += 4;
else {
- float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) /
- M_PI * 180.;
+ float mob_dir =
+ atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
float dir = mob_dir - m_rotation.Y;
dir = wrapDegrees_180(dir);
if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
col += 2;
- else if (std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
+ else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
col += 3;
- else if (std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
+ else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
col += 0;
- else if (std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
+ else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
col += 1;
else
col += 4;
@@ -1256,106 +1235,87 @@ void GenericCAO::updateTextures(std::string mod)
texturestring += mod;
m_spritenode->getMaterial(0).MaterialType = m_material_type;
m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
- m_spritenode->setMaterialTexture(
- 0, tsrc->getTextureForMesh(texturestring));
+ m_spritenode->setMaterialTexture(0,
+ tsrc->getTextureForMesh(texturestring));
- // This allows setting per-material colors. However, until a real
- // lighting system is added, the code below will have no effect.
- // Once MineTest has directional lighting, it should work
- // automatically.
+ // This allows setting per-material colors. However, until a real lighting
+ // system is added, the code below will have no effect. Once MineTest
+ // has directional lighting, it should work automatically.
if (!m_prop.colors.empty()) {
- m_spritenode->getMaterial(0).AmbientColor =
- m_prop.colors[0];
- m_spritenode->getMaterial(0).DiffuseColor =
- m_prop.colors[0];
- m_spritenode->getMaterial(0).SpecularColor =
- m_prop.colors[0];
+ m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
+ m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
+ m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
}
- m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER,
- use_trilinear_filter);
- m_spritenode->getMaterial(0).setFlag(
- video::EMF_BILINEAR_FILTER, use_bilinear_filter);
- m_spritenode->getMaterial(0).setFlag(
- video::EMF_ANISOTROPIC_FILTER,
- use_anisotropic_filter);
+ m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
+ m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
+ m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
}
}
if (m_animated_meshnode) {
if (m_prop.visual == "mesh") {
for (u32 i = 0; i < m_prop.textures.size() &&
- i < m_animated_meshnode->getMaterialCount();
- ++i) {
+ i < m_animated_meshnode->getMaterialCount(); ++i) {
std::string texturestring = m_prop.textures[i];
if (texturestring.empty())
- continue; // Empty texture string means don't
- // modify that material
+ continue; // Empty texture string means don't modify that material
texturestring += mod;
- video::ITexture *texture =
- tsrc->getTextureForMesh(texturestring);
+ video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
if (!texture) {
- errorstream << "GenericCAO::updateTextures(): "
- "Could not load texture "
- << texturestring << std::endl;
+ errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
continue;
}
// Set material flags and texture
- video::SMaterial &material =
- m_animated_meshnode->getMaterial(i);
+ video::SMaterial& material = m_animated_meshnode->getMaterial(i);
material.MaterialType = m_material_type;
material.MaterialTypeParam = 0.5f;
material.TextureLayer[0].Texture = texture;
material.setFlag(video::EMF_LIGHTING, true);
material.setFlag(video::EMF_BILINEAR_FILTER, false);
- material.setFlag(video::EMF_BACK_FACE_CULLING,
- m_prop.backface_culling);
+ material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
// don't filter low-res textures, makes them look blurry
// player models have a res of 64
- const core::dimension2d<u32> &size =
- texture->getOriginalSize();
+ const core::dimension2d<u32> &size = texture->getOriginalSize();
const u32 res = std::min(size.Height, size.Width);
use_trilinear_filter &= res > 64;
use_bilinear_filter &= res > 64;
- m_animated_meshnode->getMaterial(i).setFlag(
- video::EMF_TRILINEAR_FILTER,
- use_trilinear_filter);
- m_animated_meshnode->getMaterial(i).setFlag(
- video::EMF_BILINEAR_FILTER,
- use_bilinear_filter);
- m_animated_meshnode->getMaterial(i).setFlag(
- video::EMF_ANISOTROPIC_FILTER,
- use_anisotropic_filter);
+ m_animated_meshnode->getMaterial(i)
+ .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
+ m_animated_meshnode->getMaterial(i)
+ .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
+ m_animated_meshnode->getMaterial(i)
+ .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
}
for (u32 i = 0; i < m_prop.colors.size() &&
- i < m_animated_meshnode->getMaterialCount();
- ++i) {
- // This allows setting per-material colors. However, until
- // a real lighting system is added, the code below will
- // have no effect. Once MineTest has directional lighting,
- // it should work automatically.
- m_animated_meshnode->getMaterial(i).AmbientColor =
- m_prop.colors[i];
- m_animated_meshnode->getMaterial(i).DiffuseColor =
- m_prop.colors[i];
- m_animated_meshnode->getMaterial(i).SpecularColor =
- m_prop.colors[i];
+ i < m_animated_meshnode->getMaterialCount(); ++i)
+ {
+ // This allows setting per-material colors. However, until a real lighting
+ // system is added, the code below will have no effect. Once MineTest
+ // has directional lighting, it should work automatically.
+ m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
+ m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
+ m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
}
}
}
- if (m_meshnode) {
- if (m_prop.visual == "cube") {
- for (u32 i = 0; i < 6; ++i) {
+ if(m_meshnode)
+ {
+ if(m_prop.visual == "cube")
+ {
+ for (u32 i = 0; i < 6; ++i)
+ {
std::string texturestring = "unknown_node.png";
- if (m_prop.textures.size() > i)
+ if(m_prop.textures.size() > i)
texturestring = m_prop.textures[i];
texturestring += mod;
+
// Set material flags and texture
- video::SMaterial &material = m_meshnode->getMaterial(i);
+ video::SMaterial& material = m_meshnode->getMaterial(i);
material.MaterialType = m_material_type;
material.MaterialTypeParam = 0.5f;
material.setFlag(video::EMF_LIGHTING, false);
@@ -1364,28 +1324,19 @@ void GenericCAO::updateTextures(std::string mod)
tsrc->getTextureForMesh(texturestring));
material.getTextureMatrix(0).makeIdentity();
- // This allows setting per-material colors. However, until
- // a real lighting system is added, the code below will
- // have no effect. Once MineTest has directional lighting,
- // it should work automatically.
- if (m_prop.colors.size() > i) {
- m_meshnode->getMaterial(i).AmbientColor =
- m_prop.colors[i];
- m_meshnode->getMaterial(i).DiffuseColor =
- m_prop.colors[i];
- m_meshnode->getMaterial(i).SpecularColor =
- m_prop.colors[i];
+ // This allows setting per-material colors. However, until a real lighting
+ // system is added, the code below will have no effect. Once MineTest
+ // has directional lighting, it should work automatically.
+ if(m_prop.colors.size() > i)
+ {
+ m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
+ m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
+ m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
}
- m_meshnode->getMaterial(i).setFlag(
- video::EMF_TRILINEAR_FILTER,
- use_trilinear_filter);
- m_meshnode->getMaterial(i).setFlag(
- video::EMF_BILINEAR_FILTER,
- use_bilinear_filter);
- m_meshnode->getMaterial(i).setFlag(
- video::EMF_ANISOTROPIC_FILTER,
- use_anisotropic_filter);
+ m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
+ m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
+ m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
}
} else if (m_prop.visual == "upright_sprite") {
scene::IMesh *mesh = m_meshnode->getMesh();
@@ -1395,28 +1346,21 @@ void GenericCAO::updateTextures(std::string mod)
tname = m_prop.textures[0];
tname += mod;
scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
- buf->getMaterial().setTexture(
- 0, tsrc->getTextureForMesh(tname));
-
- // This allows setting per-material colors. However, until
- // a real lighting system is added, the code below will
- // have no effect. Once MineTest has directional lighting,
- // it should work automatically.
- if (!m_prop.colors.empty()) {
- buf->getMaterial().AmbientColor =
- m_prop.colors[0];
- buf->getMaterial().DiffuseColor =
- m_prop.colors[0];
- buf->getMaterial().SpecularColor =
- m_prop.colors[0];
+ buf->getMaterial().setTexture(0,
+ tsrc->getTextureForMesh(tname));
+
+ // This allows setting per-material colors. However, until a real lighting
+ // system is added, the code below will have no effect. Once MineTest
+ // has directional lighting, it should work automatically.
+ if(!m_prop.colors.empty()) {
+ buf->getMaterial().AmbientColor = m_prop.colors[0];
+ buf->getMaterial().DiffuseColor = m_prop.colors[0];
+ buf->getMaterial().SpecularColor = m_prop.colors[0];
}
- buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER,
- use_trilinear_filter);
- buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER,
- use_bilinear_filter);
- buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER,
- use_anisotropic_filter);
+ buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
+ buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
+ buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
}
{
std::string tname = "unknown_object.png";
@@ -1426,35 +1370,25 @@ void GenericCAO::updateTextures(std::string mod)
tname = m_prop.textures[0];
tname += mod;
scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
- buf->getMaterial().setTexture(
- 0, tsrc->getTextureForMesh(tname));
+ buf->getMaterial().setTexture(0,
+ tsrc->getTextureForMesh(tname));
- // This allows setting per-material colors. However, until
- // a real lighting system is added, the code below will
- // have no effect. Once MineTest has directional lighting,
- // it should work automatically.
+ // This allows setting per-material colors. However, until a real lighting
+ // system is added, the code below will have no effect. Once MineTest
+ // has directional lighting, it should work automatically.
if (m_prop.colors.size() >= 2) {
- buf->getMaterial().AmbientColor =
- m_prop.colors[1];
- buf->getMaterial().DiffuseColor =
- m_prop.colors[1];
- buf->getMaterial().SpecularColor =
- m_prop.colors[1];
+ buf->getMaterial().AmbientColor = m_prop.colors[1];
+ buf->getMaterial().DiffuseColor = m_prop.colors[1];
+ buf->getMaterial().SpecularColor = m_prop.colors[1];
} else if (!m_prop.colors.empty()) {
- buf->getMaterial().AmbientColor =
- m_prop.colors[0];
- buf->getMaterial().DiffuseColor =
- m_prop.colors[0];
- buf->getMaterial().SpecularColor =
- m_prop.colors[0];
+ buf->getMaterial().AmbientColor = m_prop.colors[0];
+ buf->getMaterial().DiffuseColor = m_prop.colors[0];
+ buf->getMaterial().SpecularColor = m_prop.colors[0];
}
- buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER,
- use_trilinear_filter);
- buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER,
- use_bilinear_filter);
- buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER,
- use_anisotropic_filter);
+ buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
+ buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
+ buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
}
// Set mesh color (only if lighting is disabled)
if (!m_prop.colors.empty() && m_glow < 0)
@@ -1469,15 +1403,13 @@ void GenericCAO::updateAnimation()
return;
if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
- m_animated_meshnode->getEndFrame() != m_animation_range.Y)
- m_animated_meshnode->setFrameLoop(
- m_animation_range.X, m_animation_range.Y);
+ m_animated_meshnode->getEndFrame() != m_animation_range.Y)
+ m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
m_animated_meshnode->setAnimationSpeed(m_animation_speed);
m_animated_meshnode->setTransitionTime(m_animation_blend);
// Requires Irrlicht 1.8 or greater
-#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || \
- IRRLICHT_VERSION_MAJOR > 1
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
if (m_animated_meshnode->getLoopMode() != m_animation_loop)
m_animated_meshnode->setLoopMode(m_animation_loop);
#endif
@@ -1496,13 +1428,10 @@ void GenericCAO::updateBonePosition()
if (m_bone_position.empty() || !m_animated_meshnode)
return;
- m_animated_meshnode->setJointMode(
- irr::scene::EJUOR_CONTROL); // To write positions to the mesh on
- // render
+ m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
for (auto &it : m_bone_position) {
std::string bone_name = it.first;
- irr::scene::IBoneSceneNode *bone =
- m_animated_meshnode->getJointNode(bone_name.c_str());
+ irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
if (bone) {
bone->setPosition(it.second.X);
bone->setRotation(it.second.Y);
@@ -1515,8 +1444,7 @@ void GenericCAO::updateBonePosition()
if (!bone)
continue;
- // If bone is manually positioned there is no need to perform the bug
- // check
+ //If bone is manually positioned there is no need to perform the bug check
bool skip = false;
for (auto &it : m_bone_position) {
if (it.first == bone->getName()) {
@@ -1528,10 +1456,9 @@ void GenericCAO::updateBonePosition()
continue;
// Workaround for Irrlicht bug
- // We check each bone to see if it has been rotated ~180deg from its
- // expected position due to a bug in Irricht when using EJUOR_CONTROL
- // joint control. If the bug is detected we update the bone to the proper
- // position and update the bones transformation.
+ // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
+ // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
+ // and update the bones transformation.
v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
float offset = fabsf(bone_rot.X - bone->getRotation().X);
if (offset > 179.9f && offset < 180.1f) {
@@ -1577,26 +1504,25 @@ void GenericCAO::updateAttachments()
v3f old_pos = getPosition();
m_matrixnode->setParent(m_smgr->getRootSceneNode());
- getPosRotMatrix().setTranslation(
- old_pos - intToFloat(camera_offset, BS));
+ getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
m_matrixnode->updateAbsolutePosition();
}
- } else // Attach
+ }
+ else // Attach
{
parent->updateAttachments();
scene::ISceneNode *parent_node = parent->getSceneNode();
scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
parent->getAnimatedMeshSceneNode();
if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
- parent_node = parent_animated_mesh_node->getJointNode(
- m_attachment_bone.c_str());
+ parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
}
if (m_matrixnode && parent_node) {
m_matrixnode->setParent(parent_node);
parent_node->updateAbsolutePosition();
getPosRotMatrix().setTranslation(m_attachment_position);
- // setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
+ //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
// use Irrlicht eulers instead
getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
m_matrixnode->updateAbsolutePosition();
@@ -1616,20 +1542,23 @@ bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
*/
bool uses_legacy_texture = new_.wield_item.empty() &&
- (new_.visual == "wielditem" || new_.visual == "item");
+ (new_.visual == "wielditem" || new_.visual == "item");
// Ordered to compare primitive types before std::vectors
return old.backface_culling != new_.backface_culling ||
- old.is_visible != new_.is_visible || old.mesh != new_.mesh ||
- old.shaded != new_.shaded ||
- old.use_texture_alpha != new_.use_texture_alpha ||
- old.visual != new_.visual || old.visual_size != new_.visual_size ||
- old.wield_item != new_.wield_item || old.colors != new_.colors ||
- (uses_legacy_texture && old.textures != new_.textures);
+ old.is_visible != new_.is_visible ||
+ old.mesh != new_.mesh ||
+ old.shaded != new_.shaded ||
+ old.use_texture_alpha != new_.use_texture_alpha ||
+ old.visual != new_.visual ||
+ old.visual_size != new_.visual_size ||
+ old.wield_item != new_.wield_item ||
+ old.colors != new_.colors ||
+ (uses_legacy_texture && old.textures != new_.textures);
}
void GenericCAO::processMessage(const std::string &data)
{
- // infostream<<"GenericCAO: Got message"<<std::endl;
+ //infostream<<"GenericCAO: Got message"<<std::endl;
std::istringstream is(data, std::ios::binary);
// command
u8 cmd = readU8(is);
@@ -1651,7 +1580,7 @@ void GenericCAO::processMessage(const std::string &data)
m_tx_size.X = 1.0f / m_prop.spritediv.X;
m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
- if (!m_initial_tx_basepos_set) {
+ if(!m_initial_tx_basepos_set){
m_initial_tx_basepos_set = true;
m_tx_basepos = m_prop.initial_sprite_basepos;
}
@@ -1672,9 +1601,8 @@ void GenericCAO::processMessage(const std::string &data)
if (expire_visuals) {
expireVisuals();
} else {
- infostream << "GenericCAO: properties updated but expiring "
- "visuals"
- << " not necessary" << std::endl;
+ infostream << "GenericCAO: properties updated but expiring visuals"
+ << " not necessary" << std::endl;
if (textures_changed) {
// don't update while punch texture modifier is active
if (m_reset_textures_timer < 0)
@@ -1684,8 +1612,7 @@ void GenericCAO::processMessage(const std::string &data)
}
} else if (cmd == AO_CMD_UPDATE_POSITION) {
// Not sent by the server if this object is an attachment.
- // We might however get here if the server notices the object being
- // detached before the client.
+ // We might however get here if the server notices the object being detached before the client.
m_position = readV3F32(is);
m_velocity = readV3F32(is);
m_acceleration = readV3F32(is);
@@ -1698,16 +1625,16 @@ void GenericCAO::processMessage(const std::string &data)
// Place us a bit higher if we're physical, to not sink into
// the ground due to sucky collision detection...
- if (m_prop.physical)
- m_position += v3f(0, 0.002, 0);
+ if(m_prop.physical)
+ m_position += v3f(0,0.002,0);
- if (getParent() != NULL) // Just in case
+ if(getParent() != NULL) // Just in case
return;
- if (do_interpolate) {
- if (!m_prop.physical)
- pos_translator.update(m_position, is_end_position,
- update_interval);
+ if(do_interpolate)
+ {
+ if(!m_prop.physical)
+ pos_translator.update(m_position, is_end_position, update_interval);
} else {
pos_translator.init(m_position);
}
@@ -1716,8 +1643,7 @@ void GenericCAO::processMessage(const std::string &data)
} else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
std::string mod = deSerializeString(is);
- // immediately reset a engine issued texture modifier if a mod sends a
- // different one
+ // immediately reset a engine issued texture modifier if a mod sends a different one
if (m_reset_textures_timer > 0) {
m_reset_textures_timer = -1;
updateTextures(m_previous_texture_modifier);
@@ -1744,7 +1670,9 @@ void GenericCAO::processMessage(const std::string &data)
bool sneak_glitch = !readU8(is);
bool new_move = !readU8(is);
- if (m_is_local_player) {
+
+ if(m_is_local_player)
+ {
LocalPlayer *player = m_env->getLocalPlayer();
player->physics_override_speed = override_speed;
player->physics_override_jump = override_jump;
@@ -1760,33 +1688,31 @@ void GenericCAO::processMessage(const std::string &data)
m_animation_range = v2s32((s32)range.X, (s32)range.Y);
m_animation_speed = readF32(is);
m_animation_blend = readF32(is);
- // these are sent inverted so we get true when the server sends
- // nothing
+ // these are sent inverted so we get true when the server sends nothing
m_animation_loop = !readU8(is);
updateAnimation();
} else {
LocalPlayer *player = m_env->getLocalPlayer();
- if (player->last_animation == NO_ANIM) {
+ if(player->last_animation == NO_ANIM)
+ {
m_animation_range = v2s32((s32)range.X, (s32)range.Y);
m_animation_speed = readF32(is);
m_animation_blend = readF32(is);
- // these are sent inverted so we get true when the server
- // sends nothing
+ // these are sent inverted so we get true when the server sends nothing
m_animation_loop = !readU8(is);
}
// update animation only if local animations present
// and received animation is unknown (except idle animation)
bool is_known = false;
- for (int i = 1; i < 4; i++) {
- if (m_animation_range.Y == player->local_animations[i].Y)
+ for (int i = 1;i<4;i++)
+ {
+ if(m_animation_range.Y == player->local_animations[i].Y)
is_known = true;
}
- if (!is_known ||
- (player->local_animations[1].Y +
- player->local_animations[2]
- .Y <
- 1)) {
- updateAnimation();
+ if(!is_known ||
+ (player->local_animations[1].Y + player->local_animations[2].Y < 1))
+ {
+ updateAnimation();
}
}
} else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
@@ -1821,23 +1747,21 @@ void GenericCAO::processMessage(const std::string &data)
if (m_is_local_player)
m_env->getLocalPlayer()->hp = m_hp;
- if (damage > 0) {
- if (m_hp == 0) {
+ if (damage > 0)
+ {
+ if (m_hp == 0)
+ {
// TODO: Execute defined fast response
// As there is no definition, make a smoke puff
- ClientSimpleObject *simple = createSmokePuff(m_smgr,
- m_env, m_position,
- v2f(m_prop.visual_size.X,
- m_prop.visual_size.Y) *
- BS);
+ ClientSimpleObject *simple = createSmokePuff(
+ m_smgr, m_env, m_position,
+ v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
m_env->addSimpleObject(simple);
- } else if (m_reset_textures_timer < 0 &&
- !m_prop.damage_texture_modifier.empty()) {
+ } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
m_reset_textures_timer = 0.05;
- if (damage >= 2)
+ if(damage >= 2)
m_reset_textures_timer += 0.05 * damage;
- updateTextures(m_current_texture_modifier +
- m_prop.damage_texture_modifier);
+ updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
}
}
@@ -1851,7 +1775,8 @@ void GenericCAO::processMessage(const std::string &data)
} else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
m_armor_groups.clear();
int armor_groups_size = readU16(is);
- for (int i = 0; i < armor_groups_size; i++) {
+ for(int i=0; i<armor_groups_size; i++)
+ {
std::string name = deSerializeString(is);
int rating = readS16(is);
m_armor_groups[name] = rating;
@@ -1866,42 +1791,44 @@ void GenericCAO::processMessage(const std::string &data)
// Don't do anything and also don't log a warning
} else {
warningstream << FUNCTION_NAME
- << ": unknown command or outdated client \"" << +cmd << "\""
- << std::endl;
+ << ": unknown command or outdated client \""
+ << +cmd << "\"" << std::endl;
}
}
/* \pre punchitem != NULL
*/
-bool GenericCAO::directReportPunch(
- v3f dir, const ItemStack *punchitem, float time_from_last_punch)
+bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
+ float time_from_last_punch)
{
- assert(punchitem); // pre-condition
+ assert(punchitem); // pre-condition
const ToolCapabilities *toolcap =
&punchitem->getToolCapabilities(m_client->idef());
PunchDamageResult result = getPunchDamage(
- m_armor_groups, toolcap, punchitem, time_from_last_punch);
+ m_armor_groups,
+ toolcap,
+ punchitem,
+ time_from_last_punch);
- if (result.did_punch && result.damage != 0) {
- if (result.damage < m_hp) {
+ if(result.did_punch && result.damage != 0)
+ {
+ if(result.damage < m_hp)
+ {
m_hp -= result.damage;
} else {
m_hp = 0;
// TODO: Execute defined fast response
// As there is no definition, make a smoke puff
- ClientSimpleObject *simple = createSmokePuff(m_smgr, m_env,
- m_position,
- v2f(m_prop.visual_size.X, m_prop.visual_size.Y) *
- BS);
+ ClientSimpleObject *simple = createSmokePuff(
+ m_smgr, m_env, m_position,
+ v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
m_env->addSimpleObject(simple);
}
- if (m_reset_textures_timer < 0 &&
- !m_prop.damage_texture_modifier.empty()) {
+ if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
m_reset_textures_timer = 0.05;
if (result.damage >= 2)
m_reset_textures_timer += 0.05 * result.damage;
- updateTextures(m_current_texture_modifier +
- m_prop.damage_texture_modifier);
+ updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
}
}
@@ -1911,13 +1838,14 @@ bool GenericCAO::directReportPunch(
std::string GenericCAO::debugInfoText()
{
std::ostringstream os(std::ios::binary);
- os << "GenericCAO hp=" << m_hp << "\n";
- os << "armor={";
- for (ItemGroupList::const_iterator i = m_armor_groups.begin();
- i != m_armor_groups.end(); ++i) {
- os << i->first << "=" << i->second << ", ";
+ os<<"GenericCAO hp="<<m_hp<<"\n";
+ os<<"armor={";
+ for(ItemGroupList::const_iterator i = m_armor_groups.begin();
+ i != m_armor_groups.end(); ++i)
+ {
+ os<<i->first<<"="<<i->second<<", ";
}
- os << "}";
+ os<<"}";
return os.str();
}
diff --git a/src/client/content_cao.h b/src/client/content_cao.h
index 9ab5d710d..56ba8e0ec 100644
--- a/src/client/content_cao.h
+++ b/src/client/content_cao.h
@@ -35,7 +35,8 @@ struct Nametag;
SmoothTranslator
*/
-template <typename T> struct SmoothTranslator
+template<typename T>
+struct SmoothTranslator
{
T val_old;
T val_current;
@@ -49,7 +50,7 @@ template <typename T> struct SmoothTranslator
void init(T current);
void update(T new_target, bool is_end_position = false,
- float update_interval = -1);
+ float update_interval = -1);
void translate(f32 dtime);
};
@@ -76,8 +77,7 @@ private:
//
scene::ISceneManager *m_smgr = nullptr;
Client *m_client = nullptr;
- aabb3f m_selection_box =
- aabb3f(-BS / 3., -BS / 3., -BS / 3., BS / 3., BS / 3., BS / 3.);
+ aabb3f m_selection_box = aabb3f(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.);
scene::IMeshSceneNode *m_meshnode = nullptr;
scene::IAnimatedMeshSceneNode *m_animated_meshnode = nullptr;
WieldMeshSceneNode *m_wield_meshnode = nullptr;
@@ -92,7 +92,7 @@ private:
SmoothTranslator<v3f> pos_translator;
SmoothTranslatorWrappedv3f rot_translator;
// Spritesheet/animation stuff
- v2f m_tx_size = v2f(1, 1);
+ v2f m_tx_size = v2f(1,1);
v2s16 m_tx_basepos;
bool m_initial_tx_basepos_set = false;
bool m_tx_select_horiz_by_yawpitch = false;
@@ -137,13 +137,19 @@ public:
~GenericCAO();
- static ClientActiveObject *create(Client *client, ClientEnvironment *env)
+ static ClientActiveObject* create(Client *client, ClientEnvironment *env)
{
return new GenericCAO(client, env);
}
- inline ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_GENERIC; }
- inline const ItemGroupList &getGroups() const { return m_armor_groups; }
+ inline ActiveObjectType getType() const
+ {
+ return ACTIVEOBJECT_TYPE_GENERIC;
+ }
+ inline const ItemGroupList &getGroups() const
+ {
+ return m_armor_groups;
+ }
void initialize(const std::string &data);
void processInitData(const std::string &data);
@@ -156,13 +162,22 @@ public:
const v3f getPosition() const;
- void setPosition(const v3f &pos) { pos_translator.val_current = pos; }
+ void setPosition(const v3f &pos)
+ {
+ pos_translator.val_current = pos;
+ }
inline const v3f &getRotation() const { return m_rotation; }
- inline const v3f getAcceleration() const { return m_acceleration; }
+ inline const v3f getAcceleration() const
+ {
+ return m_acceleration;
+ }
- inline const v3f getVelocity() const { return m_velocity; }
+ inline const v3f getVelocity() const
+ {
+ return m_velocity;
+ }
const bool isImmortal();
@@ -190,21 +205,38 @@ public:
return &m_matrixnode->getAbsoluteTransformation();
}
- inline f32 getStepHeight() const { return m_prop.stepheight; }
+ inline f32 getStepHeight() const
+ {
+ return m_prop.stepheight;
+ }
- inline bool isLocalPlayer() const { return m_is_local_player; }
+ inline bool isLocalPlayer() const
+ {
+ return m_is_local_player;
+ }
- inline std::string getName() const { return m_name; }
+ inline std::string getName() const
+ {
+ return m_name;
+ }
- inline bool isPlayer() const { return m_is_player; }
+ inline bool isPlayer() const
+ {
+ return m_is_player;
+ }
- inline bool isVisible() const { return m_is_visible; }
+ inline bool isVisible() const
+ {
+ return m_is_visible;
+ }
- inline void setVisible(bool toset) { m_is_visible = toset; }
+ inline void setVisible(bool toset)
+ {
+ m_is_visible = toset;
+ }
void setChildrenVisible(bool toset);
- void setAttachment(int parent_id, const std::string &bone, v3f position,
- v3f rotation);
+ void setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation);
void getAttachment(int *parent_id, std::string *bone, v3f *position,
v3f *rotation) const;
void clearChildAttachments();
@@ -214,16 +246,17 @@ public:
ClientActiveObject *getParent() const;
int getParentId() const { return m_attachment_parent_id; }
const std::unordered_set<int> &getAttachmentChildIds() const
- {
- return m_attachment_child_ids;
- }
+ { return m_attachment_child_ids; }
void updateAttachments();
void removeFromScene(bool permanent);
void addToScene(ITextureSource *tsrc);
- inline void expireVisuals() { m_visuals_expired = true; }
+ inline void expireVisuals()
+ {
+ m_visuals_expired = true;
+ }
void updateLight(u32 day_night_ratio);
@@ -254,14 +287,20 @@ public:
void processMessage(const std::string &data);
- bool directReportPunch(v3f dir, const ItemStack *punchitem = NULL,
- float time_from_last_punch = 1000000);
+ bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL,
+ float time_from_last_punch=1000000);
std::string debugInfoText();
- std::string infoText() { return m_prop.infotext; }
-
+ std::string infoText()
+ {
+ return m_prop.infotext;
+ }
+
float m_waiting_for_reattach;
-
- ObjectProperties *getProperties() { return &m_prop; }
+
+ ObjectProperties *getProperties()
+ {
+ return &m_prop;
+ }
};
diff --git a/src/client/content_cso.cpp b/src/client/content_cso.cpp
index f9b02e823..f9641afbe 100644
--- a/src/client/content_cso.cpp
+++ b/src/client/content_cso.cpp
@@ -24,26 +24,25 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client.h"
#include "map.h"
-class SmokePuffCSO : public ClientSimpleObject
+class SmokePuffCSO: public ClientSimpleObject
{
float m_age = 0.0f;
scene::IBillboardSceneNode *m_spritenode = nullptr;
-
public:
- SmokePuffCSO(scene::ISceneManager *smgr, ClientEnvironment *env, const v3f &pos,
- const v2f &size)
+ SmokePuffCSO(scene::ISceneManager *smgr,
+ ClientEnvironment *env, const v3f &pos, const v2f &size)
{
- infostream << "SmokePuffCSO: constructing" << std::endl;
- m_spritenode = smgr->addBillboardSceneNode(NULL, v2f(1, 1), pos, -1);
- m_spritenode->setMaterialTexture(
- 0, env->getGameDef()->tsrc()->getTextureForMesh(
- "smoke_puff.png"));
+ infostream<<"SmokePuffCSO: constructing"<<std::endl;
+ m_spritenode = smgr->addBillboardSceneNode(
+ NULL, v2f(1,1), pos, -1);
+ m_spritenode->setMaterialTexture(0,
+ env->getGameDef()->tsrc()->getTextureForMesh("smoke_puff.png"));
m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
- // m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
+ //m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL);
m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
- m_spritenode->setColor(video::SColor(255, 0, 0, 0));
+ m_spritenode->setColor(video::SColor(255,0,0,0));
m_spritenode->setVisible(true);
m_spritenode->setSize(size);
/* Update brightness */
@@ -51,27 +50,28 @@ public:
bool pos_ok;
MapNode n = env->getMap().getNode(floatToInt(pos, BS), &pos_ok);
light = pos_ok ? decode_light(n.getLightBlend(env->getDayNightRatio(),
- env->getGameDef()->ndef()))
- : 64;
- video::SColor color(255, light, light, light);
+ env->getGameDef()->ndef()))
+ : 64;
+ video::SColor color(255,light,light,light);
m_spritenode->setColor(color);
}
virtual ~SmokePuffCSO()
{
- infostream << "SmokePuffCSO: destructing" << std::endl;
+ infostream<<"SmokePuffCSO: destructing"<<std::endl;
m_spritenode->remove();
}
void step(float dtime)
{
m_age += dtime;
- if (m_age > 1.0) {
+ if(m_age > 1.0){
m_to_be_removed = true;
}
}
};
-ClientSimpleObject *createSmokePuff(
- scene::ISceneManager *smgr, ClientEnvironment *env, v3f pos, v2f size)
+ClientSimpleObject* createSmokePuff(scene::ISceneManager *smgr,
+ ClientEnvironment *env, v3f pos, v2f size)
{
return new SmokePuffCSO(smgr, env, pos, size);
}
+
diff --git a/src/client/content_cso.h b/src/client/content_cso.h
index ccdb00610..cc9213175 100644
--- a/src/client/content_cso.h
+++ b/src/client/content_cso.h
@@ -22,5 +22,5 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "irrlichttypes_extrabloated.h"
#include "clientsimpleobject.h"
-ClientSimpleObject *createSmokePuff(
- scene::ISceneManager *smgr, ClientEnvironment *env, v3f pos, v2f size);
+ClientSimpleObject* createSmokePuff(scene::ISceneManager *smgr,
+ ClientEnvironment *env, v3f pos, v2f size);
diff --git a/src/client/content_mapblock.cpp b/src/client/content_mapblock.cpp
index c97963ede..3d06584c4 100644
--- a/src/client/content_mapblock.cpp
+++ b/src/client/content_mapblock.cpp
@@ -45,14 +45,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define FRAMED_NEIGHBOR_COUNT 18
static const v3s16 light_dirs[8] = {
- v3s16(-1, -1, -1),
- v3s16(-1, -1, 1),
- v3s16(-1, 1, -1),
- v3s16(-1, 1, 1),
- v3s16(1, -1, -1),
- v3s16(1, -1, 1),
- v3s16(1, 1, -1),
- v3s16(1, 1, 1),
+ v3s16(-1, -1, -1),
+ v3s16(-1, -1, 1),
+ v3s16(-1, 1, -1),
+ v3s16(-1, 1, 1),
+ v3s16( 1, -1, -1),
+ v3s16( 1, -1, 1),
+ v3s16( 1, 1, -1),
+ v3s16( 1, 1, 1),
};
// Standard index set to make a quad on 4 vertices
@@ -62,15 +62,14 @@ const std::string MapblockMeshGenerator::raillike_groupname = "connect_to_railli
MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output)
{
- data = input;
+ data = input;
collector = output;
- nodedef = data->m_client->ndef();
+ nodedef = data->m_client->ndef();
meshmanip = RenderingEngine::get_scene_manager()->getMeshManipulator();
enable_mesh_cache = g_settings->getBool("enable_mesh_cache") &&
- !data->m_smooth_lighting; // Mesh cache is not supported with
- // smooth lighting
+ !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting
blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE;
}
@@ -121,11 +120,11 @@ void MapblockMeshGenerator::getSpecialTile(int index, TileSpec *tile, bool apply
top_layer->material_flags |= MATERIAL_FLAG_CRACK;
}
-void MapblockMeshGenerator::drawQuad(
- v3f *coords, const v3s16 &normal, float vertical_tiling)
+void MapblockMeshGenerator::drawQuad(v3f *coords, const v3s16 &normal,
+ float vertical_tiling)
{
- const v2f tcoords[4] = {v2f(0.0, 0.0), v2f(1.0, 0.0), v2f(1.0, vertical_tiling),
- v2f(0.0, vertical_tiling)};
+ const v2f tcoords[4] = {v2f(0.0, 0.0), v2f(1.0, 0.0),
+ v2f(1.0, vertical_tiling), v2f(0.0, vertical_tiling)};
video::S3DVertex vertices[4];
bool shade_face = !f->light_source && (normal != v3s16(0, 0, 0));
v3f normal2(normal.X, normal.Y, normal.Z);
@@ -153,8 +152,8 @@ void MapblockMeshGenerator::drawQuad(
// should be (2+2)*6=24 values in the list. The order of
// the faces in the list is up-down-right-left-back-front
// (compatible with ContentFeatures).
-void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int tilecount,
- const LightInfo *lights, const f32 *txc)
+void MapblockMeshGenerator::drawCuboid(const aabb3f &box,
+ TileSpec *tiles, int tilecount, const LightInfo *lights, const f32 *txc)
{
assert(tilecount >= 1 && tilecount <= 6); // pre-condition
@@ -177,64 +176,46 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int t
}
video::S3DVertex vertices[24] = {
- // top
- video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[0],
- txc[1]),
- video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[2],
- txc[1]),
- video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[2],
- txc[3]),
- video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[0],
- txc[3]),
- // bottom
- video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[4],
- txc[5]),
- video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[6],
- txc[5]),
- video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[6],
- txc[7]),
- video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[4],
- txc[7]),
- // right
- video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, colors[2], txc[8],
- txc[9]),
- video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, colors[2], txc[10],
- txc[9]),
- video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, colors[2], txc[10],
- txc[11]),
- video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, colors[2], txc[8],
- txc[11]),
- // left
- video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, colors[3],
- txc[12], txc[13]),
- video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, colors[3],
- txc[14], txc[13]),
- video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, colors[3],
- txc[14], txc[15]),
- video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, colors[3],
- txc[12], txc[15]),
- // back
- video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[16],
- txc[17]),
- video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[18],
- txc[17]),
- video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[18],
- txc[19]),
- video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[16],
- txc[19]),
- // front
- video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, colors[5],
- txc[20], txc[21]),
- video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, colors[5],
- txc[22], txc[21]),
- video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, colors[5],
- txc[22], txc[23]),
- video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, colors[5],
- txc[20], txc[23]),
+ // top
+ video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[0], txc[1]),
+ video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, colors[0], txc[2], txc[1]),
+ video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[2], txc[3]),
+ video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, colors[0], txc[0], txc[3]),
+ // bottom
+ video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[4], txc[5]),
+ video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, colors[1], txc[6], txc[5]),
+ video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[6], txc[7]),
+ video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, colors[1], txc[4], txc[7]),
+ // right
+ video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[9]),
+ video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[9]),
+ video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, colors[2], txc[10], txc[11]),
+ video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, colors[2], txc[ 8], txc[11]),
+ // left
+ video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[13]),
+ video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[13]),
+ video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, colors[3], txc[14], txc[15]),
+ video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, colors[3], txc[12], txc[15]),
+ // back
+ video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[17]),
+ video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[17]),
+ video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[18], txc[19]),
+ video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, colors[4], txc[16], txc[19]),
+ // front
+ video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[21]),
+ video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[21]),
+ video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[22], txc[23]),
+ video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, colors[5], txc[20], txc[23]),
};
- static const u8 light_indices[24] = {3, 7, 6, 2, 0, 4, 5, 1, 6, 7, 5, 4, 3, 2, 0,
- 1, 7, 3, 1, 5, 2, 6, 4, 0};
+ static const u8 light_indices[24] = {
+ 3, 7, 6, 2,
+ 0, 4, 5, 1,
+ 6, 7, 5, 4,
+ 3, 2, 0, 1,
+ 7, 3, 1, 5,
+ 2, 6, 4, 0
+ };
for (int face = 0; face < 6; face++) {
int tileindex = MYMIN(face, tilecount - 1);
@@ -286,9 +267,8 @@ void MapblockMeshGenerator::drawCuboid(const aabb3f &box, TileSpec *tiles, int t
for (int j = 0; j < 24; ++j) {
video::S3DVertex &vertex = vertices[j];
vertex.Color = encode_light(
- lights[light_indices[j]].getPair(
- MYMAX(0.0f, vertex.Normal.Y)),
- f->light_source);
+ lights[light_indices[j]].getPair(MYMAX(0.0f, vertex.Normal.Y)),
+ f->light_source);
if (!f->light_source)
applyFacesShading(vertex.Color, vertex.Normal);
}
@@ -307,8 +287,7 @@ void MapblockMeshGenerator::getSmoothLightFrame()
for (int k = 0; k < 8; ++k)
frame.sunlight[k] = false;
for (int k = 0; k < 8; ++k) {
- LightPair light(getSmoothLightTransparent(
- blockpos_nodes + p, light_dirs[k], data));
+ LightPair light(getSmoothLightTransparent(blockpos_nodes + p, light_dirs[k], data));
frame.lightsDay[k] = light.lightDay;
frame.lightsNight[k] = light.lightNight;
// If there is direct sunlight and no ambient occlusion at some corner,
@@ -327,12 +306,9 @@ LightInfo MapblockMeshGenerator::blendLight(const v3f &vertex_pos)
// Light levels at (logical) node corners are known. Here,
// trilinear interpolation is used to calculate light level
// at a given point in the node.
- f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE,
- 1.0 + SMOOTH_LIGHTING_OVERSIZE);
- f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE,
- 1.0 + SMOOTH_LIGHTING_OVERSIZE);
- f32 z = core::clamp(vertex_pos.Z / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE,
- 1.0 + SMOOTH_LIGHTING_OVERSIZE);
+ f32 x = core::clamp(vertex_pos.X / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE);
+ f32 y = core::clamp(vertex_pos.Y / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE);
+ f32 z = core::clamp(vertex_pos.Z / BS + 0.5, 0.0 - SMOOTH_LIGHTING_OVERSIZE, 1.0 + SMOOTH_LIGHTING_OVERSIZE);
f32 lightDay = 0.0; // daylight
f32 lightNight = 0.0;
f32 lightBoosted = 0.0; // daylight + direct sunlight, if any
@@ -358,12 +334,11 @@ video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos)
return encode_light(light.getPair(), f->light_source);
}
-video::SColor MapblockMeshGenerator::blendLightColor(
- const v3f &vertex_pos, const v3f &vertex_normal)
+video::SColor MapblockMeshGenerator::blendLightColor(const v3f &vertex_pos,
+ const v3f &vertex_normal)
{
LightInfo light = blendLight(vertex_pos);
- video::SColor color = encode_light(
- light.getPair(MYMAX(0.0f, vertex_normal.Y)), f->light_source);
+ video::SColor color = encode_light(light.getPair(MYMAX(0.0f, vertex_normal.Y)), f->light_source);
if (!f->light_source)
applyFacesShading(color, vertex_normal);
return color;
@@ -378,19 +353,19 @@ void MapblockMeshGenerator::generateCuboidTextureCoords(const aabb3f &box, f32 *
f32 ty2 = (box.MaxEdge.Y / BS) + 0.5;
f32 tz2 = (box.MaxEdge.Z / BS) + 0.5;
f32 txc[24] = {
- tx1, 1 - tz2, tx2, 1 - tz1, // up
- tx1, tz1, tx2, tz2, // down
- tz1, 1 - ty2, tz2, 1 - ty1, // right
- 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, // left
- 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, // back
- tx1, 1 - ty2, tx2, 1 - ty1, // front
+ tx1, 1 - tz2, tx2, 1 - tz1, // up
+ tx1, tz1, tx2, tz2, // down
+ tz1, 1 - ty2, tz2, 1 - ty1, // right
+ 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1, // left
+ 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1, // back
+ tx1, 1 - ty2, tx2, 1 - ty1, // front
};
for (int i = 0; i != 24; ++i)
coords[i] = txc[i];
}
-void MapblockMeshGenerator::drawAutoLightedCuboid(
- aabb3f box, const f32 *txc, TileSpec *tiles, int tile_count)
+void MapblockMeshGenerator::drawAutoLightedCuboid(aabb3f box, const f32 *txc,
+ TileSpec *tiles, int tile_count)
{
bool scale = std::fabs(f->visual_scale - 1.0f) > 1e-3f;
f32 texture_coord_buf[24];
@@ -438,16 +413,12 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing()
getSpecialTile(0, &tile_liquid_top);
getSpecialTile(1, &tile_liquid);
- MapNode ntop = data->m_vmanip.getNodeNoEx(
- blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z));
- MapNode nbottom = data->m_vmanip.getNodeNoEx(
- blockpos_nodes + v3s16(p.X, p.Y - 1, p.Z));
+ MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y + 1, p.Z));
+ MapNode nbottom = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(p.X, p.Y - 1, p.Z));
c_flowing = f->liquid_alternative_flowing_id;
c_source = f->liquid_alternative_source_id;
- top_is_same_liquid = (ntop.getContent() == c_flowing) ||
- (ntop.getContent() == c_source);
- draw_liquid_bottom = (nbottom.getContent() != c_flowing) &&
- (nbottom.getContent() != c_source);
+ top_is_same_liquid = (ntop.getContent() == c_flowing) || (ntop.getContent() == c_source);
+ draw_liquid_bottom = (nbottom.getContent() != c_flowing) && (nbottom.getContent() != c_source);
if (draw_liquid_bottom) {
const ContentFeatures &f2 = nodedef->get(nbottom.getContent());
if (f2.solidness > 1)
@@ -461,8 +432,7 @@ void MapblockMeshGenerator::prepareLiquidNodeDrawing()
// If this liquid emits light and doesn't contain light, draw
// it at what it emits, for an increased effect
u8 e = decode_light(f->light_source);
- light = LightPair(std::max(e, light.lightDay),
- std::max(e, light.lightNight));
+ light = LightPair(std::max(e, light.lightDay), std::max(e, light.lightNight));
} else if (nodedef->get(ntop).param_type == CPT_LIGHT) {
// Otherwise, use the light of the node on top if possible
light = LightPair(getInteriorLight(ntop, 0, nodedef));
@@ -477,47 +447,46 @@ void MapblockMeshGenerator::getLiquidNeighborhood()
u8 range = rangelim(nodedef->get(c_flowing).liquid_range, 1, 8);
for (int w = -1; w <= 1; w++)
- for (int u = -1; u <= 1; u++) {
- NeighborData &neighbor = liquid_neighbors[w + 1][u + 1];
- v3s16 p2 = p + v3s16(u, 0, w);
- MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
- neighbor.content = n2.getContent();
- neighbor.level = -0.5 * BS;
- neighbor.is_same_liquid = false;
- neighbor.top_is_same_liquid = false;
-
- if (neighbor.content == CONTENT_IGNORE)
- continue;
-
- if (neighbor.content == c_source) {
- neighbor.is_same_liquid = true;
- neighbor.level = 0.5 * BS;
- } else if (neighbor.content == c_flowing) {
- neighbor.is_same_liquid = true;
- u8 liquid_level = (n2.param2 & LIQUID_LEVEL_MASK);
- if (liquid_level <= LIQUID_LEVEL_MAX + 1 - range)
- liquid_level = 0;
- else
- liquid_level -= (LIQUID_LEVEL_MAX + 1 - range);
- neighbor.level = (-0.5 + (liquid_level + 0.5) / range) *
- BS;
- }
+ for (int u = -1; u <= 1; u++) {
+ NeighborData &neighbor = liquid_neighbors[w + 1][u + 1];
+ v3s16 p2 = p + v3s16(u, 0, w);
+ MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
+ neighbor.content = n2.getContent();
+ neighbor.level = -0.5 * BS;
+ neighbor.is_same_liquid = false;
+ neighbor.top_is_same_liquid = false;
+
+ if (neighbor.content == CONTENT_IGNORE)
+ continue;
- // Check node above neighbor.
- // NOTE: This doesn't get executed if neighbor
- // doesn't exist
- p2.Y++;
- n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
- if (n2.getContent() == c_source || n2.getContent() == c_flowing)
- neighbor.top_is_same_liquid = true;
+ if (neighbor.content == c_source) {
+ neighbor.is_same_liquid = true;
+ neighbor.level = 0.5 * BS;
+ } else if (neighbor.content == c_flowing) {
+ neighbor.is_same_liquid = true;
+ u8 liquid_level = (n2.param2 & LIQUID_LEVEL_MASK);
+ if (liquid_level <= LIQUID_LEVEL_MAX + 1 - range)
+ liquid_level = 0;
+ else
+ liquid_level -= (LIQUID_LEVEL_MAX + 1 - range);
+ neighbor.level = (-0.5 + (liquid_level + 0.5) / range) * BS;
}
+
+ // Check node above neighbor.
+ // NOTE: This doesn't get executed if neighbor
+ // doesn't exist
+ p2.Y++;
+ n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
+ if (n2.getContent() == c_source || n2.getContent() == c_flowing)
+ neighbor.top_is_same_liquid = true;
+ }
}
void MapblockMeshGenerator::calculateCornerLevels()
{
for (int k = 0; k < 2; k++)
- for (int i = 0; i < 2; i++)
- corner_levels[k][i] = getCornerLevel(i, k);
+ for (int i = 0; i < 2; i++)
+ corner_levels[k][i] = getCornerLevel(i, k);
}
f32 MapblockMeshGenerator::getCornerLevel(int i, int k)
@@ -526,58 +495,59 @@ f32 MapblockMeshGenerator::getCornerLevel(int i, int k)
int count = 0;
int air_count = 0;
for (int dk = 0; dk < 2; dk++)
- for (int di = 0; di < 2; di++) {
- NeighborData &neighbor_data = liquid_neighbors[k + dk][i + di];
- content_t content = neighbor_data.content;
-
- // If top is liquid, draw starting from top of node
- if (neighbor_data.top_is_same_liquid)
- return 0.5 * BS;
-
- // Source always has the full height
- if (content == c_source)
- return 0.5 * BS;
-
- // Flowing liquid has level information
- if (content == c_flowing) {
- sum += neighbor_data.level;
- count++;
- } else if (content == CONTENT_AIR) {
- air_count++;
- if (air_count >= 2)
- return -0.5 * BS + 0.2;
- }
+ for (int di = 0; di < 2; di++) {
+ NeighborData &neighbor_data = liquid_neighbors[k + dk][i + di];
+ content_t content = neighbor_data.content;
+
+ // If top is liquid, draw starting from top of node
+ if (neighbor_data.top_is_same_liquid)
+ return 0.5 * BS;
+
+ // Source always has the full height
+ if (content == c_source)
+ return 0.5 * BS;
+
+ // Flowing liquid has level information
+ if (content == c_flowing) {
+ sum += neighbor_data.level;
+ count++;
+ } else if (content == CONTENT_AIR) {
+ air_count++;
+ if (air_count >= 2)
+ return -0.5 * BS + 0.2;
}
+ }
if (count > 0)
return sum / count;
return 0;
}
-namespace
-{
-struct LiquidFaceDesc
-{
- v3s16 dir; // XZ
- v3s16 p[2]; // XZ only; 1 means +, 0 means -
-};
-struct UV
-{
- int u, v;
-};
-static const LiquidFaceDesc liquid_base_faces[4] = {
- {v3s16(1, 0, 0), {v3s16(1, 0, 1), v3s16(1, 0, 0)}},
- {v3s16(-1, 0, 0), {v3s16(0, 0, 0), v3s16(0, 0, 1)}},
- {v3s16(0, 0, 1), {v3s16(0, 0, 1), v3s16(1, 0, 1)}},
- {v3s16(0, 0, -1), {v3s16(1, 0, 0), v3s16(0, 0, 0)}},
-};
-static const UV liquid_base_vertices[4] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}};
+namespace {
+ struct LiquidFaceDesc {
+ v3s16 dir; // XZ
+ v3s16 p[2]; // XZ only; 1 means +, 0 means -
+ };
+ struct UV {
+ int u, v;
+ };
+ static const LiquidFaceDesc liquid_base_faces[4] = {
+ {v3s16( 1, 0, 0), {v3s16(1, 0, 1), v3s16(1, 0, 0)}},
+ {v3s16(-1, 0, 0), {v3s16(0, 0, 0), v3s16(0, 0, 1)}},
+ {v3s16( 0, 0, 1), {v3s16(0, 0, 1), v3s16(1, 0, 1)}},
+ {v3s16( 0, 0, -1), {v3s16(1, 0, 0), v3s16(0, 0, 0)}},
+ };
+ static const UV liquid_base_vertices[4] = {
+ {0, 1},
+ {1, 1},
+ {1, 0},
+ {0, 0}
+ };
}
void MapblockMeshGenerator::drawLiquidSides()
{
for (const auto &face : liquid_base_faces) {
- const NeighborData &neighbor =
- liquid_neighbors[face.dir.Z + 1][face.dir.X + 1];
+ const NeighborData &neighbor = liquid_neighbors[face.dir.Z + 1][face.dir.X + 1];
// No face between nodes of the same liquid, unless there is node
// at the top to which it should be connected. Again, unless the face
@@ -604,9 +574,7 @@ void MapblockMeshGenerator::drawLiquidSides()
pos.X = (base.X - 0.5f) * BS;
pos.Z = (base.Z - 0.5f) * BS;
if (vertex.v) {
- pos.Y = neighbor.is_same_liquid
- ? corner_levels[base.Z][base.X]
- : -0.5f * BS;
+ pos.Y = neighbor.is_same_liquid ? corner_levels[base.Z][base.X] : -0.5f * BS;
} else if (top_is_same_liquid) {
pos.Y = 0.5f * BS;
} else {
@@ -617,8 +585,7 @@ void MapblockMeshGenerator::drawLiquidSides()
if (data->m_smooth_lighting)
color = blendLightColor(pos);
pos += origin;
- vertices[j] = video::S3DVertex(
- pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, v);
+ vertices[j] = video::S3DVertex(pos.X, pos.Y, pos.Z, 0, 0, 0, color, vertex.u, v);
};
collector->append(tile_liquid, vertices, 4, quad_indices, 6);
}
@@ -632,14 +599,10 @@ void MapblockMeshGenerator::drawLiquidTop()
static const int corner_resolve[4][2] = {{0, 1}, {1, 1}, {1, 0}, {0, 0}};
video::S3DVertex vertices[4] = {
- video::S3DVertex(-BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 0,
- 1),
- video::S3DVertex(BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 1,
- 1),
- video::S3DVertex(BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 1,
- 0),
- video::S3DVertex(-BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top,
- 0, 0),
+ video::S3DVertex(-BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 0, 1),
+ video::S3DVertex( BS / 2, 0, BS / 2, 0, 0, 0, color_liquid_top, 1, 1),
+ video::S3DVertex( BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 1, 0),
+ video::S3DVertex(-BS / 2, 0, -BS / 2, 0, 0, 0, color_liquid_top, 0, 0),
};
for (int i = 0; i < 4; i++) {
@@ -656,10 +619,10 @@ void MapblockMeshGenerator::drawLiquidTop()
// Rotate texture to make animation go in flow direction
// Positive if liquid moves towards +Z
f32 dz = (corner_levels[0][0] + corner_levels[0][1]) -
- (corner_levels[1][0] + corner_levels[1][1]);
+ (corner_levels[1][0] + corner_levels[1][1]);
// Positive if liquid moves towards +X
f32 dx = (corner_levels[0][0] + corner_levels[1][0]) -
- (corner_levels[0][1] + corner_levels[1][1]);
+ (corner_levels[0][1] + corner_levels[1][1]);
f32 tcoord_angle = atan2(dz, dx) * core::RADTODEG;
v2f tcoord_center(0.5, 0.5);
v2f tcoord_translate(blockpos_nodes.Z + p.Z, blockpos_nodes.X + p.X);
@@ -680,14 +643,10 @@ void MapblockMeshGenerator::drawLiquidTop()
void MapblockMeshGenerator::drawLiquidBottom()
{
video::S3DVertex vertices[4] = {
- video::S3DVertex(-BS / 2, -BS / 2, -BS / 2, 0, 0, 0,
- color_liquid_top, 0, 0),
- video::S3DVertex(BS / 2, -BS / 2, -BS / 2, 0, 0, 0,
- color_liquid_top, 1, 0),
- video::S3DVertex(BS / 2, -BS / 2, BS / 2, 0, 0, 0,
- color_liquid_top, 1, 1),
- video::S3DVertex(-BS / 2, -BS / 2, BS / 2, 0, 0, 0,
- color_liquid_top, 0, 1),
+ video::S3DVertex(-BS / 2, -BS / 2, -BS / 2, 0, 0, 0, color_liquid_top, 0, 0),
+ video::S3DVertex( BS / 2, -BS / 2, -BS / 2, 0, 0, 0, color_liquid_top, 1, 0),
+ video::S3DVertex( BS / 2, -BS / 2, BS / 2, 0, 0, 0, color_liquid_top, 1, 1),
+ video::S3DVertex(-BS / 2, -BS / 2, BS / 2, 0, 0, 0, color_liquid_top, 0, 1),
};
for (int i = 0; i < 4; i++) {
@@ -725,32 +684,26 @@ void MapblockMeshGenerator::drawGlasslikeNode()
continue;
// Face at Z-
v3f vertices[4] = {
- v3f(-BS / 2, BS / 2, -BS / 2),
- v3f(BS / 2, BS / 2, -BS / 2),
- v3f(BS / 2, -BS / 2, -BS / 2),
- v3f(-BS / 2, -BS / 2, -BS / 2),
+ v3f(-BS / 2, BS / 2, -BS / 2),
+ v3f( BS / 2, BS / 2, -BS / 2),
+ v3f( BS / 2, -BS / 2, -BS / 2),
+ v3f(-BS / 2, -BS / 2, -BS / 2),
};
for (v3f &vertex : vertices) {
switch (face) {
- case D6D_ZP:
- vertex.rotateXZBy(180);
- break;
- case D6D_YP:
- vertex.rotateYZBy(90);
- break;
- case D6D_XP:
- vertex.rotateXZBy(90);
- break;
- case D6D_ZN:
- vertex.rotateXZBy(0);
- break;
- case D6D_YN:
- vertex.rotateYZBy(-90);
- break;
- case D6D_XN:
- vertex.rotateXZBy(-90);
- break;
+ case D6D_ZP:
+ vertex.rotateXZBy(180); break;
+ case D6D_YP:
+ vertex.rotateYZBy( 90); break;
+ case D6D_XP:
+ vertex.rotateXZBy( 90); break;
+ case D6D_ZN:
+ vertex.rotateXZBy( 0); break;
+ case D6D_YN:
+ vertex.rotateYZBy(-90); break;
+ case D6D_XN:
+ vertex.rotateXZBy(-90); break;
}
}
drawQuad(vertices, dir);
@@ -780,34 +733,33 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode()
static const float b = 0.876f * (BS / 2.0f);
static const aabb3f frame_edges[FRAMED_EDGE_COUNT] = {
- aabb3f(b, b, -a, a, a, a), // y+
- aabb3f(-a, b, -a, -b, a, a), // y+
- aabb3f(b, -a, -a, a, -b, a), // y-
- aabb3f(-a, -a, -a, -b, -b, a), // y-
- aabb3f(b, -a, b, a, a, a), // x+
- aabb3f(b, -a, -a, a, a, -b), // x+
- aabb3f(-a, -a, b, -b, a, a), // x-
- aabb3f(-a, -a, -a, -b, a, -b), // x-
- aabb3f(-a, b, b, a, a, a), // z+
- aabb3f(-a, -a, b, a, -b, a), // z+
- aabb3f(-a, -a, -a, a, -b, -b), // z-
- aabb3f(-a, b, -a, a, a, -b), // z-
+ aabb3f( b, b, -a, a, a, a), // y+
+ aabb3f(-a, b, -a, -b, a, a), // y+
+ aabb3f( b, -a, -a, a, -b, a), // y-
+ aabb3f(-a, -a, -a, -b, -b, a), // y-
+ aabb3f( b, -a, b, a, a, a), // x+
+ aabb3f( b, -a, -a, a, a, -b), // x+
+ aabb3f(-a, -a, b, -b, a, a), // x-
+ aabb3f(-a, -a, -a, -b, a, -b), // x-
+ aabb3f(-a, b, b, a, a, a), // z+
+ aabb3f(-a, -a, b, a, -b, a), // z+
+ aabb3f(-a, -a, -a, a, -b, -b), // z-
+ aabb3f(-a, b, -a, a, a, -b), // z-
};
// tables of neighbour (connect if same type and merge allowed),
// checked with g_26dirs
// 1 = connect, 0 = face visible
- bool nb[FRAMED_NEIGHBOR_COUNT] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ bool nb[FRAMED_NEIGHBOR_COUNT] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// 1 = check
- static const bool check_nb_vertical[FRAMED_NEIGHBOR_COUNT] = {
- 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- static const bool check_nb_horizontal[FRAMED_NEIGHBOR_COUNT] = {
- 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0};
- static const bool check_nb_all[FRAMED_NEIGHBOR_COUNT] = {
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
+ static const bool check_nb_vertical [FRAMED_NEIGHBOR_COUNT] =
+ {0,1,0,0,1,0, 0,0,0,0, 0,0,0,0, 0,0,0,0};
+ static const bool check_nb_horizontal [FRAMED_NEIGHBOR_COUNT] =
+ {1,0,1,1,0,1, 0,0,0,0, 1,1,1,1, 0,0,0,0};
+ static const bool check_nb_all [FRAMED_NEIGHBOR_COUNT] =
+ {1,1,1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1};
const bool *check_nb = check_nb_all;
// neighbours checks for frames visibility
@@ -831,29 +783,18 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode()
// edge visibility
static const u8 nb_triplet[FRAMED_EDGE_COUNT][3] = {
- {1, 2, 7},
- {1, 5, 6},
- {4, 2, 15},
- {4, 5, 14},
- {2, 0, 11},
- {2, 3, 13},
- {5, 0, 10},
- {5, 3, 12},
- {0, 1, 8},
- {0, 4, 16},
- {3, 4, 17},
- {3, 1, 9},
+ {1, 2, 7}, {1, 5, 6}, {4, 2, 15}, {4, 5, 14},
+ {2, 0, 11}, {2, 3, 13}, {5, 0, 10}, {5, 3, 12},
+ {0, 1, 8}, {0, 4, 16}, {3, 4, 17}, {3, 1, 9},
};
tile = tiles[1];
for (int edge = 0; edge < FRAMED_EDGE_COUNT; edge++) {
bool edge_invisible;
if (nb[nb_triplet[edge][2]])
- edge_invisible =
- nb[nb_triplet[edge][0]] & nb[nb_triplet[edge][1]];
+ edge_invisible = nb[nb_triplet[edge][0]] & nb[nb_triplet[edge][1]];
else
- edge_invisible =
- nb[nb_triplet[edge][0]] ^ nb[nb_triplet[edge][1]];
+ edge_invisible = nb[nb_triplet[edge][0]] ^ nb[nb_triplet[edge][1]];
if (edge_invisible)
continue;
drawAutoLightedCuboid(frame_edges[edge]);
@@ -866,32 +807,26 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode()
tile = glass_tiles[face];
// Face at Z-
v3f vertices[4] = {
- v3f(-a, a, -g),
- v3f(a, a, -g),
- v3f(a, -a, -g),
- v3f(-a, -a, -g),
+ v3f(-a, a, -g),
+ v3f( a, a, -g),
+ v3f( a, -a, -g),
+ v3f(-a, -a, -g),
};
for (v3f &vertex : vertices) {
switch (face) {
- case D6D_ZP:
- vertex.rotateXZBy(180);
- break;
- case D6D_YP:
- vertex.rotateYZBy(90);
- break;
- case D6D_XP:
- vertex.rotateXZBy(90);
- break;
- case D6D_ZN:
- vertex.rotateXZBy(0);
- break;
- case D6D_YN:
- vertex.rotateYZBy(-90);
- break;
- case D6D_XN:
- vertex.rotateXZBy(-90);
- break;
+ case D6D_ZP:
+ vertex.rotateXZBy(180); break;
+ case D6D_YP:
+ vertex.rotateYZBy( 90); break;
+ case D6D_XP:
+ vertex.rotateXZBy( 90); break;
+ case D6D_ZN:
+ vertex.rotateXZBy( 0); break;
+ case D6D_YN:
+ vertex.rotateYZBy(-90); break;
+ case D6D_XN:
+ vertex.rotateXZBy(-90); break;
}
}
v3s16 dir = g_6dirs[face];
@@ -906,9 +841,12 @@ void MapblockMeshGenerator::drawGlasslikeFramedNode()
// convert it to -0.5 .. 0.5
float vlev = (param2 / 63.0f) * 2.0f - 1.0f;
getSpecialTile(0, &tile);
- drawAutoLightedCuboid(aabb3f(-(nb[5] ? g : b), -(nb[4] ? g : b),
- -(nb[3] ? g : b), (nb[2] ? g : b), (nb[1] ? g : b) * vlev,
- (nb[0] ? g : b)));
+ drawAutoLightedCuboid(aabb3f(-(nb[5] ? g : b),
+ -(nb[4] ? g : b),
+ -(nb[3] ? g : b),
+ (nb[2] ? g : b),
+ (nb[1] ? g : b) * vlev,
+ (nb[0] ? g : b)));
}
}
@@ -924,49 +862,44 @@ void MapblockMeshGenerator::drawTorchlikeNode()
u8 wall = n.getWallMounted(nodedef);
u8 tileindex = 0;
switch (wall) {
- case DWM_YP:
- tileindex = 1;
- break; // ceiling
- case DWM_YN:
- tileindex = 0;
- break; // floor
- default:
- tileindex = 2; // side (or invalid—should we care?)
+ case DWM_YP: tileindex = 1; break; // ceiling
+ case DWM_YN: tileindex = 0; break; // floor
+ default: tileindex = 2; // side (or invalid—should we care?)
}
useTile(tileindex, MATERIAL_FLAG_CRACK_OVERLAY, MATERIAL_FLAG_BACKFACE_CULLING);
float size = BS / 2 * f->visual_scale;
v3f vertices[4] = {
- v3f(-size, size, 0),
- v3f(size, size, 0),
- v3f(size, -size, 0),
- v3f(-size, -size, 0),
+ v3f(-size, size, 0),
+ v3f( size, size, 0),
+ v3f( size, -size, 0),
+ v3f(-size, -size, 0),
};
for (v3f &vertex : vertices) {
switch (wall) {
- case DWM_YP:
- vertex.Y += -size + BS / 2;
- vertex.rotateXZBy(-45);
- break;
- case DWM_YN:
- vertex.Y += size - BS / 2;
- vertex.rotateXZBy(45);
- break;
- case DWM_XP:
- vertex.X += -size + BS / 2;
- break;
- case DWM_XN:
- vertex.X += -size + BS / 2;
- vertex.rotateXZBy(180);
- break;
- case DWM_ZP:
- vertex.X += -size + BS / 2;
- vertex.rotateXZBy(90);
- break;
- case DWM_ZN:
- vertex.X += -size + BS / 2;
- vertex.rotateXZBy(-90);
+ case DWM_YP:
+ vertex.Y += -size + BS/2;
+ vertex.rotateXZBy(-45);
+ break;
+ case DWM_YN:
+ vertex.Y += size - BS/2;
+ vertex.rotateXZBy(45);
+ break;
+ case DWM_XP:
+ vertex.X += -size + BS/2;
+ break;
+ case DWM_XN:
+ vertex.X += -size + BS/2;
+ vertex.rotateXZBy(180);
+ break;
+ case DWM_ZP:
+ vertex.X += -size + BS/2;
+ vertex.rotateXZBy(90);
+ break;
+ case DWM_ZN:
+ vertex.X += -size + BS/2;
+ vertex.rotateXZBy(-90);
}
}
drawQuad(vertices);
@@ -980,45 +913,39 @@ void MapblockMeshGenerator::drawSignlikeNode()
float size = BS / 2 * f->visual_scale;
// Wall at X+ of node
v3f vertices[4] = {
- v3f(BS / 2 - offset, size, size),
- v3f(BS / 2 - offset, size, -size),
- v3f(BS / 2 - offset, -size, -size),
- v3f(BS / 2 - offset, -size, size),
+ v3f(BS / 2 - offset, size, size),
+ v3f(BS / 2 - offset, size, -size),
+ v3f(BS / 2 - offset, -size, -size),
+ v3f(BS / 2 - offset, -size, size),
};
for (v3f &vertex : vertices) {
switch (wall) {
- case DWM_YP:
- vertex.rotateXYBy(90);
- break;
- case DWM_YN:
- vertex.rotateXYBy(-90);
- break;
- case DWM_XP:
- vertex.rotateXZBy(0);
- break;
- case DWM_XN:
- vertex.rotateXZBy(180);
- break;
- case DWM_ZP:
- vertex.rotateXZBy(90);
- break;
- case DWM_ZN:
- vertex.rotateXZBy(-90);
- break;
+ case DWM_YP:
+ vertex.rotateXYBy( 90); break;
+ case DWM_YN:
+ vertex.rotateXYBy(-90); break;
+ case DWM_XP:
+ vertex.rotateXZBy( 0); break;
+ case DWM_XN:
+ vertex.rotateXZBy(180); break;
+ case DWM_ZP:
+ vertex.rotateXZBy( 90); break;
+ case DWM_ZN:
+ vertex.rotateXZBy(-90); break;
}
}
drawQuad(vertices);
}
-void MapblockMeshGenerator::drawPlantlikeQuad(
- float rotation, float quad_offset, bool offset_top_only)
+void MapblockMeshGenerator::drawPlantlikeQuad(float rotation, float quad_offset,
+ bool offset_top_only)
{
v3f vertices[4] = {
- v3f(-scale, -BS / 2 + 2.0 * scale * plant_height, 0),
- v3f(scale, -BS / 2 + 2.0 * scale * plant_height, 0),
- v3f(scale, -BS / 2, 0),
- v3f(-scale, -BS / 2, 0),
+ v3f(-scale, -BS / 2 + 2.0 * scale * plant_height, 0),
+ v3f( scale, -BS / 2 + 2.0 * scale * plant_height, 0),
+ v3f( scale, -BS / 2, 0),
+ v3f(-scale, -BS / 2, 0),
};
if (random_offset_Y) {
PseudoRandom yrng(face_num++ | p.X << 16 | p.Z << 8 | p.Y << 24);
@@ -1089,15 +1016,15 @@ void MapblockMeshGenerator::drawPlantlike()
break;
case PLANT_STYLE_HASH:
- drawPlantlikeQuad(1, BS / 4);
- drawPlantlikeQuad(91, BS / 4);
+ drawPlantlikeQuad( 1, BS / 4);
+ drawPlantlikeQuad( 91, BS / 4);
drawPlantlikeQuad(181, BS / 4);
drawPlantlikeQuad(271, BS / 4);
break;
case PLANT_STYLE_HASH2:
- drawPlantlikeQuad(1, -BS / 2, true);
- drawPlantlikeQuad(91, -BS / 2, true);
+ drawPlantlikeQuad( 1, -BS / 2, true);
+ drawPlantlikeQuad( 91, -BS / 2, true);
drawPlantlikeQuad(181, -BS / 2, true);
drawPlantlikeQuad(271, -BS / 2, true);
break;
@@ -1125,14 +1052,14 @@ void MapblockMeshGenerator::drawPlantlikeRootedNode()
p.Y--;
}
-void MapblockMeshGenerator::drawFirelikeQuad(
- float rotation, float opening_angle, float offset_h, float offset_v)
+void MapblockMeshGenerator::drawFirelikeQuad(float rotation, float opening_angle,
+ float offset_h, float offset_v)
{
v3f vertices[4] = {
- v3f(-scale, -BS / 2 + scale * 2, 0),
- v3f(scale, -BS / 2 + scale * 2, 0),
- v3f(scale, -BS / 2, 0),
- v3f(-scale, -BS / 2, 0),
+ v3f(-scale, -BS / 2 + scale * 2, 0),
+ v3f( scale, -BS / 2 + scale * 2, 0),
+ v3f( scale, -BS / 2, 0),
+ v3f(-scale, -BS / 2, 0),
};
for (v3f &vertex : vertices) {
@@ -1204,37 +1131,19 @@ void MapblockMeshGenerator::drawFencelikeNode()
tile_rot.rotation = 1;
static const f32 post_rad = BS / 8;
- static const f32 bar_rad = BS / 16;
- static const f32 bar_len = BS / 2 - post_rad;
+ static const f32 bar_rad = BS / 16;
+ static const f32 bar_len = BS / 2 - post_rad;
// The post - always present
- static const aabb3f post(
- -post_rad, -BS / 2, -post_rad, post_rad, BS / 2, post_rad);
+ static const aabb3f post(-post_rad, -BS / 2, -post_rad,
+ post_rad, BS / 2, post_rad);
static const f32 postuv[24] = {
- 0.375,
- 0.375,
- 0.625,
- 0.625,
- 0.375,
- 0.375,
- 0.625,
- 0.625,
- 0.000,
- 0.000,
- 0.250,
- 1.000,
- 0.250,
- 0.000,
- 0.500,
- 1.000,
- 0.500,
- 0.000,
- 0.750,
- 1.000,
- 0.750,
- 0.000,
- 1.000,
- 1.000,
+ 0.375, 0.375, 0.625, 0.625,
+ 0.375, 0.375, 0.625, 0.625,
+ 0.000, 0.000, 0.250, 1.000,
+ 0.250, 0.000, 0.500, 1.000,
+ 0.500, 0.000, 0.750, 1.000,
+ 0.750, 0.000, 1.000, 1.000,
};
tile = tile_rot;
drawAutoLightedCuboid(post, postuv);
@@ -1247,35 +1156,17 @@ void MapblockMeshGenerator::drawFencelikeNode()
MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
const ContentFeatures *f2 = &nodedef->get(n2);
if (f2->drawtype == NDT_FENCELIKE) {
- static const aabb3f bar_x1(BS / 2 - bar_len, BS / 4 - bar_rad, -bar_rad,
- BS / 2 + bar_len, BS / 4 + bar_rad, bar_rad);
+ static const aabb3f bar_x1(BS / 2 - bar_len, BS / 4 - bar_rad, -bar_rad,
+ BS / 2 + bar_len, BS / 4 + bar_rad, bar_rad);
static const aabb3f bar_x2(BS / 2 - bar_len, -BS / 4 - bar_rad, -bar_rad,
- BS / 2 + bar_len, -BS / 4 + bar_rad, bar_rad);
+ BS / 2 + bar_len, -BS / 4 + bar_rad, bar_rad);
static const f32 xrailuv[24] = {
- 0.000,
- 0.125,
- 1.000,
- 0.250,
- 0.000,
- 0.250,
- 1.000,
- 0.375,
- 0.375,
- 0.375,
- 0.500,
- 0.500,
- 0.625,
- 0.625,
- 0.750,
- 0.750,
- 0.000,
- 0.500,
- 1.000,
- 0.625,
- 0.000,
- 0.875,
- 1.000,
- 1.000,
+ 0.000, 0.125, 1.000, 0.250,
+ 0.000, 0.250, 1.000, 0.375,
+ 0.375, 0.375, 0.500, 0.500,
+ 0.625, 0.625, 0.750, 0.750,
+ 0.000, 0.500, 1.000, 0.625,
+ 0.000, 0.875, 1.000, 1.000,
};
drawAutoLightedCuboid(bar_x1, xrailuv);
drawAutoLightedCuboid(bar_x2, xrailuv);
@@ -1287,35 +1178,17 @@ void MapblockMeshGenerator::drawFencelikeNode()
n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2);
f2 = &nodedef->get(n2);
if (f2->drawtype == NDT_FENCELIKE) {
- static const aabb3f bar_z1(-bar_rad, BS / 4 - bar_rad, BS / 2 - bar_len,
- bar_rad, BS / 4 + bar_rad, BS / 2 + bar_len);
+ static const aabb3f bar_z1(-bar_rad, BS / 4 - bar_rad, BS / 2 - bar_len,
+ bar_rad, BS / 4 + bar_rad, BS / 2 + bar_len);
static const aabb3f bar_z2(-bar_rad, -BS / 4 - bar_rad, BS / 2 - bar_len,
- bar_rad, -BS / 4 + bar_rad, BS / 2 + bar_len);
+ bar_rad, -BS / 4 + bar_rad, BS / 2 + bar_len);
static const f32 zrailuv[24] = {
- 0.1875,
- 0.0625,
- 0.3125,
- 0.3125, // cannot rotate; stretch
- 0.2500,
- 0.0625,
- 0.3750,
- 0.3125, // for wood texture instead
- 0.0000,
- 0.5625,
- 1.0000,
- 0.6875,
- 0.0000,
- 0.3750,
- 1.0000,
- 0.5000,
- 0.3750,
- 0.3750,
- 0.5000,
- 0.5000,
- 0.6250,
- 0.6250,
- 0.7500,
- 0.7500,
+ 0.1875, 0.0625, 0.3125, 0.3125, // cannot rotate; stretch
+ 0.2500, 0.0625, 0.3750, 0.3125, // for wood texture instead
+ 0.0000, 0.5625, 1.0000, 0.6875,
+ 0.0000, 0.3750, 1.0000, 0.5000,
+ 0.3750, 0.3750, 0.5000, 0.5000,
+ 0.6250, 0.6250, 0.7500, 0.7500,
};
drawAutoLightedCuboid(bar_z1, zrailuv);
drawAutoLightedCuboid(bar_z2, zrailuv);
@@ -1329,51 +1202,48 @@ bool MapblockMeshGenerator::isSameRail(v3s16 dir)
return true;
const ContentFeatures &def2 = nodedef->get(node2);
return ((def2.drawtype == NDT_RAILLIKE) &&
- (def2.getGroup(raillike_groupname) == raillike_group));
+ (def2.getGroup(raillike_groupname) == raillike_group));
}
-namespace
-{
-static const v3s16 rail_direction[4] = {
- v3s16(0, 0, 1),
- v3s16(0, 0, -1),
- v3s16(-1, 0, 0),
- v3s16(1, 0, 0),
-};
-static const int rail_slope_angle[4] = {0, 180, 90, -90};
+namespace {
+ static const v3s16 rail_direction[4] = {
+ v3s16( 0, 0, 1),
+ v3s16( 0, 0, -1),
+ v3s16(-1, 0, 0),
+ v3s16( 1, 0, 0),
+ };
+ static const int rail_slope_angle[4] = {0, 180, 90, -90};
-enum RailTile
-{
- straight,
- curved,
- junction,
- cross,
-};
-struct RailDesc
-{
- int tile_index;
- int angle;
-};
-static const RailDesc rail_kinds[16] = {
- // +x -x -z +z
- //-------------
- {straight, 0}, // . . . .
- {straight, 0}, // . . . +Z
- {straight, 0}, // . . -Z .
- {straight, 0}, // . . -Z +Z
- {straight, 90}, // . -X . .
- {curved, 180}, // . -X . +Z
- {curved, 270}, // . -X -Z .
+ enum RailTile {
+ straight,
+ curved,
+ junction,
+ cross,
+ };
+ struct RailDesc {
+ int tile_index;
+ int angle;
+ };
+ static const RailDesc rail_kinds[16] = {
+ // +x -x -z +z
+ //-------------
+ {straight, 0}, // . . . .
+ {straight, 0}, // . . . +Z
+ {straight, 0}, // . . -Z .
+ {straight, 0}, // . . -Z +Z
+ {straight, 90}, // . -X . .
+ { curved, 180}, // . -X . +Z
+ { curved, 270}, // . -X -Z .
{junction, 180}, // . -X -Z +Z
- {straight, 90}, // +X . . .
- {curved, 90}, // +X . . +Z
- {curved, 0}, // +X . -Z .
- {junction, 0}, // +X . -Z +Z
- {straight, 90}, // +X -X . .
- {junction, 90}, // +X -X . +Z
+ {straight, 90}, // +X . . .
+ { curved, 90}, // +X . . +Z
+ { curved, 0}, // +X . -Z .
+ {junction, 0}, // +X . -Z +Z
+ {straight, 90}, // +X -X . .
+ {junction, 90}, // +X -X . +Z
{junction, 270}, // +X -X -Z .
- {cross, 0}, // +X -X -Z +Z
-};
+ { cross, 0}, // +X -X -Z +Z
+ };
}
void MapblockMeshGenerator::drawRaillikeNode()
@@ -1390,7 +1260,8 @@ void MapblockMeshGenerator::drawRaillikeNode()
sloped = true;
angle = rail_slope_angle[dir];
}
- if (rail_above || isSameRail(rail_direction[dir]) ||
+ if (rail_above ||
+ isSameRail(rail_direction[dir]) ||
isSameRail(rail_direction[dir] + v3s16(0, -1, 0)))
code |= 1 << dir;
}
@@ -1405,13 +1276,13 @@ void MapblockMeshGenerator::drawRaillikeNode()
useTile(tile_index, MATERIAL_FLAG_CRACK_OVERLAY, MATERIAL_FLAG_BACKFACE_CULLING);
static const float offset = BS / 64;
- static const float size = BS / 2;
+ static const float size = BS / 2;
float y2 = sloped ? size : -size;
v3f vertices[4] = {
- v3f(-size, y2 + offset, size),
- v3f(size, y2 + offset, size),
- v3f(size, -size + offset, -size),
- v3f(-size, -size + offset, -size),
+ v3f(-size, y2 + offset, size),
+ v3f( size, y2 + offset, size),
+ v3f( size, -size + offset, -size),
+ v3f(-size, -size + offset, -size),
};
if (angle)
for (v3f &vertex : vertices)
@@ -1419,20 +1290,25 @@ void MapblockMeshGenerator::drawRaillikeNode()
drawQuad(vertices);
}
-namespace
-{
-static const v3s16 nodebox_tile_dirs[6] = {v3s16(0, 1, 0), v3s16(0, -1, 0),
- v3s16(1, 0, 0), v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1)};
-
-// we have this order for some reason...
-static const v3s16 nodebox_connection_dirs[6] = {
- v3s16(0, 1, 0), // top
- v3s16(0, -1, 0), // bottom
- v3s16(0, 0, -1), // front
- v3s16(-1, 0, 0), // left
- v3s16(0, 0, 1), // back
- v3s16(1, 0, 0), // right
-};
+namespace {
+ static const v3s16 nodebox_tile_dirs[6] = {
+ v3s16(0, 1, 0),
+ v3s16(0, -1, 0),
+ v3s16(1, 0, 0),
+ v3s16(-1, 0, 0),
+ v3s16(0, 0, 1),
+ v3s16(0, 0, -1)
+ };
+
+ // we have this order for some reason...
+ static const v3s16 nodebox_connection_dirs[6] = {
+ v3s16( 0, 1, 0), // top
+ v3s16( 0, -1, 0), // bottom
+ v3s16( 0, 0, -1), // front
+ v3s16(-1, 0, 0), // left
+ v3s16( 0, 0, 1), // back
+ v3s16( 1, 0, 0), // right
+ };
}
void MapblockMeshGenerator::drawNodeboxNode()
@@ -1464,10 +1340,11 @@ void MapblockMeshGenerator::drawNodeboxNode()
void MapblockMeshGenerator::drawMeshNode()
{
u8 facedir = 0;
- scene::IMesh *mesh;
+ scene::IMesh* mesh;
bool private_mesh; // as a grab/drop pair is not thread-safe
- if (f->param_type_2 == CPT2_FACEDIR || f->param_type_2 == CPT2_COLORED_FACEDIR) {
+ if (f->param_type_2 == CPT2_FACEDIR ||
+ f->param_type_2 == CPT2_COLORED_FACEDIR) {
facedir = n.getFaceDir(nodedef);
} else if (f->param_type_2 == CPT2_WALLMOUNTED ||
f->param_type_2 == CPT2_COLORED_WALLMOUNTED) {
@@ -1507,14 +1384,14 @@ void MapblockMeshGenerator::drawMeshNode()
vertex.Color = blendLightColor(vertex.Pos, vertex.Normal);
vertex.Pos += origin;
}
- collector->append(tile, vertices, vertex_count, buf->getIndices(),
- buf->getIndexCount());
+ collector->append(tile, vertices, vertex_count,
+ buf->getIndices(), buf->getIndexCount());
} else {
// Don't modify the mesh, it may not be private here.
// Instead, let the collector process colors, etc.
- collector->append(tile, vertices, vertex_count, buf->getIndices(),
- buf->getIndexCount(), origin, color,
- f->light_source);
+ collector->append(tile, vertices, vertex_count,
+ buf->getIndices(), buf->getIndexCount(), origin,
+ color, f->light_source);
}
}
if (private_mesh)
@@ -1532,12 +1409,12 @@ void MapblockMeshGenerator::drawNode()
{
// skip some drawtypes early
switch (f->drawtype) {
- case NDT_NORMAL: // Drawn by MapBlockMesh
- case NDT_AIRLIKE: // Not drawn at all
- case NDT_LIQUID: // Drawn by MapBlockMesh
- return;
- default:
- break;
+ case NDT_NORMAL: // Drawn by MapBlockMesh
+ case NDT_AIRLIKE: // Not drawn at all
+ case NDT_LIQUID: // Drawn by MapBlockMesh
+ return;
+ default:
+ break;
}
origin = intToFloat(p, BS);
if (data->m_smooth_lighting)
@@ -1545,48 +1422,20 @@ void MapblockMeshGenerator::drawNode()
else
light = LightPair(getInteriorLight(n, 1, nodedef));
switch (f->drawtype) {
- case NDT_FLOWINGLIQUID:
- drawLiquidNode();
- break;
- case NDT_GLASSLIKE:
- drawGlasslikeNode();
- break;
- case NDT_GLASSLIKE_FRAMED:
- drawGlasslikeFramedNode();
- break;
- case NDT_ALLFACES:
- drawAllfacesNode();
- break;
- case NDT_TORCHLIKE:
- drawTorchlikeNode();
- break;
- case NDT_SIGNLIKE:
- drawSignlikeNode();
- break;
- case NDT_PLANTLIKE:
- drawPlantlikeNode();
- break;
- case NDT_PLANTLIKE_ROOTED:
- drawPlantlikeRootedNode();
- break;
- case NDT_FIRELIKE:
- drawFirelikeNode();
- break;
- case NDT_FENCELIKE:
- drawFencelikeNode();
- break;
- case NDT_RAILLIKE:
- drawRaillikeNode();
- break;
- case NDT_NODEBOX:
- drawNodeboxNode();
- break;
- case NDT_MESH:
- drawMeshNode();
- break;
- default:
- errorUnknownDrawtype();
- break;
+ case NDT_FLOWINGLIQUID: drawLiquidNode(); break;
+ case NDT_GLASSLIKE: drawGlasslikeNode(); break;
+ case NDT_GLASSLIKE_FRAMED: drawGlasslikeFramedNode(); break;
+ case NDT_ALLFACES: drawAllfacesNode(); break;
+ case NDT_TORCHLIKE: drawTorchlikeNode(); break;
+ case NDT_SIGNLIKE: drawSignlikeNode(); break;
+ case NDT_PLANTLIKE: drawPlantlikeNode(); break;
+ case NDT_PLANTLIKE_ROOTED: drawPlantlikeRootedNode(); break;
+ case NDT_FIRELIKE: drawFirelikeNode(); break;
+ case NDT_FENCELIKE: drawFencelikeNode(); break;
+ case NDT_RAILLIKE: drawRaillikeNode(); break;
+ case NDT_NODEBOX: drawNodeboxNode(); break;
+ case NDT_MESH: drawMeshNode(); break;
+ default: errorUnknownDrawtype(); break;
}
}
@@ -1597,12 +1446,12 @@ void MapblockMeshGenerator::drawNode()
void MapblockMeshGenerator::generate()
{
for (p.Z = 0; p.Z < MAP_BLOCKSIZE; p.Z++)
- for (p.Y = 0; p.Y < MAP_BLOCKSIZE; p.Y++)
- for (p.X = 0; p.X < MAP_BLOCKSIZE; p.X++) {
- n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p);
- f = &nodedef->get(n);
- drawNode();
- }
+ for (p.Y = 0; p.Y < MAP_BLOCKSIZE; p.Y++)
+ for (p.X = 0; p.X < MAP_BLOCKSIZE; p.X++) {
+ n = data->m_vmanip.getNodeNoEx(blockpos_nodes + p);
+ f = &nodedef->get(n);
+ drawNode();
+ }
}
void MapblockMeshGenerator::renderSingle(content_t node)
diff --git a/src/client/content_mapblock.h b/src/client/content_mapblock.h
index 73ff11333..97947cdbe 100644
--- a/src/client/content_mapblock.h
+++ b/src/client/content_mapblock.h
@@ -25,8 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
struct MeshMakeData;
struct MeshCollector;
-struct LightPair
-{
+struct LightPair {
u8 lightDay;
u8 lightNight;
@@ -34,29 +33,26 @@ struct LightPair
explicit LightPair(u16 value) : lightDay(value & 0xff), lightNight(value >> 8) {}
LightPair(u8 valueA, u8 valueB) : lightDay(valueA), lightNight(valueB) {}
LightPair(float valueA, float valueB) :
- lightDay(core::clamp(core::round32(valueA), 0, 255)),
- lightNight(core::clamp(core::round32(valueB), 0, 255))
- {
- }
+ lightDay(core::clamp(core::round32(valueA), 0, 255)),
+ lightNight(core::clamp(core::round32(valueB), 0, 255)) {}
operator u16() const { return lightDay | lightNight << 8; }
};
-struct LightInfo
-{
+struct LightInfo {
float light_day;
float light_night;
float light_boosted;
LightPair getPair(float sunlight_boost = 0.0) const
{
- return LightPair((1 - sunlight_boost) * light_day +
- sunlight_boost * light_boosted,
- light_night);
+ return LightPair(
+ (1 - sunlight_boost) * light_day
+ + sunlight_boost * light_boosted,
+ light_night);
}
};
-struct LightFrame
-{
+struct LightFrame {
f32 lightsDay[8];
f32 lightsNight[8];
bool sunlight[8];
@@ -71,10 +67,10 @@ public:
const NodeDefManager *nodedef;
scene::IMeshManipulator *meshmanip;
- // options
+// options
bool enable_mesh_cache;
- // current node
+// current node
v3s16 blockpos_nodes;
v3s16 p;
v3f origin;
@@ -86,30 +82,30 @@ public:
TileSpec tile;
float scale;
- // lighting
+// lighting
void getSmoothLightFrame();
LightInfo blendLight(const v3f &vertex_pos);
video::SColor blendLightColor(const v3f &vertex_pos);
video::SColor blendLightColor(const v3f &vertex_pos, const v3f &vertex_normal);
void useTile(int index = 0, u8 set_flags = MATERIAL_FLAG_CRACK_OVERLAY,
- u8 reset_flags = 0, bool special = false);
+ u8 reset_flags = 0, bool special = false);
void getTile(int index, TileSpec *tile);
void getTile(v3s16 direction, TileSpec *tile);
void getSpecialTile(int index, TileSpec *tile, bool apply_crack = false);
- // face drawing
+// face drawing
void drawQuad(v3f *vertices, const v3s16 &normal = v3s16(0, 0, 0),
- float vertical_tiling = 1.0);
+ float vertical_tiling = 1.0);
- // cuboid drawing!
+// cuboid drawing!
void drawCuboid(const aabb3f &box, TileSpec *tiles, int tilecount,
- const LightInfo *lights, const f32 *txc);
+ const LightInfo *lights , const f32 *txc);
void generateCuboidTextureCoords(aabb3f const &box, f32 *coords);
void drawAutoLightedCuboid(aabb3f box, const f32 *txc = NULL,
- TileSpec *tiles = NULL, int tile_count = 0);
+ TileSpec *tiles = NULL, int tile_count = 0);
- // liquid-specific
+// liquid-specific
bool top_is_same_liquid;
bool draw_liquid_bottom;
TileSpec tile_liquid;
@@ -117,8 +113,7 @@ public:
content_t c_flowing;
content_t c_source;
video::SColor color_liquid_top;
- struct NeighborData
- {
+ struct NeighborData {
f32 level;
content_t content;
bool is_same_liquid;
@@ -135,13 +130,13 @@ public:
void drawLiquidTop();
void drawLiquidBottom();
- // raillike-specific
+// raillike-specific
// name of the group that enables connecting to raillike nodes of different kind
static const std::string raillike_groupname;
int raillike_group;
bool isSameRail(v3s16 dir);
- // plantlike-specific
+// plantlike-specific
PlantlikeStyle draw_style;
v3f offset;
int rotate_degree;
@@ -150,14 +145,14 @@ public:
float plant_height;
void drawPlantlikeQuad(float rotation, float quad_offset = 0,
- bool offset_top_only = false);
+ bool offset_top_only = false);
void drawPlantlike();
- // firelike-specific
- void drawFirelikeQuad(float rotation, float opening_angle, float offset_h,
- float offset_v = 0.0);
+// firelike-specific
+ void drawFirelikeQuad(float rotation, float opening_angle,
+ float offset_h, float offset_v = 0.0);
- // drawtypes
+// drawtypes
void drawLiquidNode();
void drawGlasslikeNode();
void drawGlasslikeFramedNode();
@@ -172,7 +167,7 @@ public:
void drawNodeboxNode();
void drawMeshNode();
- // common
+// common
void errorUnknownDrawtype();
void drawNode();
diff --git a/src/client/filecache.cpp b/src/client/filecache.cpp
index 0c8f06198..46bbe4059 100644
--- a/src/client/filecache.cpp
+++ b/src/client/filecache.cpp
@@ -32,28 +32,28 @@ bool FileCache::loadByPath(const std::string &path, std::ostream &os)
{
std::ifstream fis(path.c_str(), std::ios_base::binary);
- if (!fis.good()) {
- verbosestream << "FileCache: File not found in cache: " << path
- << std::endl;
+ if(!fis.good()){
+ verbosestream<<"FileCache: File not found in cache: "
+ <<path<<std::endl;
return false;
}
bool bad = false;
- for (;;) {
+ for(;;){
char buf[1024];
fis.read(buf, 1024);
std::streamsize len = fis.gcount();
os.write(buf, len);
- if (fis.eof())
+ if(fis.eof())
break;
- if (!fis.good()) {
+ if(!fis.good()){
bad = true;
break;
}
}
- if (bad) {
- errorstream << "FileCache: Failed to read file from cache: \"" << path
- << "\"" << std::endl;
+ if(bad){
+ errorstream<<"FileCache: Failed to read file from cache: \""
+ <<path<<"\""<<std::endl;
}
return !bad;
@@ -61,10 +61,13 @@ bool FileCache::loadByPath(const std::string &path, std::ostream &os)
bool FileCache::updateByPath(const std::string &path, const std::string &data)
{
- std::ofstream file(path.c_str(), std::ios_base::binary | std::ios_base::trunc);
+ std::ofstream file(path.c_str(), std::ios_base::binary |
+ std::ios_base::trunc);
- if (!file.good()) {
- errorstream << "FileCache: Can't write to file at " << path << std::endl;
+ if(!file.good())
+ {
+ errorstream<<"FileCache: Can't write to file at "
+ <<path<<std::endl;
return false;
}
diff --git a/src/client/fontengine.cpp b/src/client/fontengine.cpp
index 965fa88e2..a55420846 100644
--- a/src/client/fontengine.cpp
+++ b/src/client/fontengine.cpp
@@ -33,7 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define MAX_FONT_SIZE_OFFSET 10
/** reference to access font engine, has to be initialized by main */
-FontEngine *g_fontengine = NULL;
+FontEngine* g_fontengine = NULL;
/** callback to be used on change of font size setting */
static void font_setting_changed(const std::string &name, void *userdata)
@@ -42,48 +42,37 @@ static void font_setting_changed(const std::string &name, void *userdata)
}
/******************************************************************************/
-FontEngine::FontEngine(Settings *main_settings, gui::IGUIEnvironment *env) :
- m_settings(main_settings), m_env(env)
+FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) :
+ m_settings(main_settings),
+ m_env(env)
{
for (u32 &i : m_default_size) {
- i = (FontMode)FONT_SIZE_UNSPECIFIED;
+ i = (FontMode) FONT_SIZE_UNSPECIFIED;
}
- assert(m_settings != NULL); // pre-condition
- assert(m_env != NULL); // pre-condition
+ assert(m_settings != NULL); // pre-condition
+ assert(m_env != NULL); // pre-condition
assert(m_env->getSkin() != NULL); // pre-condition
readSettings();
if (m_currentMode == FM_Standard) {
- m_settings->registerChangedCallback(
- "font_size", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_bold", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_italic", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_path", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_path_bold", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_path_italic", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_path_bolditalic", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_shadow", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "font_shadow_alpha", font_setting_changed, NULL);
- } else if (m_currentMode == FM_Fallback) {
- m_settings->registerChangedCallback(
- "fallback_font_size", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "fallback_font_path", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "fallback_font_shadow", font_setting_changed, NULL);
- m_settings->registerChangedCallback(
- "fallback_font_shadow_alpha", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_size", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_bold", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_italic", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_path", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL);
+ }
+ else if (m_currentMode == FM_Fallback) {
+ m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL);
+ m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL);
}
m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
@@ -118,9 +107,9 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec)
spec.mode = m_currentMode;
} else if (m_currentMode == FM_Simple) {
// Freetype disabled -> Force simple mode
- spec.mode = (spec.mode == FM_Mono || spec.mode == FM_SimpleMono)
- ? FM_SimpleMono
- : FM_Simple;
+ spec.mode = (spec.mode == FM_Mono ||
+ spec.mode == FM_SimpleMono) ?
+ FM_SimpleMono : FM_Simple;
// Support for those could be added, but who cares?
spec.bold = false;
spec.italic = false;
@@ -175,6 +164,7 @@ unsigned int FontEngine::getTextWidth(const std::wstring &text, const FontSpec &
return font->getDimension(text.c_str()).Width;
}
+
/** get line height for a specific font (including empty room between lines) */
unsigned int FontEngine::getLineHeight(const FontSpec &spec)
{
@@ -186,8 +176,8 @@ unsigned int FontEngine::getLineHeight(const FontSpec &spec)
}
FATAL_ERROR_IF(font == NULL, "Could not get font");
- return font->getDimension(L"Some unimportant example String").Height +
- font->getKerningHeight();
+ return font->getDimension(L"Some unimportant example String").Height
+ + font->getKerningHeight();
}
/******************************************************************************/
@@ -217,7 +207,7 @@ void FontEngine::readSettings()
if (USE_FREETYPE && g_settings->getBool("freetype")) {
m_default_size[FM_Standard] = m_settings->getU16("font_size");
m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size");
- m_default_size[FM_Mono] = m_settings->getU16("mono_font_size");
+ m_default_size[FM_Mono] = m_settings->getU16("mono_font_size");
/*~ DO NOT TRANSLATE THIS LITERALLY!
This is a special string. Put either "no" or "yes"
@@ -227,8 +217,8 @@ void FontEngine::readSettings()
The fallback font is (normally) required for languages with
non-Latin script, like Chinese.
When in doubt, test your translation. */
- m_currentMode = is_yes(gettext("needs_fallback_font")) ? FM_Fallback
- : FM_Standard;
+ m_currentMode = is_yes(gettext("needs_fallback_font")) ?
+ FM_Fallback : FM_Standard;
m_default_bold = m_settings->getBool("font_bold");
m_default_italic = m_settings->getBool("font_italic");
@@ -237,8 +227,8 @@ void FontEngine::readSettings()
m_currentMode = FM_Simple;
}
- m_default_size[FM_Simple] = m_settings->getU16("font_size");
- m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size");
+ m_default_size[FM_Simple] = m_settings->getU16("font_size");
+ m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size");
cleanCache();
updateFontCache();
@@ -253,12 +243,11 @@ void FontEngine::updateSkin()
if (font)
m_env->getSkin()->setFont(font);
else
- errorstream << "FontEngine: Default font file: "
- << "\n\t\"" << m_settings->get("font_path") << "\""
- << "\n\trequired for current screen configuration was not "
- "found"
- << " or was invalid file format."
- << "\n\tUsing irrlicht default font." << std::endl;
+ errorstream << "FontEngine: Default font file: " <<
+ "\n\t\"" << m_settings->get("font_path") << "\"" <<
+ "\n\trequired for current screen configuration was not found" <<
+ " or was invalid file format." <<
+ "\n\tUsing irrlicht default font." << std::endl;
// If we did fail to create a font our own make irrlicht find a default one
font = m_env->getSkin()->getFont();
@@ -285,15 +274,15 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
std::string setting_prefix = "";
switch (spec.mode) {
- case FM_Fallback:
- setting_prefix = "fallback_";
- break;
- case FM_Mono:
- case FM_SimpleMono:
- setting_prefix = "mono_";
- break;
- default:
- break;
+ case FM_Fallback:
+ setting_prefix = "fallback_";
+ break;
+ case FM_Mono:
+ case FM_SimpleMono:
+ setting_prefix = "mono_";
+ break;
+ default:
+ break;
}
std::string setting_suffix = "";
@@ -303,26 +292,28 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
setting_suffix.append("_italic");
u32 size = std::floor(RenderingEngine::getDisplayDensity() *
- m_settings->getFloat("gui_scaling") * spec.size);
+ m_settings->getFloat("gui_scaling") * spec.size);
if (size == 0) {
errorstream << "FontEngine: attempt to use font size 0" << std::endl;
- errorstream << " display density: "
- << RenderingEngine::getDisplayDensity() << std::endl;
+ errorstream << " display density: " << RenderingEngine::getDisplayDensity() << std::endl;
abort();
}
- u16 font_shadow = 0;
+ u16 font_shadow = 0;
u16 font_shadow_alpha = 0;
g_settings->getU16NoEx(setting_prefix + "font_shadow", font_shadow);
- g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha", font_shadow_alpha);
+ g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha",
+ font_shadow_alpha);
std::string wanted_font_path;
wanted_font_path = g_settings->get(setting_prefix + "font_path" + setting_suffix);
- std::string fallback_settings[] = {wanted_font_path,
- m_settings->get("fallback_font_path"),
- m_settings->getDefault(setting_prefix + "font_path")};
+ std::string fallback_settings[] = {
+ wanted_font_path,
+ m_settings->get("fallback_font_path"),
+ m_settings->getDefault(setting_prefix + "font_path")
+ };
#if USE_FREETYPE
for (const std::string &font_path : fallback_settings) {
@@ -333,19 +324,18 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec)
if (font)
return font;
- errorstream << "FontEngine: Cannot load '" << font_path
- << "'. Trying to fall back to another path." << std::endl;
+ errorstream << "FontEngine: Cannot load '" << font_path <<
+ "'. Trying to fall back to another path." << std::endl;
}
+
// give up
errorstream << "minetest can not continue without a valid font. "
- "Please correct the 'font_path' setting or install the font "
- "file in the proper location"
- << std::endl;
+ "Please correct the 'font_path' setting or install the font "
+ "file in the proper location" << std::endl;
#else
errorstream << "FontEngine: Tried to load freetype fonts but Minetest was"
- " not compiled with that library."
- << std::endl;
+ " not compiled with that library." << std::endl;
#endif
abort();
}
@@ -365,18 +355,20 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
if (ending == ".ttf") {
errorstream << "FontEngine: Found font \"" << font_path
- << "\" but freetype is not available." << std::endl;
+ << "\" but freetype is not available." << std::endl;
return nullptr;
}
if (ending == ".xml" || ending == ".png")
basename = font_path.substr(0, pos_dot);
- u32 size = std::floor(RenderingEngine::getDisplayDensity() *
- m_settings->getFloat("gui_scaling") * spec.size);
+ u32 size = std::floor(
+ RenderingEngine::getDisplayDensity() *
+ m_settings->getFloat("gui_scaling") *
+ spec.size);
irr::gui::IGUIFont *font = nullptr;
- std::string font_extensions[] = {".png", ".xml"};
+ std::string font_extensions[] = { ".png", ".xml" };
// Find nearest matching font scale
// Does a "zig-zag motion" (positibe/negative), from 0 to MAX_FONT_SIZE_OFFSET
@@ -397,8 +389,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
font = m_env->getFont(path.str().c_str());
if (font) {
- verbosestream << "FontEngine: found font: " << path.str()
- << std::endl;
+ verbosestream << "FontEngine: found font: " << path.str() << std::endl;
break;
}
}
@@ -412,8 +403,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec)
if (fs::PathExists(font_path)) {
font = m_env->getFont(font_path.c_str());
if (font)
- verbosestream << "FontEngine: found font: " << font_path
- << std::endl;
+ verbosestream << "FontEngine: found font: " << font_path << std::endl;
}
}
diff --git a/src/client/fontengine.h b/src/client/fontengine.h
index a9d7a13c2..865b2d3ff 100644
--- a/src/client/fontengine.h
+++ b/src/client/fontengine.h
@@ -29,8 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define FONT_SIZE_UNSPECIFIED 0xFFFFFFFF
-enum FontMode : u8
-{
+enum FontMode : u8 {
FM_Standard = 0,
FM_Mono,
FM_Fallback,
@@ -40,15 +39,18 @@ enum FontMode : u8
FM_Unspecified
};
-struct FontSpec
-{
+struct FontSpec {
FontSpec(unsigned int font_size, FontMode mode, bool bold, bool italic) :
- size(font_size), mode(mode), bold(bold), italic(italic)
+ size(font_size),
+ mode(mode),
+ bold(bold),
+ italic(italic) {}
+
+ u16 getHash()
{
+ return (mode << 2) | (bold << 1) | italic;
}
- u16 getHash() { return (mode << 2) | (bold << 1) | italic; }
-
unsigned int size;
FontMode mode;
bool bold;
@@ -58,15 +60,16 @@ struct FontSpec
class FontEngine
{
public:
- FontEngine(Settings *main_settings, gui::IGUIEnvironment *env);
+
+ FontEngine(Settings* main_settings, gui::IGUIEnvironment* env);
~FontEngine();
// Get best possible font specified by FontSpec
irr::gui::IGUIFont *getFont(FontSpec spec);
- irr::gui::IGUIFont *getFont(unsigned int font_size = FONT_SIZE_UNSPECIFIED,
- FontMode mode = FM_Unspecified)
+ irr::gui::IGUIFont *getFont(unsigned int font_size=FONT_SIZE_UNSPECIFIED,
+ FontMode mode=FM_Unspecified)
{
FontSpec spec(font_size, mode, m_default_bold, m_default_italic);
return getFont(spec);
@@ -76,8 +79,9 @@ public:
unsigned int getTextHeight(const FontSpec &spec);
/** get text width if a text for a specific font */
- unsigned int getTextHeight(unsigned int font_size = FONT_SIZE_UNSPECIFIED,
- FontMode mode = FM_Unspecified)
+ unsigned int getTextHeight(
+ unsigned int font_size=FONT_SIZE_UNSPECIFIED,
+ FontMode mode=FM_Unspecified)
{
FontSpec spec(font_size, mode, m_default_bold, m_default_italic);
return getTextHeight(spec);
@@ -86,9 +90,9 @@ public:
unsigned int getTextWidth(const std::wstring &text, const FontSpec &spec);
/** get text width if a text for a specific font */
- unsigned int getTextWidth(const std::wstring &text,
- unsigned int font_size = FONT_SIZE_UNSPECIFIED,
- FontMode mode = FM_Unspecified)
+ unsigned int getTextWidth(const std::wstring& text,
+ unsigned int font_size=FONT_SIZE_UNSPECIFIED,
+ FontMode mode=FM_Unspecified)
{
FontSpec spec(font_size, mode, m_default_bold, m_default_italic);
return getTextWidth(text, spec);
@@ -99,9 +103,9 @@ public:
return getTextWidth(utf8_to_wide(text), spec);
}
- unsigned int getTextWidth(const std::string &text,
- unsigned int font_size = FONT_SIZE_UNSPECIFIED,
- FontMode mode = FM_Unspecified)
+ unsigned int getTextWidth(const std::string& text,
+ unsigned int font_size=FONT_SIZE_UNSPECIFIED,
+ FontMode mode=FM_Unspecified)
{
FontSpec spec(font_size, mode, m_default_bold, m_default_italic);
return getTextWidth(utf8_to_wide(text), spec);
@@ -110,8 +114,8 @@ public:
/** get line height for a specific font (including empty room between lines) */
unsigned int getLineHeight(const FontSpec &spec);
- unsigned int getLineHeight(unsigned int font_size = FONT_SIZE_UNSPECIFIED,
- FontMode mode = FM_Unspecified)
+ unsigned int getLineHeight(unsigned int font_size=FONT_SIZE_UNSPECIFIED,
+ FontMode mode=FM_Unspecified)
{
FontSpec spec(font_size, mode, m_default_bold, m_default_italic);
return getLineHeight(spec);
@@ -124,7 +128,7 @@ public:
unsigned int getFontSize(FontMode mode);
/** initialize font engine */
- void initialize(Settings *main_settings, gui::IGUIEnvironment *env);
+ void initialize(Settings* main_settings, gui::IGUIEnvironment* env);
/** update internal parameters from settings */
void readSettings();
@@ -146,13 +150,13 @@ private:
void cleanCache();
/** pointer to settings for registering callbacks or reading config */
- Settings *m_settings = nullptr;
+ Settings* m_settings = nullptr;
/** pointer to irrlicht gui environment */
- gui::IGUIEnvironment *m_env = nullptr;
+ gui::IGUIEnvironment* m_env = nullptr;
/** internal storage for caching fonts of different size */
- std::map<unsigned int, irr::gui::IGUIFont *> m_font_cache[FM_MaxMode << 2];
+ std::map<unsigned int, irr::gui::IGUIFont*> m_font_cache[FM_MaxMode << 2];
/** default font size to use */
unsigned int m_default_size[FM_MaxMode];
@@ -168,4 +172,4 @@ private:
};
/** interface to access main font engine*/
-extern FontEngine *g_fontengine;
+extern FontEngine* g_fontengine;
diff --git a/src/client/game.cpp b/src/client/game.cpp
index e56101436..479484ae9 100644
--- a/src/client/game.cpp
+++ b/src/client/game.cpp
@@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client/clientevent.h"
#include "client/gameui.h"
#include "client/inputhandler.h"
-#include "client/tile.h" // For TextureSource
+#include "client/tile.h" // For TextureSource
#include "client/keys.h"
#include "client/joystick_controller.h"
#include "clientmap.h"
@@ -52,7 +52,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gui/profilergraph.h"
#include "mapblock.h"
#include "minimap.h"
-#include "nodedef.h" // Needed for determining pointing to nodes
+#include "nodedef.h" // Needed for determining pointing to nodes
#include "nodemetadata.h"
#include "particles.h"
#include "porting.h"
@@ -73,49 +73,60 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "hud.h"
#if USE_SOUND
-#include "client/sound_openal.h"
+ #include "client/sound_openal.h"
#else
-#include "client/sound.h"
+ #include "client/sound.h"
#endif
-Game::Game() : m_chat_log_buf(g_logger), m_game_ui(new GameUI())
-{
- g_settings->registerChangedCallback(
- "doubletap_jump", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "enable_clouds", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "doubletap_joysticks", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "enable_particles", &settingChangedCallback, this);
- g_settings->registerChangedCallback("enable_fog", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "mouse_sensitivity", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "joystick_frustum_sensitivity", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "repeat_rightclick_time", &settingChangedCallback, this);
- g_settings->registerChangedCallback("noclip", &settingChangedCallback, this);
- g_settings->registerChangedCallback("free_move", &settingChangedCallback, this);
- g_settings->registerChangedCallback("cinematic", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "cinematic_camera_smoothing", &settingChangedCallback, this);
- g_settings->registerChangedCallback(
- "camera_smoothing", &settingChangedCallback, this);
- g_settings->registerChangedCallback("freecam", &freecamChangedCallback, this);
- g_settings->registerChangedCallback("xray", &updateAllMapBlocksCallback, this);
- g_settings->registerChangedCallback(
- "xray_nodes", &updateAllMapBlocksCallback, this);
- g_settings->registerChangedCallback(
- "fullbright", &updateAllMapBlocksCallback, this);
-
+Game::Game() :
+ m_chat_log_buf(g_logger),
+ m_game_ui(new GameUI())
+{
+ g_settings->registerChangedCallback("doubletap_jump",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("enable_clouds",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("doubletap_joysticks",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("enable_particles",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("enable_fog",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("mouse_sensitivity",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("joystick_frustum_sensitivity",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("repeat_rightclick_time",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("noclip",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("free_move",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("cinematic",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("cinematic_camera_smoothing",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("camera_smoothing",
+ &settingChangedCallback, this);
+ g_settings->registerChangedCallback("freecam",
+ &freecamChangedCallback, this);
+ g_settings->registerChangedCallback("xray",
+ &updateAllMapBlocksCallback, this);
+ g_settings->registerChangedCallback("xray_nodes",
+ &updateAllMapBlocksCallback, this);
+ g_settings->registerChangedCallback("fullbright",
+ &updateAllMapBlocksCallback, this);
+
readSettings();
#ifdef __ANDROID__
- m_cache_hold_aux1 = false; // This is initialised properly later
+ m_cache_hold_aux1 = false; // This is initialised properly later
#endif
+
}
+
+
/****************************************************************************
MinetestApp Public
****************************************************************************/
@@ -141,44 +152,53 @@ Game::~Game()
extendedResourceCleanup();
- g_settings->deregisterChangedCallback(
- "doubletap_jump", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "enable_clouds", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "enable_particles", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "enable_fog", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "mouse_sensitivity", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "repeat_rightclick_time", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback("noclip", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback("free_move", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback("cinematic", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "cinematic_camera_smoothing", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback(
- "camera_smoothing", &settingChangedCallback, this);
- g_settings->deregisterChangedCallback("freecam", &freecamChangedCallback, this);
- g_settings->deregisterChangedCallback("xray", &updateAllMapBlocksCallback, this);
- g_settings->deregisterChangedCallback(
- "xray_nodes", &updateAllMapBlocksCallback, this);
- g_settings->deregisterChangedCallback(
- "fullbright", &updateAllMapBlocksCallback, this);
-}
-
-bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_data,
- std::string &error_message, bool *reconnect, ChatBackend *chat_backend)
+ g_settings->deregisterChangedCallback("doubletap_jump",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("enable_clouds",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("enable_particles",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("enable_fog",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("mouse_sensitivity",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("repeat_rightclick_time",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("noclip",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("free_move",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("cinematic",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("camera_smoothing",
+ &settingChangedCallback, this);
+ g_settings->deregisterChangedCallback("freecam",
+ &freecamChangedCallback, this);
+ g_settings->deregisterChangedCallback("xray",
+ &updateAllMapBlocksCallback, this);
+ g_settings->deregisterChangedCallback("xray_nodes",
+ &updateAllMapBlocksCallback, this);
+ g_settings->deregisterChangedCallback("fullbright",
+ &updateAllMapBlocksCallback, this);
+}
+
+bool Game::startup(bool *kill,
+ InputHandler *input,
+ const GameStartData &start_data,
+ std::string &error_message,
+ bool *reconnect,
+ ChatBackend *chat_backend)
{
// "cache"
- this->device = RenderingEngine::get_raw_device();
- this->kill = kill;
- this->error_message = &error_message;
+ this->device = RenderingEngine::get_raw_device();
+ this->kill = kill;
+ this->error_message = &error_message;
this->reconnect_requested = reconnect;
- this->input = input;
- this->chat_backend = chat_backend;
+ this->input = input;
+ this->chat_backend = chat_backend;
this->simple_singleplayer_mode = start_data.isSinglePlayer();
input->keycache.populate();
@@ -186,8 +206,8 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d
driver = device->getVideoDriver();
smgr = RenderingEngine::get_scene_manager();
- RenderingEngine::get_scene_manager()->getParameters()->setAttribute(
- scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
+ RenderingEngine::get_scene_manager()->getParameters()->
+ setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
// Reinit runData
runData = GameRunData();
@@ -201,8 +221,8 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d
g_client_translations->clear();
// address can change if simple_singleplayer_mode
- if (!init(start_data.world_spec.path, start_data.address, start_data.socket_port,
- start_data.game_spec))
+ if (!init(start_data.world_spec.path, start_data.address,
+ start_data.socket_port, start_data.game_spec))
return false;
if (!createClient(start_data))
@@ -213,13 +233,14 @@ bool Game::startup(bool *kill, InputHandler *input, const GameStartData &start_d
return true;
}
+
void Game::run()
{
ProfilerGraph graph;
- RunStats stats = {0};
- FpsControl draw_times = {0};
+ RunStats stats = { 0 };
+ FpsControl draw_times = { 0 };
f32 dtime; // in seconds
-
+
/* Clear the profiler */
Profiler::GraphValues dummyvalues;
g_profiler->graphGet(dummyvalues);
@@ -229,25 +250,24 @@ void Game::run()
set_light_table(g_settings->getFloat("display_gamma"));
#ifdef __ANDROID__
- m_cache_hold_aux1 = g_settings->getBool("fast_move") &&
- client->checkPrivilege("fast");
+ m_cache_hold_aux1 = g_settings->getBool("fast_move")
+ && client->checkPrivilege("fast");
#endif
- irr::core::dimension2d<u32> previous_screen_size(
- g_settings->getU16("screen_w"), g_settings->getU16("screen_h"));
+ irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
+ g_settings->getU16("screen_h"));
- while (RenderingEngine::run() &&
- !(*kill || g_gamecallback->shutdown_requested ||
- (server && server->isShutdownRequested()))) {
+ while (RenderingEngine::run()
+ && !(*kill || g_gamecallback->shutdown_requested
+ || (server && server->isShutdownRequested()))) {
const irr::core::dimension2d<u32> &current_screen_size =
- RenderingEngine::get_video_driver()->getScreenSize();
+ RenderingEngine::get_video_driver()->getScreenSize();
// Verify if window size has changed and save it if it's the case
// Ensure evaluating settings->getBool after verifying screensize
// First condition is cheaper
if (previous_screen_size != current_screen_size &&
- current_screen_size !=
- irr::core::dimension2d<u32>(0, 0) &&
+ current_screen_size != irr::core::dimension2d<u32>(0,0) &&
g_settings->getBool("autosave_screensize")) {
g_settings->setU16("screen_w", current_screen_size.Width);
g_settings->setU16("screen_h", current_screen_size.Height);
@@ -278,32 +298,30 @@ void Game::run()
processUserInput(dtime);
// Update camera before player movement to avoid camera lag of one frame
updateCameraDirection(&cam_view_target, dtime);
- cam_view.camera_yaw +=
- (cam_view_target.camera_yaw - cam_view.camera_yaw) *
- m_cache_cam_smoothing;
- cam_view.camera_pitch +=
- (cam_view_target.camera_pitch - cam_view.camera_pitch) *
- m_cache_cam_smoothing;
+ cam_view.camera_yaw += (cam_view_target.camera_yaw -
+ cam_view.camera_yaw) * m_cache_cam_smoothing;
+ cam_view.camera_pitch += (cam_view_target.camera_pitch -
+ cam_view.camera_pitch) * m_cache_cam_smoothing;
updatePlayerControl(cam_view);
step(&dtime);
processClientEvents(&cam_view_target);
updateCamera(draw_times.busy_time, dtime);
updateSound(dtime);
processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
- m_game_ui->m_flags.show_debug);
+ m_game_ui->m_flags.show_debug);
updateFrame(&graph, &stats, dtime, cam_view);
updateProfilerGraphs(&graph);
// Update if minimap has been disabled by the server
m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
- if (m_does_lost_focus_pause_game && !device->isWindowFocused() &&
- !isMenuActive()) {
+ if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
showPauseMenu();
}
}
}
+
void Game::shutdown()
{
RenderingEngine::finalize();
@@ -358,13 +376,17 @@ void Game::shutdown()
}
}
+
/****************************************************************************/
/****************************************************************************
Startup
****************************************************************************/
/****************************************************************************/
-bool Game::init(const std::string &map_dir, const std::string &address, u16 port,
+bool Game::init(
+ const std::string &map_dir,
+ const std::string &address,
+ u16 port,
const SubgameSpec &gamespec)
{
texture_src = createTextureSource();
@@ -379,8 +401,8 @@ bool Game::init(const std::string &map_dir, const std::string &address, u16 port
eventmgr = new EventManager();
quicktune = new QuicktuneShortcutter();
- if (!(texture_src && shader_src && itemdef_manager && nodedef_manager &&
- eventmgr && quicktune))
+ if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
+ && eventmgr && quicktune))
return false;
if (!initSound())
@@ -400,8 +422,7 @@ bool Game::initSound()
#if USE_SOUND
if (g_settings->getBool("enable_sound") && g_sound_manager_singleton.get()) {
infostream << "Attempting to use OpenAL audio" << std::endl;
- sound = createOpenALSoundManager(
- g_sound_manager_singleton.get(), &soundfetcher);
+ sound = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher);
if (!sound)
infostream << "Failed to initialize OpenAL audio" << std::endl;
} else
@@ -423,8 +444,8 @@ bool Game::initSound()
return true;
}
-bool Game::createSingleplayerServer(
- const std::string &map_dir, const SubgameSpec &gamespec, u16 port)
+bool Game::createSingleplayerServer(const std::string &map_dir,
+ const SubgameSpec &gamespec, u16 port)
{
showOverlayMessage(N_("Creating server..."), 0, 5);
@@ -432,7 +453,7 @@ bool Game::createSingleplayerServer(
Address bind_addr(0, 0, 0, 0, port);
if (g_settings->getBool("ipv6_server")) {
- bind_addr.setAddress((IPv6AddressBytes *)NULL);
+ bind_addr.setAddress((IPv6AddressBytes *) NULL);
}
try {
@@ -444,14 +465,14 @@ bool Game::createSingleplayerServer(
}
if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
- *error_message = "Unable to listen on " + bind_addr.serializeString() +
- " because IPv6 is disabled";
+ *error_message = "Unable to listen on " +
+ bind_addr.serializeString() +
+ " because IPv6 is disabled";
errorstream << *error_message << std::endl;
return false;
}
- server = new Server(
- map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
+ server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
server->start();
return true;
@@ -493,9 +514,8 @@ bool Game::createClient(const GameStartData &start_data)
return false;
}
- GameGlobalShaderConstantSetterFactory *scsf =
- new GameGlobalShaderConstantSetterFactory(&m_flags.force_fog_off,
- &runData.fog_range, client);
+ GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
+ &m_flags.force_fog_off, &runData.fog_range, client);
shader_src->addShaderConstantSetterFactory(scsf);
// Update cached textures, meshes and materials
@@ -523,7 +543,7 @@ bool Game::createClient(const GameStartData &start_data)
*/
sky = new Sky(-1, texture_src);
scsf->setSky(sky);
- skybox = NULL; // This is used/set later on in the main run loop
+ skybox = NULL; // This is used/set later on in the main run loop
if (!sky) {
*error_message = "Memory allocation error sky";
@@ -587,15 +607,15 @@ bool Game::initGui()
chat_backend->applySettings();
// Chat backend and console
- gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1,
- chat_backend, client, &g_menumgr);
+ gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
+ -1, chat_backend, client, &g_menumgr);
if (!gui_chat_console) {
*error_message = "Could not allocate memory for chat console";
errorstream << *error_message << std::endl;
return false;
}
-
+
m_cheat_menu = new CheatMenu(client);
if (!m_cheat_menu) {
@@ -614,10 +634,10 @@ bool Game::initGui()
return true;
}
-bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
- bool *connection_aborted)
+bool Game::connectToServer(const GameStartData &start_data,
+ bool *connect_ok, bool *connection_aborted)
{
- *connect_ok = false; // Let's not be overly optimistic
+ *connect_ok = false; // Let's not be overly optimistic
*connection_aborted = false;
bool local_server_mode = false;
@@ -629,7 +649,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
connect_address.Resolve(start_data.address.c_str());
if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
- // connect_address.Resolve("localhost");
+ //connect_address.Resolve("localhost");
if (connect_address.isIPv6()) {
IPv6AddressBytes addr_bytes;
addr_bytes.bytes[15] = 1;
@@ -647,14 +667,15 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
*error_message = "Unable to connect to " +
- connect_address.serializeString() +
- " because IPv6 is disabled";
+ connect_address.serializeString() +
+ " because IPv6 is disabled";
errorstream << *error_message << std::endl;
return false;
}
- client = new Client(start_data.name.c_str(), start_data.password,
- start_data.address, *draw_control, texture_src, shader_src,
+ client = new Client(start_data.name.c_str(),
+ start_data.password, start_data.address,
+ *draw_control, texture_src, shader_src,
itemdef_manager, nodedef_manager, sound, eventmgr,
connect_address.isIPv6(), m_game_ui.get());
@@ -667,7 +688,8 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
connect_address.print(&infostream);
infostream << std::endl;
- client->connect(connect_address, simple_singleplayer_mode || local_server_mode);
+ client->connect(connect_address,
+ simple_singleplayer_mode || local_server_mode);
/*
Wait for server to accept connection
@@ -676,7 +698,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
try {
input->clear();
- FpsControl fps_control = {0};
+ FpsControl fps_control = { 0 };
f32 dtime;
f32 wait_time = 0; // in seconds
@@ -703,8 +725,8 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
break;
if (client->accessDenied()) {
- *error_message = "Access denied. Reason: " +
- client->accessDeniedReason();
+ *error_message = "Access denied. Reason: "
+ + client->accessDeniedReason();
*reconnect_requested = client->reconnectRequested();
errorstream << *error_message << std::endl;
break;
@@ -719,22 +741,16 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
if (client->m_is_registration_confirmation_state) {
if (registration_confirmation_shown) {
// Keep drawing the GUI
- RenderingEngine::draw_menu_scene(
- guienv, dtime, true);
+ RenderingEngine::draw_menu_scene(guienv, dtime, true);
} else {
registration_confirmation_shown = true;
- (new GUIConfirmRegistration(guienv,
- guienv->getRootGUIElement(), -1,
- &g_menumgr, client,
- start_data.name,
- start_data.password,
- connection_aborted, texture_src))
- ->drop();
+ (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1,
+ &g_menumgr, client, start_data.name, start_data.password,
+ connection_aborted, texture_src))->drop();
}
} else {
wait_time += dtime;
- // Only time out if we aren't waiting for the server we
- // started
+ // Only time out if we aren't waiting for the server we started
if (!start_data.isSinglePlayer() && wait_time > 10) {
*error_message = "Connection timed out.";
errorstream << *error_message << std::endl;
@@ -742,8 +758,7 @@ bool Game::connectToServer(const GameStartData &start_data, bool *connect_ok,
}
// Update status
- showOverlayMessage(
- N_("Connecting to server..."), dtime, 20);
+ showOverlayMessage(N_("Connecting to server..."), dtime, 20);
}
}
} catch (con::PeerNotFoundException &e) {
@@ -759,7 +774,7 @@ bool Game::getServerContent(bool *aborted)
{
input->clear();
- FpsControl fps_control = {0};
+ FpsControl fps_control = { 0 };
f32 dtime; // in seconds
fps_control.last_time = RenderingEngine::get_timer_time();
@@ -802,26 +817,24 @@ bool Game::getServerContent(bool *aborted)
if (!client->itemdefReceived()) {
const wchar_t *text = wgettext("Item definitions...");
progress = 25;
- RenderingEngine::draw_load_screen(
- text, guienv, texture_src, dtime, progress);
+ RenderingEngine::draw_load_screen(text, guienv, texture_src,
+ dtime, progress);
delete[] text;
} else if (!client->nodedefReceived()) {
const wchar_t *text = wgettext("Node definitions...");
progress = 30;
- RenderingEngine::draw_load_screen(
- text, guienv, texture_src, dtime, progress);
+ RenderingEngine::draw_load_screen(text, guienv, texture_src,
+ dtime, progress);
delete[] text;
} else {
std::stringstream message;
std::fixed(message);
message.precision(0);
- message << gettext("Media...") << " "
- << (client->mediaReceiveProgress() * 100) << "%";
+ message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
message.precision(2);
if ((USE_CURL == 0) ||
- (!g_settings->getBool(
- "enable_remote_media_server"))) {
+ (!g_settings->getBool("enable_remote_media_server"))) {
float cur = client->getCurRate();
std::string cur_unit = gettext("KiB/s");
@@ -834,14 +847,15 @@ bool Game::getServerContent(bool *aborted)
}
progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
- RenderingEngine::draw_load_screen(utf8_to_wide(message.str()),
- guienv, texture_src, dtime, progress);
+ RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
+ texture_src, dtime, progress);
}
}
return true;
}
+
/****************************************************************************/
/****************************************************************************
Run
@@ -859,12 +873,14 @@ inline void Game::updateInteractTimers(f32 dtime)
runData.time_from_last_punch += dtime;
}
+
/* returns false if game should exit, otherwise true
*/
inline bool Game::checkConnection()
{
if (client->accessDenied()) {
- *error_message = "Access denied. Reason: " + client->accessDeniedReason();
+ *error_message = "Access denied. Reason: "
+ + client->accessDeniedReason();
*reconnect_requested = client->reconnectRequested();
errorstream << *error_message << std::endl;
return false;
@@ -873,6 +889,7 @@ inline bool Game::checkConnection()
return true;
}
+
/* returns false if game should exit, otherwise true
*/
inline bool Game::handleCallbacks()
@@ -883,21 +900,20 @@ inline bool Game::handleCallbacks()
}
if (g_gamecallback->changepassword_requested) {
- (new GUIPasswordChange(
- guienv, guiroot, -1, &g_menumgr, client, texture_src))
- ->drop();
+ (new GUIPasswordChange(guienv, guiroot, -1,
+ &g_menumgr, client, texture_src))->drop();
g_gamecallback->changepassword_requested = false;
}
if (g_gamecallback->changevolume_requested) {
- (new GUIVolumeChange(guienv, guiroot, -1, &g_menumgr, texture_src))
- ->drop();
+ (new GUIVolumeChange(guienv, guiroot, -1,
+ &g_menumgr, texture_src))->drop();
g_gamecallback->changevolume_requested = false;
}
if (g_gamecallback->keyconfig_requested) {
- (new GUIKeyChangeMenu(guienv, guiroot, -1, &g_menumgr, texture_src))
- ->drop();
+ (new GUIKeyChangeMenu(guienv, guiroot, -1,
+ &g_menumgr, texture_src))->drop();
g_gamecallback->keyconfig_requested = false;
}
@@ -909,6 +925,7 @@ inline bool Game::handleCallbacks()
return true;
}
+
void Game::processQueues()
{
texture_src->processQueue();
@@ -916,9 +933,12 @@ void Game::processQueues()
shader_src->processQueue();
}
-void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
+
+void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
+ f32 dtime)
{
- float profiler_print_interval = g_settings->getFloat("profiler_print_interval");
+ float profiler_print_interval =
+ g_settings->getFloat("profiler_print_interval");
bool print_to_log = true;
if (profiler_print_interval == 0) {
@@ -937,14 +957,15 @@ void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times,
}
// Update update graphs
- g_profiler->graphAdd(
- "Time non-rendering [ms]", draw_times.busy_time - stats.drawtime);
+ g_profiler->graphAdd("Time non-rendering [ms]",
+ draw_times.busy_time - stats.drawtime);
g_profiler->graphAdd("Sleep [ms]", draw_times.sleep_time);
g_profiler->graphAdd("FPS", 1.0f / dtime);
}
-void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime)
+void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
+ f32 dtime)
{
f32 jitter;
@@ -992,6 +1013,8 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime)
}
}
+
+
/****************************************************************************
Input handling
****************************************************************************/
@@ -999,8 +1022,7 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime)
void Game::processUserInput(f32 dtime)
{
// Reset input if window not active or some menu is active
- if (!device->isWindowActive() || isMenuActive() ||
- guienv->hasFocus(gui_chat_console)) {
+ if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
input->clear();
#ifdef HAVE_TOUCHSCREENGUI
g_touchscreengui->hide();
@@ -1037,6 +1059,7 @@ void Game::processUserInput(f32 dtime)
processItemSelection(&runData.new_playeritem);
}
+
void Game::processKeyInput()
{
if (wasKeyDown(KeyType::DROP)) {
@@ -1065,11 +1088,9 @@ void Game::processKeyInput()
if (client->modsLoaded())
openConsole(0.2, L".");
else
- m_game_ui->showStatusText(
- wgettext("Client side scripting is disabled"));
+ m_game_ui->showStatusText(wgettext("Client side scripting is disabled"));
} else if (wasKeyDown(KeyType::CONSOLE)) {
- openConsole(core::clamp(
- g_settings->getFloat("console_height"), 0.1f, 1.0f));
+ openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
} else if (wasKeyDown(KeyType::FREEMOVE)) {
toggleFreeMove();
} else if (wasKeyDown(KeyType::JUMP)) {
@@ -1112,14 +1133,11 @@ void Game::processKeyInput()
}
} else if (wasKeyDown(KeyType::INC_VOLUME)) {
if (g_settings->getBool("enable_sound")) {
- float new_volume = rangelim(
- g_settings->getFloat("sound_volume") + 0.1f, 0.0f,
- 1.0f);
+ float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
wchar_t buf[100];
g_settings->setFloat("sound_volume", new_volume);
const wchar_t *str = wgettext("Volume changed to %d%%");
- swprintf(buf, sizeof(buf) / sizeof(wchar_t), str,
- myround(new_volume * 100));
+ swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
delete[] str;
m_game_ui->showStatusText(buf);
} else {
@@ -1127,24 +1145,20 @@ void Game::processKeyInput()
}
} else if (wasKeyDown(KeyType::DEC_VOLUME)) {
if (g_settings->getBool("enable_sound")) {
- float new_volume = rangelim(
- g_settings->getFloat("sound_volume") - 0.1f, 0.0f,
- 1.0f);
+ float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
wchar_t buf[100];
g_settings->setFloat("sound_volume", new_volume);
const wchar_t *str = wgettext("Volume changed to %d%%");
- swprintf(buf, sizeof(buf) / sizeof(wchar_t), str,
- myround(new_volume * 100));
+ swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
delete[] str;
m_game_ui->showStatusText(buf);
} else {
m_game_ui->showTranslatedStatusText("Sound system is disabled");
}
#else
- } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME) ||
- wasKeyDown(KeyType::DEC_VOLUME)) {
- m_game_ui->showTranslatedStatusText(
- "Sound system is not supported on this build");
+ } else if (wasKeyDown(KeyType::MUTE) || wasKeyDown(KeyType::INC_VOLUME)
+ || wasKeyDown(KeyType::DEC_VOLUME)) {
+ m_game_ui->showTranslatedStatusText("Sound system is not supported on this build");
#endif
} else if (wasKeyDown(KeyType::CINEMATIC)) {
toggleCinematic();
@@ -1203,7 +1217,8 @@ void Game::processItemSelection(u16 *new_playeritem)
*new_playeritem = player->getWieldIndex();
s32 wheel = input->getMouseWheel();
- u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1, player->hud_hotbar_itemcount - 1);
+ u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
+ player->hud_hotbar_itemcount - 1);
s32 dir = wheel;
@@ -1226,13 +1241,14 @@ void Game::processItemSelection(u16 *new_playeritem)
/* Item selection using hotbar slot keys
*/
for (u16 i = 0; i <= max_item; i++) {
- if (wasKeyDown((GameKeyType)(KeyType::SLOT_1 + i))) {
+ if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
*new_playeritem = i;
break;
}
}
}
+
void Game::dropSelectedItem(bool single_item)
{
IDropAction *a = new IDropAction();
@@ -1243,6 +1259,7 @@ void Game::dropSelectedItem(bool single_item)
client->inventoryAction(a);
}
+
void Game::openInventory()
{
/*
@@ -1261,13 +1278,12 @@ void Game::openInventory()
InventoryLocation inventoryloc;
inventoryloc.setCurrentPlayer();
- if (!client->modsLoaded() ||
- !client->getScript()->on_inventory_open(
- fs_src->m_client->getInventory(inventoryloc))) {
+ if (!client->modsLoaded()
+ || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
TextDest *txt_dst = new TextDestPlayerInventory(client);
auto *&formspec = m_game_ui->updateFormspec("");
GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
- txt_dst, client->getFormspecPrepend());
+ txt_dst, client->getFormspecPrepend());
formspec->setFormSpec(fs_src->getForm(), inventoryloc);
}
@@ -1285,6 +1301,7 @@ void Game::openEnderchest()
client->getScript()->open_enderchest();
}
+
void Game::openConsole(float scale, const wchar_t *line)
{
assert(scale > 0.0f && scale <= 1.0f);
@@ -1314,6 +1331,7 @@ void Game::handleAndroidChatInput()
}
#endif
+
void Game::toggleFreeMove()
{
bool free_move = !g_settings->getBool("free_move");
@@ -1323,8 +1341,7 @@ void Game::toggleFreeMove()
if (client->checkPrivilege("fly")) {
m_game_ui->showTranslatedStatusText("Fly mode enabled");
} else {
- m_game_ui->showTranslatedStatusText(
- "Fly mode enabled (note: no 'fly' privilege)");
+ m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
}
} else {
m_game_ui->showTranslatedStatusText("Fly mode disabled");
@@ -1339,6 +1356,7 @@ void Game::toggleFreeMoveAlt()
runData.reset_jump_timer = true;
}
+
void Game::togglePitchMove()
{
bool pitch_move = !g_settings->getBool("pitch_move");
@@ -1351,6 +1369,7 @@ void Game::togglePitchMove()
}
}
+
void Game::toggleFast()
{
bool fast_move = !g_settings->getBool("fast_move");
@@ -1361,8 +1380,7 @@ void Game::toggleFast()
if (has_fast_privs) {
m_game_ui->showTranslatedStatusText("Fast mode enabled");
} else {
- m_game_ui->showTranslatedStatusText(
- "Fast mode enabled (note: no 'fast' privilege)");
+ m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
}
} else {
m_game_ui->showTranslatedStatusText("Fast mode disabled");
@@ -1373,6 +1391,7 @@ void Game::toggleFast()
#endif
}
+
void Game::toggleNoClip()
{
bool noclip = !g_settings->getBool("noclip");
@@ -1382,8 +1401,7 @@ void Game::toggleNoClip()
if (client->checkPrivilege("noclip")) {
m_game_ui->showTranslatedStatusText("Noclip mode enabled");
} else {
- m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: "
- "no 'noclip' privilege)");
+ m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
}
} else {
m_game_ui->showTranslatedStatusText("Noclip mode disabled");
@@ -1392,7 +1410,7 @@ void Game::toggleNoClip()
void Game::toggleKillaura()
{
- bool killaura = !g_settings->getBool("killaura");
+ bool killaura = ! g_settings->getBool("killaura");
g_settings->set("killaura", bool_to_cstr(killaura));
if (killaura) {
@@ -1404,7 +1422,7 @@ void Game::toggleKillaura()
void Game::toggleFreecam()
{
- bool freecam = !g_settings->getBool("freecam");
+ bool freecam = ! g_settings->getBool("freecam");
g_settings->set("freecam", bool_to_cstr(freecam));
if (freecam) {
@@ -1416,7 +1434,7 @@ void Game::toggleFreecam()
void Game::toggleScaffold()
{
- bool scaffold = !g_settings->getBool("scaffold");
+ bool scaffold = ! g_settings->getBool("scaffold");
g_settings->set("scaffold", bool_to_cstr(scaffold));
if (scaffold) {
@@ -1428,7 +1446,7 @@ void Game::toggleScaffold()
void Game::toggleNextItem()
{
- bool next_item = !g_settings->getBool("next_item");
+ bool next_item = ! g_settings->getBool("next_item");
g_settings->set("next_item", bool_to_cstr(next_item));
if (next_item) {
@@ -1463,8 +1481,7 @@ void Game::toggleAutoforward()
void Game::toggleMinimap(bool shift_pressed)
{
- if (!mapper || !m_game_ui->m_flags.show_hud ||
- !g_settings->getBool("enable_minimap"))
+ if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
return;
if (shift_pressed) {
@@ -1485,32 +1502,31 @@ void Game::toggleMinimap(bool shift_pressed)
m_game_ui->m_flags.show_minimap = true;
switch (mode) {
- case MINIMAP_MODE_SURFACEx1:
- m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
- break;
- case MINIMAP_MODE_SURFACEx2:
- m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
- break;
- case MINIMAP_MODE_SURFACEx4:
- m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
- break;
- case MINIMAP_MODE_RADARx1:
- m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
- break;
- case MINIMAP_MODE_RADARx2:
- m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
- break;
- case MINIMAP_MODE_RADARx4:
- m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
- break;
- default:
- mode = MINIMAP_MODE_OFF;
- m_game_ui->m_flags.show_minimap = false;
- if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
- m_game_ui->showTranslatedStatusText("Minimap hidden");
- else
- m_game_ui->showTranslatedStatusText(
- "Minimap currently disabled by game or mod");
+ case MINIMAP_MODE_SURFACEx1:
+ m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
+ break;
+ case MINIMAP_MODE_SURFACEx2:
+ m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
+ break;
+ case MINIMAP_MODE_SURFACEx4:
+ m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
+ break;
+ case MINIMAP_MODE_RADARx1:
+ m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
+ break;
+ case MINIMAP_MODE_RADARx2:
+ m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
+ break;
+ case MINIMAP_MODE_RADARx4:
+ m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
+ break;
+ default:
+ mode = MINIMAP_MODE_OFF;
+ m_game_ui->m_flags.show_minimap = false;
+ if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
+ m_game_ui->showTranslatedStatusText("Minimap hidden");
+ else
+ m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
}
mapper->setMinimapMode(mode);
@@ -1526,6 +1542,7 @@ void Game::toggleFog()
m_game_ui->showTranslatedStatusText("Fog enabled");
}
+
void Game::toggleDebug()
{
// Initial / 4x toggle: Chat only
@@ -1537,8 +1554,7 @@ void Game::toggleDebug()
m_game_ui->m_flags.show_profiler_graph = false;
draw_control->show_wireframe = false;
m_game_ui->showTranslatedStatusText("Debug info shown");
- } else if (!m_game_ui->m_flags.show_profiler_graph &&
- !draw_control->show_wireframe) {
+ } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
m_game_ui->m_flags.show_profiler_graph = true;
m_game_ui->showTranslatedStatusText("Profiler graph shown");
} else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
@@ -1550,15 +1566,14 @@ void Game::toggleDebug()
m_game_ui->m_flags.show_profiler_graph = false;
draw_control->show_wireframe = false;
if (client->checkPrivilege("debug")) {
- m_game_ui->showTranslatedStatusText("Debug info, profiler graph, "
- "and wireframe hidden");
+ m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
} else {
- m_game_ui->showTranslatedStatusText(
- "Debug info and profiler graph hidden");
+ m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
}
}
}
+
void Game::toggleUpdateCamera()
{
if (g_settings->getBool("freecam"))
@@ -1570,6 +1585,7 @@ void Game::toggleUpdateCamera()
m_game_ui->showTranslatedStatusText("Camera update enabled");
}
+
void Game::increaseViewRange()
{
s16 range = g_settings->getS16("viewing_range");
@@ -1593,6 +1609,7 @@ void Game::increaseViewRange()
g_settings->set("viewing_range", itos(range_new));
}
+
void Game::decreaseViewRange()
{
s16 range = g_settings->getS16("viewing_range");
@@ -1615,6 +1632,7 @@ void Game::decreaseViewRange()
g_settings->set("viewing_range", itos(range_new));
}
+
void Game::toggleFullViewRange()
{
draw_control->range_all = !draw_control->range_all;
@@ -1624,18 +1642,19 @@ void Game::toggleFullViewRange()
m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
}
+
void Game::checkZoomEnabled()
{
LocalPlayer *player = client->getEnv().getLocalPlayer();
if (player->getZoomFOV() < 0.001f || player->getFov().fov > 0.0f)
- m_game_ui->showTranslatedStatusText(
- "Zoom currently disabled by game or mod");
+ m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
}
+
void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
{
- if ((device->isWindowActive() && device->isWindowFocused() && !isMenuActive()) ||
- input->isRandom()) {
+ if ((device->isWindowActive() && device->isWindowFocused()
+ && !isMenuActive()) || input->isRandom()) {
#ifndef __ANDROID__
if (!input->isRandom()) {
@@ -1649,7 +1668,7 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
m_first_loop_after_window_activation = false;
input->setMousePos(driver->getScreenSize().Width / 2,
- driver->getScreenSize().Height / 2);
+ driver->getScreenSize().Height / 2);
} else {
updateCameraOrientation(cam, dtime);
}
@@ -1663,6 +1682,7 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
#endif
m_first_loop_after_window_activation = true;
+
}
}
@@ -1670,20 +1690,18 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
{
#ifdef HAVE_TOUCHSCREENGUI
if (g_touchscreengui) {
- cam->camera_yaw += g_touchscreengui->getYawChange();
- cam->camera_pitch = g_touchscreengui->getPitch();
+ cam->camera_yaw += g_touchscreengui->getYawChange();
+ cam->camera_pitch = g_touchscreengui->getPitch();
} else {
#endif
- v2s32 center(driver->getScreenSize().Width / 2,
- driver->getScreenSize().Height / 2);
+ v2s32 center(driver->getScreenSize().Width / 2, driver->getScreenSize().Height / 2);
v2s32 dist = input->getMousePos() - center;
- if (m_invert_mouse ||
- camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
+ if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
dist.Y = -dist.Y;
}
- cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
+ cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity;
cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity;
if (dist.X != 0 || dist.Y != 0)
@@ -1694,45 +1712,51 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
if (m_cache_enable_joysticks) {
f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
- cam->camera_yaw -= input->joystick.getAxisWithoutDead(
- JA_FRUSTUM_HORIZONTAL) *
- c;
- cam->camera_pitch +=
- input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
- c;
+ cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
+ cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
}
cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
}
+
void Game::updatePlayerControl(const CameraOrientation &cam)
{
- // TimeTaker tt("update player control", NULL, PRECISION_NANO);
+ //TimeTaker tt("update player control", NULL, PRECISION_NANO);
// DO NOT use the isKeyDown method for the forward, backward, left, right
// buttons, as the code that uses the controls needs to be able to
// distinguish between the two in order to know when to use joysticks.
- PlayerControl control(input->isKeyDown(KeyType::FORWARD),
- input->isKeyDown(KeyType::BACKWARD),
- input->isKeyDown(KeyType::LEFT), input->isKeyDown(KeyType::RIGHT),
- isKeyDown(KeyType::JUMP), isKeyDown(KeyType::SPECIAL1),
- isKeyDown(KeyType::SNEAK), isKeyDown(KeyType::ZOOM),
- input->getLeftState(), input->getRightState(), cam.camera_pitch,
- cam.camera_yaw,
- input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
- input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE));
-
- u32 keypress_bits = (((u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
- ((u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
- ((u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
- ((u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
- ((u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
- ((u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
- ((u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
- ((u32)(input->getLeftState() & 0x1) << 7) |
- ((u32)(input->getRightState() & 0x1) << 8) |
- ((u32)(isKeyDown(KeyType::ZOOM) & 0x1) << 9));
+ PlayerControl control(
+ input->isKeyDown(KeyType::FORWARD),
+ input->isKeyDown(KeyType::BACKWARD),
+ input->isKeyDown(KeyType::LEFT),
+ input->isKeyDown(KeyType::RIGHT),
+ isKeyDown(KeyType::JUMP),
+ isKeyDown(KeyType::SPECIAL1),
+ isKeyDown(KeyType::SNEAK),
+ isKeyDown(KeyType::ZOOM),
+ input->getLeftState(),
+ input->getRightState(),
+ cam.camera_pitch,
+ cam.camera_yaw,
+ input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
+ input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
+ );
+
+ u32 keypress_bits = (
+ ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
+ ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
+ ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
+ ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
+ ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
+ ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
+ ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
+ ( (u32)(input->getLeftState() & 0x1) << 7) |
+ ( (u32)(input->getRightState() & 0x1) << 8) |
+ ( (u32)(isKeyDown(KeyType::ZOOM) & 0x1) << 9)
+ );
#ifdef ANDROID
/* For Android, simulate holding down AUX1 (fast move) if the user has
@@ -1764,15 +1788,17 @@ void Game::updatePlayerControl(const CameraOrientation &cam)
client->setPlayerControl(control);
player->keyPressed = keypress_bits;
- // tt.stop();
+ //tt.stop();
}
+
inline void Game::step(f32 *dtime)
{
- bool can_be_and_is_paused = (simple_singleplayer_mode && g_menumgr.pausesGame());
+ bool can_be_and_is_paused =
+ (simple_singleplayer_mode && g_menumgr.pausesGame());
if (can_be_and_is_paused) { // This is for a singleplayer server
- *dtime = 0; // No time passes
+ *dtime = 0; // No time passes
} else {
if (server)
server->step(*dtime);
@@ -1782,24 +1808,24 @@ inline void Game::step(f32 *dtime)
}
const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
- {&Game::handleClientEvent_None},
- {&Game::handleClientEvent_PlayerDamage},
- {&Game::handleClientEvent_PlayerForceMove},
- {&Game::handleClientEvent_Deathscreen},
- {&Game::handleClientEvent_ShowFormSpec},
- {&Game::handleClientEvent_ShowLocalFormSpec},
- {&Game::handleClientEvent_HandleParticleEvent},
- {&Game::handleClientEvent_HandleParticleEvent},
- {&Game::handleClientEvent_HandleParticleEvent},
- {&Game::handleClientEvent_HudAdd},
- {&Game::handleClientEvent_HudRemove},
- {&Game::handleClientEvent_HudChange},
- {&Game::handleClientEvent_SetSky},
- {&Game::handleClientEvent_SetSun},
- {&Game::handleClientEvent_SetMoon},
- {&Game::handleClientEvent_SetStars},
- {&Game::handleClientEvent_OverrideDayNigthRatio},
- {&Game::handleClientEvent_CloudParams},
+ {&Game::handleClientEvent_None},
+ {&Game::handleClientEvent_PlayerDamage},
+ {&Game::handleClientEvent_PlayerForceMove},
+ {&Game::handleClientEvent_Deathscreen},
+ {&Game::handleClientEvent_ShowFormSpec},
+ {&Game::handleClientEvent_ShowLocalFormSpec},
+ {&Game::handleClientEvent_HandleParticleEvent},
+ {&Game::handleClientEvent_HandleParticleEvent},
+ {&Game::handleClientEvent_HandleParticleEvent},
+ {&Game::handleClientEvent_HudAdd},
+ {&Game::handleClientEvent_HudRemove},
+ {&Game::handleClientEvent_HudChange},
+ {&Game::handleClientEvent_SetSky},
+ {&Game::handleClientEvent_SetSun},
+ {&Game::handleClientEvent_SetMoon},
+ {&Game::handleClientEvent_SetStars},
+ {&Game::handleClientEvent_OverrideDayNigthRatio},
+ {&Game::handleClientEvent_CloudParams},
};
void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
@@ -1821,7 +1847,7 @@ void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation
player->hurt_tilt_timer = 1.5f;
player->hurt_tilt_strength =
- rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
+ rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f);
}
// Play damage sound
@@ -1854,21 +1880,19 @@ void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation
{
if (event->show_formspec.formspec->empty()) {
auto formspec = m_game_ui->getFormspecGUI();
- if (formspec && (event->show_formspec.formname->empty() ||
- *(event->show_formspec.formname) ==
- m_game_ui->getFormspecName())) {
+ if (formspec && (event->show_formspec.formname->empty()
+ || *(event->show_formspec.formname) == m_game_ui->getFormspecName())) {
formspec->quitMenu();
}
} else {
FormspecFormSource *fs_src =
- new FormspecFormSource(*(event->show_formspec.formspec));
- TextDestPlayerInventory *txt_dst = new TextDestPlayerInventory(
- client, *(event->show_formspec.formname));
+ new FormspecFormSource(*(event->show_formspec.formspec));
+ TextDestPlayerInventory *txt_dst =
+ new TextDestPlayerInventory(client, *(event->show_formspec.formname));
- auto *&formspec = m_game_ui->updateFormspec(
- *(event->show_formspec.formname));
- GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
- txt_dst, client->getFormspecPrepend());
+ auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname));
+ GUIFormSpecMenu::create(formspec, client, &input->joystick,
+ fs_src, txt_dst, client->getFormspecPrepend());
}
delete event->show_formspec.formspec;
@@ -1877,10 +1901,9 @@ void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation
void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
{
- FormspecFormSource *fs_src =
- new FormspecFormSource(*event->show_formspec.formspec);
+ FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
LocalFormspecHandler *txt_dst =
- new LocalFormspecHandler(*event->show_formspec.formname, client);
+ new LocalFormspecHandler(*event->show_formspec.formname, client);
GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick,
fs_src, txt_dst, client->getFormspecPrepend());
@@ -1888,8 +1911,8 @@ void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrienta
delete event->show_formspec.formname;
}
-void Game::handleClientEvent_HandleParticleEvent(
- ClientEvent *event, CameraOrientation *cam)
+void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
+ CameraOrientation *cam)
{
LocalPlayer *player = client->getEnv().getLocalPlayer();
client->getParticleManager()->handleParticleEvent(event, client, player);
@@ -1917,20 +1940,20 @@ void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
}
HudElement *e = new HudElement;
- e->type = (HudElementType)event->hudadd.type;
- e->pos = *event->hudadd.pos;
- e->name = *event->hudadd.name;
- e->scale = *event->hudadd.scale;
- e->text = *event->hudadd.text;
+ e->type = (HudElementType)event->hudadd.type;
+ e->pos = *event->hudadd.pos;
+ e->name = *event->hudadd.name;
+ e->scale = *event->hudadd.scale;
+ e->text = *event->hudadd.text;
e->number = event->hudadd.number;
- e->item = event->hudadd.item;
- e->dir = event->hudadd.dir;
- e->align = *event->hudadd.align;
+ e->item = event->hudadd.item;
+ e->dir = event->hudadd.dir;
+ e->align = *event->hudadd.align;
e->offset = *event->hudadd.offset;
e->world_pos = *event->hudadd.world_pos;
e->size = *event->hudadd.size;
e->z_index = event->hudadd.z_index;
- e->text2 = *event->hudadd.text2;
+ e->text2 = *event->hudadd.text2;
hud_server_to_client[server_id] = player->addHud(e);
delete event->hudadd.pos;
@@ -1967,57 +1990,57 @@ void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *ca
}
switch (event->hudchange.stat) {
- case HUD_STAT_POS:
- e->pos = *event->hudchange.v2fdata;
- break;
+ case HUD_STAT_POS:
+ e->pos = *event->hudchange.v2fdata;
+ break;
- case HUD_STAT_NAME:
- e->name = *event->hudchange.sdata;
- break;
+ case HUD_STAT_NAME:
+ e->name = *event->hudchange.sdata;
+ break;
- case HUD_STAT_SCALE:
- e->scale = *event->hudchange.v2fdata;
- break;
+ case HUD_STAT_SCALE:
+ e->scale = *event->hudchange.v2fdata;
+ break;
- case HUD_STAT_TEXT:
- e->text = *event->hudchange.sdata;
- break;
+ case HUD_STAT_TEXT:
+ e->text = *event->hudchange.sdata;
+ break;
- case HUD_STAT_NUMBER:
- e->number = event->hudchange.data;
- break;
+ case HUD_STAT_NUMBER:
+ e->number = event->hudchange.data;
+ break;
- case HUD_STAT_ITEM:
- e->item = event->hudchange.data;
- break;
+ case HUD_STAT_ITEM:
+ e->item = event->hudchange.data;
+ break;
- case HUD_STAT_DIR:
- e->dir = event->hudchange.data;
- break;
+ case HUD_STAT_DIR:
+ e->dir = event->hudchange.data;
+ break;
- case HUD_STAT_ALIGN:
- e->align = *event->hudchange.v2fdata;
- break;
+ case HUD_STAT_ALIGN:
+ e->align = *event->hudchange.v2fdata;
+ break;
- case HUD_STAT_OFFSET:
- e->offset = *event->hudchange.v2fdata;
- break;
+ case HUD_STAT_OFFSET:
+ e->offset = *event->hudchange.v2fdata;
+ break;
- case HUD_STAT_WORLD_POS:
- e->world_pos = *event->hudchange.v3fdata;
- break;
+ case HUD_STAT_WORLD_POS:
+ e->world_pos = *event->hudchange.v3fdata;
+ break;
- case HUD_STAT_SIZE:
- e->size = *event->hudchange.v2s32data;
- break;
+ case HUD_STAT_SIZE:
+ e->size = *event->hudchange.v2s32data;
+ break;
- case HUD_STAT_Z_INDEX:
- e->z_index = event->hudchange.data;
- break;
+ case HUD_STAT_Z_INDEX:
+ e->z_index = event->hudchange.data;
+ break;
- case HUD_STAT_TEXT2:
- e->text2 = *event->hudchange.sdata;
- break;
+ case HUD_STAT_TEXT2:
+ e->text2 = *event->hudchange.sdata;
+ break;
}
delete event->hudchange.v3fdata;
@@ -2044,9 +2067,11 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
sky->setVisible(true);
// Update mesh based skybox colours if applicable.
sky->setSkyColors(event->set_sky->sky_color);
- sky->setHorizonTint(event->set_sky->fog_sun_tint,
- event->set_sky->fog_moon_tint,
- event->set_sky->fog_tint_type);
+ sky->setHorizonTint(
+ event->set_sky->fog_sun_tint,
+ event->set_sky->fog_moon_tint,
+ event->set_sky->fog_tint_type
+ );
} else if (event->set_sky->type == "skybox" &&
event->set_sky->textures.size() == 6) {
// Disable the dyanmic mesh skybox:
@@ -2054,23 +2079,27 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
// Set fog colors:
sky->setFallbackBgColor(event->set_sky->bgcolor);
// Set sunrise and sunset fog tinting:
- sky->setHorizonTint(event->set_sky->fog_sun_tint,
- event->set_sky->fog_moon_tint,
- event->set_sky->fog_tint_type);
+ sky->setHorizonTint(
+ event->set_sky->fog_sun_tint,
+ event->set_sky->fog_moon_tint,
+ event->set_sky->fog_tint_type
+ );
// Add textures to skybox.
for (int i = 0; i < 6; i++)
- sky->addTextureToSkybox(
- event->set_sky->textures[i], i, texture_src);
+ sky->addTextureToSkybox(event->set_sky->textures[i], i, texture_src);
} else {
// Handle everything else as plain color.
if (event->set_sky->type != "plain")
- infostream << "Unknown sky type: " << (event->set_sky->type)
- << std::endl;
+ infostream << "Unknown sky type: "
+ << (event->set_sky->type) << std::endl;
sky->setVisible(false);
sky->setFallbackBgColor(event->set_sky->bgcolor);
// Disable directional sun/moon tinting on plain or invalid skyboxes.
- sky->setHorizonTint(event->set_sky->bgcolor, event->set_sky->bgcolor,
- "custom");
+ sky->setHorizonTint(
+ event->set_sky->bgcolor,
+ event->set_sky->bgcolor,
+ "custom"
+ );
}
delete event->set_sky;
}
@@ -2078,8 +2107,8 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
{
sky->setSunVisible(event->sun_params->visible);
- sky->setSunTexture(event->sun_params->texture, event->sun_params->tonemap,
- texture_src);
+ sky->setSunTexture(event->sun_params->texture,
+ event->sun_params->tonemap, texture_src);
sky->setSunScale(event->sun_params->scale);
sky->setSunriseVisible(event->sun_params->sunrise_visible);
sky->setSunriseTexture(event->sun_params->sunrise, texture_src);
@@ -2089,8 +2118,8 @@ void Game::handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam)
void Game::handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam)
{
sky->setMoonVisible(event->moon_params->visible);
- sky->setMoonTexture(event->moon_params->texture, event->moon_params->tonemap,
- texture_src);
+ sky->setMoonTexture(event->moon_params->texture,
+ event->moon_params->tonemap, texture_src);
sky->setMoonScale(event->moon_params->scale);
delete event->moon_params;
}
@@ -2104,12 +2133,12 @@ void Game::handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam
delete event->star_params;
}
-void Game::handleClientEvent_OverrideDayNigthRatio(
- ClientEvent *event, CameraOrientation *cam)
+void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
+ CameraOrientation *cam)
{
client->getEnv().setDayNightRatioOverride(
- event->override_day_night_ratio.do_override,
- event->override_day_night_ratio.ratio_f * 1000.0f);
+ event->override_day_night_ratio.do_override,
+ event->override_day_night_ratio.ratio_f * 1000.0f);
}
void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
@@ -2129,9 +2158,8 @@ void Game::processClientEvents(CameraOrientation *cam)
{
while (client->hasClientEvents()) {
std::unique_ptr<ClientEvent> event(client->getClientEvent());
- FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX,
- "Invalid clientevent type");
- const ClientEventHandler &evHandler = clientEventHandler[event->type];
+ FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
+ const ClientEventHandler& evHandler = clientEventHandler[event->type];
(this->*evHandler.handler)(event.get(), cam);
}
}
@@ -2153,7 +2181,7 @@ void Game::updateChat(f32 dtime, const v2u32 &screensize)
// Display all messages in a static text element
m_game_ui->setChatText(chat_backend->getRecentChat(),
- chat_backend->getRecentBuffer().getLineCount());
+ chat_backend->getRecentBuffer().getLineCount());
}
void Game::updateCamera(u32 busy_time, f32 dtime)
@@ -2173,11 +2201,11 @@ void Game::updateCamera(u32 busy_time, f32 dtime)
}
ToolCapabilities playeritem_toolcap =
- playeritem.getToolCapabilities(itemdef_manager);
+ playeritem.getToolCapabilities(itemdef_manager);
v3s16 old_camera_offset = camera->getOffset();
- if (wasKeyDown(KeyType::CAMERA_MODE) && !g_settings->getBool("freecam")) {
+ if (wasKeyDown(KeyType::CAMERA_MODE) && ! g_settings->getBool("freecam")) {
camera->toggleCameraMode();
updatePlayerCAOVisibility();
}
@@ -2216,20 +2244,18 @@ void Game::updatePlayerCAOVisibility()
GenericCAO *playercao = player->getCAO();
if (!playercao)
return;
- playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST ||
- g_settings->getBool("freecam"));
- playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST ||
- g_settings->getBool("freecam"));
+ playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || g_settings->getBool("freecam"));
+ playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST || g_settings->getBool("freecam"));
}
void Game::updateSound(f32 dtime)
{
// Update sound listener
v3s16 camera_offset = camera->getOffset();
- sound->updateListener(camera->getCameraNode()->getPosition() +
- intToFloat(camera_offset, BS),
- v3f(0, 0, 0), // velocity
- camera->getDirection(), camera->getCameraNode()->getUpVector());
+ sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
+ v3f(0, 0, 0), // velocity
+ camera->getDirection(),
+ camera->getCameraNode()->getUpVector());
bool mute_sound = g_settings->getBool("mute_sound");
if (mute_sound) {
@@ -2259,12 +2285,13 @@ void Game::updateSound(f32 dtime)
soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
}
+
void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
{
LocalPlayer *player = client->getEnv().getLocalPlayer();
const v3f camera_direction = camera->getDirection();
- const v3s16 camera_offset = camera->getOffset();
+ const v3s16 camera_offset = camera->getOffset();
/*
Calculate what block is the crosshair pointing to
@@ -2275,7 +2302,7 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
const ItemDefinition &selected_def = selected_item.getDefinition(itemdef_manager);
f32 d = getToolRange(selected_def, hand_item.getDefinition(itemdef_manager));
-
+
if (g_settings->getBool("increase_tool_range"))
d += 2;
if (g_settings->getBool("increase_tool_range_plus"))
@@ -2305,17 +2332,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
shootline = g_touchscreengui->getShootline();
// Scale shootline to the acual distance the player can reach
- shootline.end = shootline.start +
- shootline.getVector().normalize() * BS * d;
+ shootline.end = shootline.start
+ + shootline.getVector().normalize() * BS * d;
shootline.start += intToFloat(camera_offset, BS);
shootline.end += intToFloat(camera_offset, BS);
}
#endif
- PointedThing pointed =
- updatePointedThing(shootline, selected_def.liquids_pointable,
- !runData.ldown_for_dig, camera_offset);
+ PointedThing pointed = updatePointedThing(shootline,
+ selected_def.liquids_pointable,
+ !runData.ldown_for_dig,
+ camera_offset);
if (pointed != runData.pointed_old) {
infostream << "Pointing at " << pointed.dump() << std::endl;
@@ -2335,19 +2363,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
if (runData.digging) {
if (input->getLeftReleased()) {
infostream << "Left button released"
- << " (stopped digging)" << std::endl;
+ << " (stopped digging)" << std::endl;
runData.digging = false;
} else if (pointed != runData.pointed_old) {
- if (pointed.type == POINTEDTHING_NODE &&
- runData.pointed_old.type == POINTEDTHING_NODE &&
- pointed.node_undersurface ==
- runData.pointed_old
- .node_undersurface) {
+ if (pointed.type == POINTEDTHING_NODE
+ && runData.pointed_old.type == POINTEDTHING_NODE
+ && pointed.node_undersurface
+ == runData.pointed_old.node_undersurface) {
// Still pointing to the same node, but a different face.
// Don't reset.
} else {
infostream << "Pointing away from node"
- << " (stopped digging)" << std::endl;
+ << " (stopped digging)" << std::endl;
runData.digging = false;
hud->updateSelectionMesh(camera_offset);
}
@@ -2373,22 +2400,19 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
soundmaker->m_player_leftpunch_sound.name = "";
// Prepare for repeating, unless we're not supposed to
- if ((input->getRightState() || g_settings->getBool("autoplace")) &&
- !g_settings->getBool("safe_dig_and_place"))
+ if ((input->getRightState() || g_settings->getBool("autoplace")) && !g_settings->getBool("safe_dig_and_place"))
runData.repeat_rightclick_timer += dtime;
else
runData.repeat_rightclick_timer = 0;
if (selected_def.usable && input->getLeftState()) {
- if (input->getLeftClicked() &&
- (!client->modsLoaded() ||
- !client->getScript()->on_item_use(
- selected_item, pointed)))
+ if (input->getLeftClicked() && (!client->modsLoaded()
+ || !client->getScript()->on_item_use(selected_item, pointed)))
client->interact(INTERACT_USE, pointed);
} else if (pointed.type == POINTEDTHING_NODE) {
handlePointingAtNode(pointed, selected_item, hand_item, dtime);
} else if (pointed.type == POINTEDTHING_OBJECT) {
- v3f player_position = player->getPosition();
+ v3f player_position = player->getPosition();
handlePointingAtObject(pointed, tool_item, player_position, show_debug);
} else if (input->getLeftState()) {
// When button is held down in air, show continuous animation
@@ -2412,14 +2436,18 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
input->resetRightReleased();
}
-PointedThing Game::updatePointedThing(const core::line3d<f32> &shootline,
- bool liquids_pointable, bool look_for_object, const v3s16 &camera_offset)
+
+PointedThing Game::updatePointedThing(
+ const core::line3d<f32> &shootline,
+ bool liquids_pointable,
+ bool look_for_object,
+ const v3s16 &camera_offset)
{
std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
selectionboxes->clear();
hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
- static thread_local const bool show_entity_selectionbox =
- g_settings->getBool("show_entity_selectionbox");
+ static thread_local const bool show_entity_selectionbox = g_settings->getBool(
+ "show_entity_selectionbox");
ClientEnvironment &env = client->getEnv();
ClientMap &map = env.getClientMap();
@@ -2427,20 +2455,16 @@ PointedThing Game::updatePointedThing(const core::line3d<f32> &shootline,
runData.selected_object = NULL;
hud->pointing_at_object = false;
- RaycastState s(shootline, look_for_object, liquids_pointable,
- !g_settings->getBool("dont_point_nodes"));
+ RaycastState s(shootline, look_for_object, liquids_pointable, ! g_settings->getBool("dont_point_nodes"));
PointedThing result;
env.continueRaycast(&s, &result);
if (result.type == POINTEDTHING_OBJECT) {
hud->pointing_at_object = true;
- runData.selected_object =
- client->getEnv().getActiveObject(result.object_id);
+ runData.selected_object = client->getEnv().getActiveObject(result.object_id);
aabb3f selection_box;
- if (show_entity_selectionbox &&
- runData.selected_object->doShowSelectionBox() &&
- runData.selected_object->getSelectionBox(
- &selection_box)) {
+ if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
+ runData.selected_object->getSelectionBox(&selection_box)) {
v3f pos = runData.selected_object->getPosition();
selectionboxes->push_back(aabb3f(selection_box));
hud->setSelectionPos(pos, camera_offset);
@@ -2450,21 +2474,22 @@ PointedThing Game::updatePointedThing(const core::line3d<f32> &shootline,
MapNode n = map.getNode(result.node_undersurface);
std::vector<aabb3f> boxes;
n.getSelectionBoxes(nodedef, &boxes,
- n.getNeighbors(result.node_undersurface, &map));
+ n.getNeighbors(result.node_undersurface, &map));
f32 d = 0.002 * BS;
for (std::vector<aabb3f>::const_iterator i = boxes.begin();
- i != boxes.end(); ++i) {
+ i != boxes.end(); ++i) {
aabb3f box = *i;
box.MinEdge -= v3f(d, d, d);
box.MaxEdge += v3f(d, d, d);
selectionboxes->push_back(box);
}
- hud->setSelectionPos(
- intToFloat(result.node_undersurface, BS), camera_offset);
- hud->setSelectedFaceNormal(v3f(result.intersection_normal.X,
- result.intersection_normal.Y,
- result.intersection_normal.Z));
+ hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
+ camera_offset);
+ hud->setSelectedFaceNormal(v3f(
+ result.intersection_normal.X,
+ result.intersection_normal.Y,
+ result.intersection_normal.Z));
}
// Update selection mesh light level and vertex colors
@@ -2490,15 +2515,13 @@ PointedThing Game::updatePointedThing(const core::line3d<f32> &shootline,
// Modify final color a bit with time
u32 timer = porting::getTimeMs() % 5000;
- float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
+ float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
float sin_r = 0.08f * std::sin(timerf);
float sin_g = 0.08f * std::sin(timerf + irr::core::PI * 0.5f);
float sin_b = 0.08f * std::sin(timerf + irr::core::PI);
c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
- c.setGreen(core::clamp(
- core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
- c.setBlue(core::clamp(
- core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
+ c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
+ c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
// Set mesh final color
hud->setSelectionMeshColor(c);
@@ -2514,8 +2537,9 @@ void Game::handlePointingAtNothing(const ItemStack &playerItem)
client->interact(INTERACT_ACTIVATE, fauxPointed);
}
+
void Game::handlePointingAtNode(const PointedThing &pointed,
- const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
+ const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
{
v3s16 nodepos = pointed.node_undersurface;
v3s16 neighbourpos = pointed.node_abovesurface;
@@ -2526,10 +2550,10 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
ClientMap &map = client->getEnv().getClientMap();
- if (((runData.nodig_delay_timer <= 0.0 || g_settings->getBool("fastdig")) &&
- (input->getLeftState() || g_settings->getBool("autodig")) &&
- !runData.digging_blocked &&
- client->checkPrivilege("interact"))) {
+ if (((runData.nodig_delay_timer <= 0.0 || g_settings->getBool("fastdig")) && (input->getLeftState() || g_settings->getBool("autodig"))
+ && !runData.digging_blocked
+ && client->checkPrivilege("interact"))
+ ) {
handleDigging(pointed, nodepos, selected_item, hand_item, dtime);
}
@@ -2537,30 +2561,25 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
NodeMetadata *meta = map.getNodeMetadata(nodepos);
if (meta) {
- m_game_ui->setInfoText(unescape_translate(
- utf8_to_wide(meta->getString("infotext"))));
+ m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
+ meta->getString("infotext"))));
} else {
MapNode n = map.getNode(nodepos);
if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
- m_game_ui->setInfoText(
- L"Unknown node: " +
- utf8_to_wide(nodedef_manager->get(n).name));
+ m_game_ui->setInfoText(L"Unknown node: " +
+ utf8_to_wide(nodedef_manager->get(n).name));
}
}
- if ((input->getRightState() || g_settings->getBool("autoplace")) &&
+ if ((input->getRightState() || g_settings->getBool("autoplace")) &&
(input->getRightClicked() ||
- (runData.repeat_rightclick_timer >=
- (g_settings->getBool("fastplace")
- ? 0
- : m_repeat_right_click_time))) &&
+ (runData.repeat_rightclick_timer >= (g_settings->getBool("fastplace") ? 0 : m_repeat_right_click_time))) &&
client->checkPrivilege("interact")) {
runData.repeat_rightclick_timer = 0;
infostream << "Ground right-clicked" << std::endl;
- camera->setDigging(
- 1); // right click animation (always shown for feedback)
+ camera->setDigging(1); // right click animation (always shown for feedback)
soundmaker->m_player_rightpunch_sound = SimpleSoundSpec();
@@ -2569,8 +2588,8 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
// And also set the sound and send the interact
// But first check for meta formspec and rightclickable
auto &def = selected_item.getDefinition(itemdef_manager);
- bool placed = nodePlacement(
- def, selected_item, nodepos, neighbourpos, pointed, meta);
+ bool placed = nodePlacement(def, selected_item, nodepos, neighbourpos,
+ pointed, meta);
if (placed && client->modsLoaded())
client->getScript()->on_placenode(pointed, def);
@@ -2578,9 +2597,8 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
}
bool Game::nodePlacement(const ItemDefinition &selected_def,
- const ItemStack &selected_item, const v3s16 &nodepos,
- const v3s16 &neighbourpos, const PointedThing &pointed,
- const NodeMetadata *meta)
+ const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos,
+ const PointedThing &pointed, const NodeMetadata *meta)
{
std::string prediction = selected_def.node_placement_prediction;
const NodeDefManager *nodedef = client->ndef();
@@ -2595,8 +2613,8 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
}
// formspec in meta
- if (meta && !meta->getString("formspec").empty() && !input->isRandom() &&
- !isKeyDown(KeyType::SNEAK)) {
+ if (meta && !meta->getString("formspec").empty() && !input->isRandom()
+ && !isKeyDown(KeyType::SNEAK)) {
// on_rightclick callbacks are called anyway
if (nodedef_manager->get(map.getNode(nodepos)).rightclickable)
client->interact(INTERACT_PLACE, pointed);
@@ -2607,12 +2625,12 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
inventoryloc.setNodeMeta(nodepos);
NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
- &client->getEnv().getClientMap(), nodepos);
+ &client->getEnv().getClientMap(), nodepos);
TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
auto *&formspec = m_game_ui->updateFormspec("");
GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src,
- txt_dst, client->getFormspecPrepend());
+ txt_dst, client->getFormspecPrepend());
formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
return false;
@@ -2620,14 +2638,15 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
// on_rightclick callback
if (prediction.empty() || (nodedef->get(node).rightclickable &&
- !isKeyDown(KeyType::SNEAK))) {
+ !isKeyDown(KeyType::SNEAK))) {
// Report to server
client->interact(INTERACT_PLACE, pointed);
return false;
}
- verbosestream << "Node placement prediction for " << selected_def.name << " is "
- << prediction << std::endl;
+ verbosestream << "Node placement prediction for "
+ << selected_def.name << " is "
+ << prediction << std::endl;
v3s16 p = neighbourpos;
// Place inside node itself if buildable_to
@@ -2651,8 +2670,9 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
if (!found) {
errorstream << "Node placement prediction failed for "
- << selected_def.name << " (places " << prediction
- << ") - Name not known" << std::endl;
+ << selected_def.name << " (places "
+ << prediction
+ << ") - Name not known" << std::endl;
// Handle this as if prediction was empty
// Report to server
client->interact(INTERACT_PLACE, pointed);
@@ -2679,9 +2699,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
if (predicted_f.param_type_2 == CPT2_FACEDIR ||
predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
- v3s16 dir = nodepos -
- floatToInt(client->getEnv().getLocalPlayer()->getPosition(),
- BS);
+ v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS);
if (abs(dir.X) > abs(dir.Z)) {
param2 = dir.X < 0 ? 3 : 1;
@@ -2692,15 +2710,15 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
assert(param2 <= 5);
- // Check attachment if node is in group attached_node
- if (((ItemGroupList)predicted_f.groups)["attached_node"] != 0) {
+ //Check attachment if node is in group attached_node
+ if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
static v3s16 wallmounted_dirs[8] = {
- v3s16(0, 1, 0),
- v3s16(0, -1, 0),
- v3s16(1, 0, 0),
- v3s16(-1, 0, 0),
- v3s16(0, 0, 1),
- v3s16(0, 0, -1),
+ v3s16(0, 1, 0),
+ v3s16(0, -1, 0),
+ v3s16(1, 0, 0),
+ v3s16(-1, 0, 0),
+ v3s16(0, 0, 1),
+ v3s16(0, 0, -1),
};
v3s16 pp;
@@ -2718,11 +2736,11 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
}
// Apply color
- if ((predicted_f.param_type_2 == CPT2_COLOR ||
- predicted_f.param_type_2 == CPT2_COLORED_FACEDIR ||
- predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
- const std::string &indexstr =
- selected_item.metadata.getString("palette_index", 0);
+ if ((predicted_f.param_type_2 == CPT2_COLOR
+ || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
+ || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
+ const std::string &indexstr = selected_item.metadata.getString(
+ "palette_index", 0);
if (!indexstr.empty()) {
s32 index = mystoi(indexstr);
if (predicted_f.param_type_2 == CPT2_COLOR) {
@@ -2747,13 +2765,10 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
// NOTE: This is to be eventually implemented by a mod as client-side Lua
if (!nodedef->get(n).walkable ||
g_settings->getBool("enable_build_where_you_stand") ||
- (client->checkPrivilege("noclip") &&
- g_settings->getBool("noclip")) ||
+ (client->checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
(nodedef->get(n).walkable &&
- neighbourpos != player->getStandingNodePos() +
- v3s16(0, 1, 0) &&
- neighbourpos != player->getStandingNodePos() +
- v3s16(0, 2, 0))) {
+ neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
+ neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
// This triggers the required mesh update too
client->addNode(p, n);
// Report to server
@@ -2762,24 +2777,24 @@ bool Game::nodePlacement(const ItemDefinition &selected_def,
soundmaker->m_player_rightpunch_sound = selected_def.sound_place;
return true;
} else {
- soundmaker->m_player_rightpunch_sound =
- selected_def.sound_place_failed;
+ soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
return false;
}
} catch (InvalidPositionException &e) {
errorstream << "Node placement prediction failed for "
- << selected_def.name << " (places " << prediction
- << ") - Position not loaded" << std::endl;
+ << selected_def.name << " (places "
+ << prediction
+ << ") - Position not loaded" << std::endl;
soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed;
return false;
}
}
-void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &tool_item,
- const v3f &player_position, bool show_debug)
+void Game::handlePointingAtObject(const PointedThing &pointed,
+ const ItemStack &tool_item, const v3f &player_position, bool show_debug)
{
std::wstring infotext = unescape_translate(
- utf8_to_wide(runData.selected_object->infoText()));
+ utf8_to_wide(runData.selected_object->infoText()));
if (show_debug) {
if (!infotext.empty()) {
@@ -2794,8 +2809,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
bool do_punch = false;
bool do_punch_damage = false;
- if (runData.object_hit_delay_timer <= 0.0 ||
- g_settings->getBool("spamclick")) {
+ if (runData.object_hit_delay_timer <= 0.0 || g_settings->getBool("spamclick")) {
do_punch = true;
do_punch_damage = true;
runData.object_hit_delay_timer = object_hit_delay;
@@ -2824,10 +2838,11 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
}
} else if (input->getRightClicked()) {
infostream << "Right-clicked object" << std::endl;
- client->interact(INTERACT_PLACE, pointed); // place
+ client->interact(INTERACT_PLACE, pointed); // place
}
}
+
void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime)
{
@@ -2855,14 +2870,13 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
runData.dig_time_complete = params.time;
if (m_cache_enable_particles) {
- const ContentFeatures &features =
- client->getNodeDefManager()->get(n);
- client->getParticleManager()->addNodeParticle(
- client, player, nodepos, n, features);
+ const ContentFeatures &features = client->getNodeDefManager()->get(n);
+ client->getParticleManager()->addNodeParticle(client,
+ player, nodepos, n, features);
}
}
-
- if (g_settings->getBool("instant_break")) {
+
+ if(g_settings->getBool("instant_break")) {
runData.dig_time_complete = 0;
runData.dig_instantly = true;
}
@@ -2877,8 +2891,9 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
}
if (!runData.dig_instantly) {
- runData.dig_index = (float)crack_animation_length * runData.dig_time /
- runData.dig_time_complete;
+ runData.dig_index = (float)crack_animation_length
+ * runData.dig_time
+ / runData.dig_time_complete;
} else {
// This is for e.g. torches
runData.dig_index = crack_animation_length;
@@ -2902,8 +2917,8 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
// Don't show cracks if not diggable
if (runData.dig_time_complete >= 100000.0) {
} else if (runData.dig_index < crack_animation_length) {
- // TimeTaker timer("client.setTempMod");
- // infostream<<"dig_index="<<dig_index<<std::endl;
+ //TimeTaker timer("client.setTempMod");
+ //infostream<<"dig_index="<<dig_index<<std::endl;
client->setCrack(runData.dig_index, nodepos);
} else {
infostream << "Digging completed" << std::endl;
@@ -2928,8 +2943,8 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
bool is_valid_position;
MapNode wasnode = map.getNode(nodepos, &is_valid_position);
if (is_valid_position) {
- if (client->modsLoaded() && client->getScript()->on_dignode(
- nodepos, wasnode)) {
+ if (client->modsLoaded() &&
+ client->getScript()->on_dignode(nodepos, wasnode)) {
return;
}
@@ -2938,8 +2953,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
client->removeNode(nodepos);
} else if (!f.node_dig_prediction.empty()) {
content_t id;
- bool found = client->ndef()->getId(
- f.node_dig_prediction, id);
+ bool found = client->ndef()->getId(f.node_dig_prediction, id);
if (found)
client->addNode(nodepos, id, true);
}
@@ -2950,11 +2964,12 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
if (m_cache_enable_particles) {
const ContentFeatures &features =
- client->getNodeDefManager()->get(wasnode);
- client->getParticleManager()->addDiggingParticles(
- client, player, nodepos, wasnode, features);
+ client->getNodeDefManager()->get(wasnode);
+ client->getParticleManager()->addDiggingParticles(client,
+ player, nodepos, wasnode, features);
}
+
// Send event to trigger sound
client->getEventManager()->put(new NodeDugEvent(nodepos, wasnode));
}
@@ -2966,9 +2981,10 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
client->setCrack(-1, nodepos);
}
- camera->setDigging(0); // left click animation
+ camera->setDigging(0); // left click animation
}
+
void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
const CameraOrientation &cam)
{
@@ -2998,13 +3014,10 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
sunlight_seen = true;
} else {
float old_brightness = sky->getBrightness();
- direct_brightness =
- client->getEnv().getClientMap().getBackgroundBrightness(
- MYMIN(runData.fog_range * 1.2, 60 * BS),
- daynight_ratio,
- (int)(old_brightness * 255.5),
- &sunlight_seen) /
- 255.0;
+ direct_brightness = client->getEnv().getClientMap()
+ .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
+ daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
+ / 255.0;
}
float time_of_day_smooth = runData.time_of_day_smooth;
@@ -3019,16 +3032,17 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
time_of_day_smooth = time_of_day;
if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
- time_of_day_smooth = time_of_day_smooth * (1.0 - todsm) +
- (time_of_day + 1.0) * todsm;
+ time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
+ + (time_of_day + 1.0) * todsm;
else
- time_of_day_smooth =
- time_of_day_smooth * (1.0 - todsm) + time_of_day * todsm;
+ time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
+ + time_of_day * todsm;
runData.time_of_day_smooth = time_of_day_smooth;
- sky->update(time_of_day_smooth, time_brightness, direct_brightness, sunlight_seen,
- camera->getCameraMode(), player->getYaw(), player->getPitch());
+ sky->update(time_of_day_smooth, time_brightness, direct_brightness,
+ sunlight_seen, camera->getCameraMode(), player->getYaw(),
+ player->getPitch());
/*
Update clouds
@@ -3039,26 +3053,20 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
clouds->step(dtime);
// camera->getPosition is not enough for 3rd person views
v3f camera_node_position = camera->getCameraNode()->getPosition();
- v3s16 camera_offset = camera->getOffset();
- camera_node_position.X =
- camera_node_position.X + camera_offset.X * BS;
- camera_node_position.Y =
- camera_node_position.Y + camera_offset.Y * BS;
- camera_node_position.Z =
- camera_node_position.Z + camera_offset.Z * BS;
- clouds->update(camera_node_position, sky->getCloudColor());
+ v3s16 camera_offset = camera->getOffset();
+ camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
+ camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
+ camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
+ clouds->update(camera_node_position,
+ sky->getCloudColor());
if (clouds->isCameraInsideCloud() && m_cache_enable_fog) {
// if inside clouds, and fog enabled, use that as sky
// color(s)
- video::SColor clouds_dark =
- clouds->getColor().getInterpolated(
- video::SColor(255, 0, 0,
- 0),
- 0.9);
+ video::SColor clouds_dark = clouds->getColor()
+ .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
sky->overrideColors(clouds_dark, clouds->getColor());
sky->setInClouds(true);
- runData.fog_range = std::fmin(
- runData.fog_range * 0.5f, 32.0f * BS);
+ runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
// do not draw clouds after all
clouds->setVisible(false);
}
@@ -3077,17 +3085,24 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
*/
if (m_cache_enable_fog) {
- driver->setFog(sky->getBgColor(), video::EFT_FOG_LINEAR,
+ driver->setFog(
+ sky->getBgColor(),
+ video::EFT_FOG_LINEAR,
runData.fog_range * m_cache_fog_start,
- runData.fog_range * 1.0, 0.01,
+ runData.fog_range * 1.0,
+ 0.01,
false, // pixel fog
- true // range fog
+ true // range fog
);
} else {
- driver->setFog(sky->getBgColor(), video::EFT_FOG_LINEAR, 100000 * BS,
- 110000 * BS, 0.01f,
+ driver->setFog(
+ sky->getBgColor(),
+ video::EFT_FOG_LINEAR,
+ 100000 * BS,
+ 110000 * BS,
+ 0.01f,
false, // pixel fog
- false // range fog
+ false // range fog
);
}
@@ -3120,17 +3135,15 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
runData.update_draw_list_timer += dtime;
v3f camera_direction = camera->getDirection();
- if (runData.update_draw_list_timer >= 0.2 ||
- runData.update_draw_list_last_cam_dir.getDistanceFrom(
- camera_direction) > 0.2 ||
- m_camera_offset_changed) {
+ if (runData.update_draw_list_timer >= 0.2
+ || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
+ || m_camera_offset_changed) {
runData.update_draw_list_timer = 0;
client->getEnv().getClientMap().updateDrawList();
runData.update_draw_list_last_cam_dir = camera_direction;
}
- m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old,
- gui_chat_console, dtime);
+ m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, gui_chat_console, dtime);
/*
make sure menu is on top
@@ -3149,9 +3162,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
auto &loc = formspec->getFormspecLocation();
if (loc.type == InventoryLocation::NODEMETA) {
- NodeMetadata *meta =
- client->getEnv().getClientMap().getNodeMetadata(
- loc.p);
+ NodeMetadata *meta = client->getEnv().getClientMap().getNodeMetadata(loc.p);
if (!meta || meta->getString("formspec").empty()) {
formspec->quitMenu();
break;
@@ -3171,10 +3182,11 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
driver->beginScene(true, true, skycolor);
bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
- (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
- (camera->getCameraMode() == CAMERA_MODE_FIRST));
- bool draw_crosshair = ((player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
- (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
+ (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
+ (camera->getCameraMode() == CAMERA_MODE_FIRST));
+ bool draw_crosshair = (
+ (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
+ (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
#ifdef HAVE_TOUCHSCREENGUI
try {
draw_crosshair = !g_settings->getBool("touchtarget");
@@ -3182,9 +3194,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
}
#endif
RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
- m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair,
- g_settings->getBool("enable_tracers"),
- g_settings->getBool("enable_esp"));
+ m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair, g_settings->getBool("enable_tracers"), g_settings->getBool("enable_esp"));
/*
Profiler graph
@@ -3196,7 +3206,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
Cheat menu
*/
- if (!gui_chat_console->isOpen()) {
+ if (! gui_chat_console->isOpen()) {
if (m_game_ui->m_flags.show_cheat_menu)
m_cheat_menu->draw(driver, m_game_ui->m_flags.show_debug);
if (g_settings->getBool("cheat_hud"))
@@ -3207,10 +3217,8 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
*/
if (runData.damage_flash > 0.0f) {
video::SColor color(runData.damage_flash, 180, 0, 0);
- if (!g_settings->getBool("no_hurt_cam"))
- driver->draw2DRectangle(color,
- core::rect<s32>(0, 0, screensize.X, screensize.Y),
- NULL);
+ if (! g_settings->getBool("no_hurt_cam"))
+ driver->draw2DRectangle(color, core::rect<s32>(0, 0, screensize.X, screensize.Y), NULL);
runData.damage_flash -= 384.0f * dtime;
}
@@ -3236,7 +3244,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
/*
End scene
*/
-
+
driver->endScene();
stats->drawtime = tt_draw.stop(true);
@@ -3252,6 +3260,8 @@ inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
graph->put(values);
}
+
+
/****************************************************************************
Misc
****************************************************************************/
@@ -3265,15 +3275,14 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
u32 time = device->getTimer()->getTime();
u32 last_time = fps_timings->last_time;
- if (time > last_time) // Make sure time hasn't overflowed
+ if (time > last_time) // Make sure time hasn't overflowed
fps_timings->busy_time = time - last_time;
else
fps_timings->busy_time = 0;
- u32 frametime_min =
- 1000 /
- (g_menumgr.pausesGame() ? g_settings->getFloat("pause_fps_max")
- : g_settings->getFloat("fps_max"));
+ u32 frametime_min = 1000 / (g_menumgr.pausesGame()
+ ? g_settings->getFloat("pause_fps_max")
+ : g_settings->getFloat("fps_max"));
if (fps_timings->busy_time < frametime_min) {
fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
@@ -3291,7 +3300,7 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
device->getTimer()->tick(); // Update device timer
time = device->getTimer()->getTime();
- if (time > last_time) // Make sure last_time hasn't overflowed
+ if (time > last_time) // Make sure last_time hasn't overflowed
*dtime = (time - last_time) / 1000.0;
else
*dtime = 0;
@@ -3302,8 +3311,8 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
{
const wchar_t *wmsg = wgettext(msg);
- RenderingEngine::draw_load_screen(
- wmsg, guienv, texture_src, dtime, percent, draw_clouds);
+ RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
+ draw_clouds);
delete[] wmsg;
}
@@ -3314,12 +3323,12 @@ void Game::settingChangedCallback(const std::string &setting_name, void *data)
void Game::updateAllMapBlocksCallback(const std::string &setting_name, void *data)
{
- ((Game *)data)->client->updateAllMapBlocks();
+ ((Game *) data)->client->updateAllMapBlocks();
}
void Game::freecamChangedCallback(const std::string &setting_name, void *data)
{
- Game *game = (Game *)data;
+ Game *game = (Game *) data;
LocalPlayer *player = game->client->getEnv().getLocalPlayer();
if (g_settings->getBool("freecam")) {
game->camera->setCameraMode(CAMERA_MODE_FIRST);
@@ -3332,25 +3341,23 @@ void Game::freecamChangedCallback(const std::string &setting_name, void *data)
void Game::readSettings()
{
- m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
- m_cache_enable_clouds = g_settings->getBool("enable_clouds");
- m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
- m_cache_enable_particles = g_settings->getBool("enable_particles");
- m_cache_enable_fog = g_settings->getBool("enable_fog");
- m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
- m_cache_joystick_frustum_sensitivity =
- g_settings->getFloat("joystick_frustum_sensitivity");
- m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
+ m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
+ m_cache_enable_clouds = g_settings->getBool("enable_clouds");
+ m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
+ m_cache_enable_particles = g_settings->getBool("enable_particles");
+ m_cache_enable_fog = g_settings->getBool("enable_fog");
+ m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
+ m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
+ m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
- m_cache_enable_noclip = g_settings->getBool("noclip");
- m_cache_enable_free_move = g_settings->getBool("free_move");
+ m_cache_enable_noclip = g_settings->getBool("noclip");
+ m_cache_enable_free_move = g_settings->getBool("free_move");
- m_cache_fog_start = g_settings->getFloat("fog_start");
+ m_cache_fog_start = g_settings->getFloat("fog_start");
m_cache_cam_smoothing = 0;
if (g_settings->getBool("cinematic"))
- m_cache_cam_smoothing =
- 1 - g_settings->getFloat("cinematic_camera_smoothing");
+ m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
else
m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
@@ -3372,40 +3379,41 @@ void Game::extendedResourceCleanup()
// Extended resource accounting
infostream << "Irrlicht resources after cleanup:" << std::endl;
infostream << "\tRemaining meshes : "
- << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
- infostream << "\tRemaining textures : " << driver->getTextureCount() << std::endl;
+ << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
+ infostream << "\tRemaining textures : "
+ << driver->getTextureCount() << std::endl;
for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
irr::video::ITexture *texture = driver->getTextureByIndex(i);
infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
- << std::endl;
+ << std::endl;
}
clearTextureNameCache();
- infostream << "\tRemaining materials: " << driver->getMaterialRendererCount()
- << " (note: irrlicht doesn't support removing renderers)" << std::endl;
+ infostream << "\tRemaining materials: "
+ << driver-> getMaterialRendererCount()
+ << " (note: irrlicht doesn't support removing renderers)" << std::endl;
}
void Game::showDeathFormspec()
{
- static std::string formspec_str = std::string("formspec_version[1]") +
- SIZE_TAG "bgcolor[#320000b4;true]"
- "label[4.85,1.35;" +
- gettext("You died") +
- "]"
- "button_exit[4,3;3,0.5;btn_respawn;" +
- gettext("Respawn") + "]";
+ static std::string formspec_str =
+ std::string("formspec_version[1]") +
+ SIZE_TAG
+ "bgcolor[#320000b4;true]"
+ "label[4.85,1.35;" + gettext("You died") + "]"
+ "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
+ ;
/* Create menu */
/* Note: FormspecFormSource and LocalFormspecHandler *
* are deleted by guiFormSpecMenu */
FormspecFormSource *fs_src = new FormspecFormSource(formspec_str);
- LocalFormspecHandler *txt_dst =
- new LocalFormspecHandler("MT_DEATH_SCREEN", client);
+ LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
auto *&formspec = m_game_ui->getFormspecGUI();
- GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, txt_dst,
- client->getFormspecPrepend());
+ GUIFormSpecMenu::create(formspec, client, &input->joystick,
+ fs_src, txt_dst, client->getFormspecPrepend());
formspec->setFocus("btn_respawn");
}
@@ -3413,53 +3421,59 @@ void Game::showDeathFormspec()
void Game::showPauseMenu()
{
#ifdef __ANDROID__
- static const std::string control_text =
- strgettext("Default Controls:\n"
- "No menu visible:\n"
- "- single tap: button activate\n"
- "- double tap: place/use\n"
- "- slide finger: look around\n"
- "Menu/Inventory visible:\n"
- "- double tap (outside):\n"
- " -->close\n"
- "- touch stack, touch slot:\n"
- " --> move stack\n"
- "- touch&drag, tap 2nd finger\n"
- " --> place single item to slot\n");
+ static const std::string control_text = strgettext("Default Controls:\n"
+ "No menu visible:\n"
+ "- single tap: button activate\n"
+ "- double tap: place/use\n"
+ "- slide finger: look around\n"
+ "Menu/Inventory visible:\n"
+ "- double tap (outside):\n"
+ " -->close\n"
+ "- touch stack, touch slot:\n"
+ " --> move stack\n"
+ "- touch&drag, tap 2nd finger\n"
+ " --> place single item to slot\n"
+ );
#else
- static const std::string control_text_template =
- strgettext("Controls:\n"
- "- %s: move forwards\n"
- "- %s: move backwards\n"
- "- %s: move left\n"
- "- %s: move right\n"
- "- %s: jump/climb\n"
- "- %s: sneak/go down\n"
- "- %s: drop item\n"
- "- %s: inventory\n"
- "- %s: enderchest\n"
- "- Mouse: turn/look\n"
- "- Mouse left: dig/punch\n"
- "- Mouse right: place/use\n"
- "- Mouse wheel: select item\n"
- "- %s: chat\n"
- "- %s: Killaura\n"
- "- %s: Freecam\n"
- "- %s: Scaffold\n"
- "- %s: NextItem\n");
-
- char control_text_buf[600];
-
- porting::mt_snprintf(control_text_buf, sizeof(control_text_buf),
- control_text_template.c_str(), GET_KEY_NAME(keymap_forward),
- GET_KEY_NAME(keymap_backward), GET_KEY_NAME(keymap_left),
- GET_KEY_NAME(keymap_right), GET_KEY_NAME(keymap_jump),
- GET_KEY_NAME(keymap_sneak), GET_KEY_NAME(keymap_drop),
- GET_KEY_NAME(keymap_inventory), GET_KEY_NAME(keymap_enderchest),
- GET_KEY_NAME(keymap_chat), GET_KEY_NAME(keymap_toggle_killaura),
+ static const std::string control_text_template = strgettext("Controls:\n"
+ "- %s: move forwards\n"
+ "- %s: move backwards\n"
+ "- %s: move left\n"
+ "- %s: move right\n"
+ "- %s: jump/climb\n"
+ "- %s: sneak/go down\n"
+ "- %s: drop item\n"
+ "- %s: inventory\n"
+ "- %s: enderchest\n"
+ "- Mouse: turn/look\n"
+ "- Mouse left: dig/punch\n"
+ "- Mouse right: place/use\n"
+ "- Mouse wheel: select item\n"
+ "- %s: chat\n"
+ "- %s: Killaura\n"
+ "- %s: Freecam\n"
+ "- %s: Scaffold\n"
+ "- %s: NextItem\n"
+ );
+
+ char control_text_buf[600];
+
+ porting::mt_snprintf(control_text_buf, sizeof(control_text_buf), control_text_template.c_str(),
+ GET_KEY_NAME(keymap_forward),
+ GET_KEY_NAME(keymap_backward),
+ GET_KEY_NAME(keymap_left),
+ GET_KEY_NAME(keymap_right),
+ GET_KEY_NAME(keymap_jump),
+ GET_KEY_NAME(keymap_sneak),
+ GET_KEY_NAME(keymap_drop),
+ GET_KEY_NAME(keymap_inventory),
+ GET_KEY_NAME(keymap_enderchest),
+ GET_KEY_NAME(keymap_chat),
+ GET_KEY_NAME(keymap_toggle_killaura),
GET_KEY_NAME(keymap_toggle_freecam),
GET_KEY_NAME(keymap_toggle_scaffold),
- GET_KEY_NAME(keymap_toggle_next_item));
+ GET_KEY_NAME(keymap_toggle_next_item)
+ );
std::string control_text = std::string(control_text_buf);
str_formspec_escape(control_text);
@@ -3468,12 +3482,13 @@ void Game::showPauseMenu()
float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
std::ostringstream os;
- os << "formspec_version[1]" << SIZE_TAG << "button_exit[4," << (ypos++)
- << ";3,0.5;btn_continue;" << strgettext("Continue") << "]";
+ os << "formspec_version[1]" << SIZE_TAG
+ << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
+ << strgettext("Continue") << "]";
if (!simple_singleplayer_mode) {
os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
- << strgettext("Change Password") << "]";
+ << strgettext("Change Password") << "]";
} else {
os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
}
@@ -3482,27 +3497,27 @@ void Game::showPauseMenu()
#if USE_SOUND
if (g_settings->getBool("enable_sound")) {
os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
- << strgettext("Sound Volume") << "]";
+ << strgettext("Sound Volume") << "]";
}
#endif
- os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
- << strgettext("Change Keys") << "]";
+ os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
+ << strgettext("Change Keys") << "]";
#endif
- os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
- << strgettext("Exit to Menu") << "]";
- os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
- << strgettext("Exit to OS") << "]"
- << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
- << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
- << "\n"
- << strgettext("Game info:") << "\n";
+ os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
+ << strgettext("Exit to Menu") << "]";
+ os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
+ << strgettext("Exit to OS") << "]"
+ << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
+ << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
+ << "\n"
+ << strgettext("Game info:") << "\n";
const std::string &address = client->getAddressName();
static const std::string mode = strgettext("- Mode: ");
if (!simple_singleplayer_mode) {
Address serverAddress = client->getServerAddress();
if (!address.empty()) {
os << mode << strgettext("Remote server") << "\n"
- << strgettext("- Address: ") << address;
+ << strgettext("- Address: ") << address;
} else {
os << mode << strgettext("Hosting server");
}
@@ -3513,24 +3528,21 @@ void Game::showPauseMenu()
if (simple_singleplayer_mode || address.empty()) {
static const std::string on = strgettext("On");
static const std::string off = strgettext("Off");
- const std::string &damage =
- g_settings->getBool("enable_damage") ? on : off;
- const std::string &creative =
- g_settings->getBool("creative_mode") ? on : off;
- const std::string &announced =
- g_settings->getBool("server_announce") ? on : off;
+ const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
+ const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
+ const std::string &announced = g_settings->getBool("server_announce") ? on : off;
os << strgettext("- Damage: ") << damage << "\n"
- << strgettext("- Creative Mode: ") << creative << "\n";
+ << strgettext("- Creative Mode: ") << creative << "\n";
if (!simple_singleplayer_mode) {
- const std::string &pvp =
- g_settings->getBool("enable_pvp") ? on : off;
+ const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
//~ PvP = Player versus Player
os << strgettext("- PvP: ") << pvp << "\n"
- << strgettext("- Public: ") << announced << "\n";
+ << strgettext("- Public: ") << announced << "\n";
std::string server_name = g_settings->get("server_name");
str_formspec_escape(server_name);
if (announced == on && !server_name.empty())
os << strgettext("- Server Name: ") << server_name;
+
}
}
os << ";]";
@@ -3542,8 +3554,8 @@ void Game::showPauseMenu()
LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
auto *&formspec = m_game_ui->getFormspecGUI();
- GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, txt_dst,
- client->getFormspecPrepend());
+ GUIFormSpecMenu::create(formspec, client, &input->joystick,
+ fs_src, txt_dst, client->getFormspecPrepend());
formspec->setFocus("btn_continue");
formspec->doPause = true;
}
@@ -3556,12 +3568,15 @@ void Game::showPauseMenu()
Game *g_game;
-void the_game(bool *kill, InputHandler *input, const GameStartData &start_data,
- std::string &error_message, ChatBackend &chat_backend,
+void the_game(bool *kill,
+ InputHandler *input,
+ const GameStartData &start_data,
+ std::string &error_message,
+ ChatBackend &chat_backend,
bool *reconnect_requested) // Used for local game
{
Game game;
-
+
g_game = &game;
/* Make a copy of the server address because if a local singleplayer server
@@ -3572,14 +3587,13 @@ void the_game(bool *kill, InputHandler *input, const GameStartData &start_data,
try {
if (game.startup(kill, input, start_data, error_message,
- reconnect_requested, &chat_backend)) {
+ reconnect_requested, &chat_backend)) {
game.run();
}
} catch (SerializationError &e) {
- error_message = std::string("A serialization error occurred:\n") +
- e.what() +
- "\n\nThe server is probably "
+ error_message = std::string("A serialization error occurred:\n")
+ + e.what() + "\n\nThe server is probably "
" running a different version of " PROJECT_NAME_C ".";
errorstream << error_message << std::endl;
} catch (ServerError &e) {
diff --git a/src/client/game.h b/src/client/game.h
index 70286ba85..51accc679 100644
--- a/src/client/game.h
+++ b/src/client/game.h
@@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
//#include "client/gameui.h"
#include "client/inputhandler.h"
#include "client/sound.h"
-#include "client/tile.h" // For TextureSource
+#include "client/tile.h" // For TextureSource
#include "client/keys.h"
#include "client/joystick_controller.h"
#include "clientmap.h"
@@ -52,7 +52,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gui/profilergraph.h"
#include "mapblock.h"
#include "minimap.h"
-#include "nodedef.h" // Needed for determining pointing to nodes
+#include "nodedef.h" // Needed for determining pointing to nodes
#include "nodemetadata.h"
#include "particles.h"
#include "porting.h"
@@ -75,26 +75,23 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <string>
class InputHandler;
-class ChatBackend; /* to avoid having to include chat.h */
+class ChatBackend; /* to avoid having to include chat.h */
struct SubgameSpec;
struct GameStartData;
-struct Jitter
-{
+struct Jitter {
f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
};
-struct RunStats
-{
+struct RunStats {
u32 drawtime;
Jitter dtime_jitter, busy_time_jitter;
};
-struct CameraOrientation
-{
- f32 camera_yaw; // "right/left"
- f32 camera_pitch; // "up/down"
+struct CameraOrientation {
+ f32 camera_yaw; // "right/left"
+ f32 camera_pitch; // "up/down"
};
/*
@@ -149,10 +146,13 @@ struct TextDestPlayerInventory : public TextDest
struct LocalFormspecHandler : public TextDest
{
- LocalFormspecHandler(const std::string &formname) { m_formname = formname; }
+ LocalFormspecHandler(const std::string &formname)
+ {
+ m_formname = formname;
+ }
- LocalFormspecHandler(const std::string &formname, Client *client) :
- m_client(client)
+ LocalFormspecHandler(const std::string &formname, Client *client):
+ m_client(client)
{
m_formname = formname;
}
@@ -212,10 +212,14 @@ struct LocalFormspecHandler : public TextDest
/* Form update callback */
-class NodeMetadataFormSource : public IFormSource
+class NodeMetadataFormSource: public IFormSource
{
public:
- NodeMetadataFormSource(ClientMap *map, v3s16 p) : m_map(map), m_p(p) {}
+ NodeMetadataFormSource(ClientMap *map, v3s16 p):
+ m_map(map),
+ m_p(p)
+ {
+ }
const std::string &getForm() const
{
static const std::string empty_string = "";
@@ -241,10 +245,13 @@ public:
v3s16 m_p;
};
-class PlayerInventoryFormSource : public IFormSource
+class PlayerInventoryFormSource: public IFormSource
{
public:
- PlayerInventoryFormSource(Client *client) : m_client(client) {}
+ PlayerInventoryFormSource(Client *client):
+ m_client(client)
+ {
+ }
const std::string &getForm() const
{
@@ -255,21 +262,26 @@ public:
Client *m_client;
};
-class NodeDugEvent : public MtEvent
+class NodeDugEvent: public MtEvent
{
public:
v3s16 p;
MapNode n;
- NodeDugEvent(v3s16 p, MapNode n) : p(p), n(n) {}
- MtEvent::Type getType() const { return MtEvent::NODE_DUG; }
+ NodeDugEvent(v3s16 p, MapNode n):
+ p(p),
+ n(n)
+ {}
+ MtEvent::Type getType() const
+ {
+ return MtEvent::NODE_DUG;
+ }
};
class SoundMaker
{
ISoundManager *m_sound;
const NodeDefManager *m_ndef;
-
public:
bool makes_footstep_sound;
float m_player_step_timer;
@@ -279,9 +291,12 @@ public:
SimpleSoundSpec m_player_leftpunch_sound;
SimpleSoundSpec m_player_rightpunch_sound;
- SoundMaker(ISoundManager *sound, const NodeDefManager *ndef) :
- m_sound(sound), m_ndef(ndef), makes_footstep_sound(true),
- m_player_step_timer(0), m_player_jump_timer(0.0f)
+ SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
+ m_sound(sound),
+ m_ndef(ndef),
+ makes_footstep_sound(true),
+ m_player_step_timer(0),
+ m_player_jump_timer(0.0f)
{
}
@@ -348,22 +363,19 @@ public:
static void playerFallingDamage(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
- sm->m_sound->playSound(
- SimpleSoundSpec("player_falling_damage", 0.5), false);
+ sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
}
void registerReceiver(MtEventManager *mgr)
{
mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
- mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround,
- this);
+ mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
- mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage,
- this);
+ mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
}
void step(float dtime)
@@ -374,40 +386,30 @@ public:
};
// Locally stored sounds don't need to be preloaded because of this
-class GameOnDemandSoundFetcher : public OnDemandSoundFetcher
+class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
{
std::set<std::string> m_fetched;
-
private:
- void paths_insert(std::set<std::string> &dst_paths, const std::string &base,
- const std::string &name)
+ void paths_insert(std::set<std::string> &dst_paths,
+ const std::string &base,
+ const std::string &name)
{
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".0.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".1.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".2.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".3.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".4.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".5.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".6.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".7.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".8.ogg");
- dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name +
- ".9.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
+ dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
}
-
public:
- void fetchSounds(const std::string &name, std::set<std::string> &dst_paths,
- std::set<std::string> &dst_datas)
+ void fetchSounds(const std::string &name,
+ std::set<std::string> &dst_paths,
+ std::set<std::string> &dst_datas)
{
if (m_fetched.count(name))
return;
@@ -415,10 +417,11 @@ public:
m_fetched.insert(name);
paths_insert(dst_paths, porting::path_share, name);
- paths_insert(dst_paths, porting::path_user, name);
+ paths_insert(dst_paths, porting::path_user, name);
}
};
+
// before 1.8 there isn't a "integer interface", only float
#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
typedef f32 SamplerLayer_t;
@@ -426,6 +429,7 @@ typedef f32 SamplerLayer_t;
typedef s32 SamplerLayer_t;
#endif
+
class GameGlobalShaderConstantSetter : public IShaderConstantSetter
{
Sky *m_sky;
@@ -456,25 +460,30 @@ public:
static void settingsCallback(const std::string &name, void *userdata)
{
- reinterpret_cast<GameGlobalShaderConstantSetter *>(userdata)
- ->onSettingsChange(name);
+ reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
}
void setSky(Sky *sky) { m_sky = sky; }
- GameGlobalShaderConstantSetter(
- Sky *sky, bool *force_fog_off, f32 *fog_range, Client *client) :
- m_sky(sky),
- m_force_fog_off(force_fog_off), m_fog_range(fog_range),
- m_sky_bg_color("skyBgColor"), m_fog_distance("fogDistance"),
- m_animation_timer_vertex("animationTimer"),
- m_animation_timer_pixel("animationTimer"),
- m_day_light("dayLight"), m_eye_position_pixel("eyePosition"),
- m_eye_position_vertex("eyePosition"), m_minimap_yaw("yawVec"),
- m_camera_offset_pixel("cameraOffset"),
- m_camera_offset_vertex("cameraOffset"),
- m_base_texture("baseTexture"), m_normal_texture("normalTexture"),
- m_texture_flags("textureFlags"), m_client(client)
+ GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
+ f32 *fog_range, Client *client) :
+ m_sky(sky),
+ m_force_fog_off(force_fog_off),
+ m_fog_range(fog_range),
+ m_sky_bg_color("skyBgColor"),
+ m_fog_distance("fogDistance"),
+ m_animation_timer_vertex("animationTimer"),
+ m_animation_timer_pixel("animationTimer"),
+ m_day_light("dayLight"),
+ m_eye_position_pixel("eyePosition"),
+ m_eye_position_vertex("eyePosition"),
+ m_minimap_yaw("yawVec"),
+ m_camera_offset_pixel("cameraOffset"),
+ m_camera_offset_vertex("cameraOffset"),
+ m_base_texture("baseTexture"),
+ m_normal_texture("normalTexture"),
+ m_texture_flags("textureFlags"),
+ m_client(client)
{
g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
m_fog_enabled = g_settings->getBool("enable_fog");
@@ -482,12 +491,11 @@ public:
~GameGlobalShaderConstantSetter()
{
- g_settings->deregisterChangedCallback(
- "enable_fog", settingsCallback, this);
+ g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
}
- virtual void onSetConstants(
- video::IMaterialRendererServices *services, bool is_highlevel)
+ virtual void onSetConstants(video::IMaterialRendererServices *services,
+ bool is_highlevel)
{
if (!is_highlevel)
return;
@@ -496,10 +504,10 @@ public:
video::SColor bgcolor = m_sky->getBgColor();
video::SColorf bgcolorf(bgcolor);
float bgcolorfa[4] = {
- bgcolorf.r,
- bgcolorf.g,
- bgcolorf.b,
- bgcolorf.a,
+ bgcolorf.r,
+ bgcolorf.g,
+ bgcolorf.b,
+ bgcolorf.a,
};
m_sky_bg_color.set(bgcolorfa, services);
@@ -514,7 +522,10 @@ public:
u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
video::SColorf sunlight;
get_sunlight_color(&sunlight, daynight_ratio);
- float dnc[3] = {sunlight.r, sunlight.g, sunlight.b};
+ float dnc[3] = {
+ sunlight.r,
+ sunlight.g,
+ sunlight.b };
m_day_light.set(dnc, services);
u32 animation_timer = porting::getTimeMs() % 1000000;
@@ -559,13 +570,16 @@ public:
m_camera_offset_pixel.set(camera_offset_array, services);
m_camera_offset_vertex.set(camera_offset_array, services);
- SamplerLayer_t base_tex = 0, normal_tex = 1, flags_tex = 2;
+ SamplerLayer_t base_tex = 0,
+ normal_tex = 1,
+ flags_tex = 2;
m_base_texture.set(&base_tex, services);
m_normal_texture.set(&normal_tex, services);
m_texture_flags.set(&flags_tex, services);
}
};
+
class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
{
Sky *m_sky;
@@ -573,18 +587,16 @@ class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactor
f32 *m_fog_range;
Client *m_client;
std::vector<GameGlobalShaderConstantSetter *> created_nosky;
-
public:
- GameGlobalShaderConstantSetterFactory(
- bool *force_fog_off, f32 *fog_range, Client *client) :
- m_sky(NULL),
- m_force_fog_off(force_fog_off), m_fog_range(fog_range),
- m_client(client)
- {
- }
-
- void setSky(Sky *sky)
- {
+ GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
+ f32 *fog_range, Client *client) :
+ m_sky(NULL),
+ m_force_fog_off(force_fog_off),
+ m_fog_range(fog_range),
+ m_client(client)
+ {}
+
+ void setSky(Sky *sky) {
m_sky = sky;
for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
ggscs->setSky(m_sky);
@@ -592,7 +604,7 @@ public:
created_nosky.clear();
}
- virtual IShaderConstantSetter *create()
+ virtual IShaderConstantSetter* create()
{
GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
m_sky, m_force_fog_off, m_fog_range, m_client);
@@ -614,19 +626,18 @@ public:
const float object_hit_delay = 0.2;
-struct FpsControl
-{
+struct FpsControl {
u32 last_time, busy_time, sleep_time;
};
+
/* The reason the following structs are not anonymous structs within the
* class is that they are not used by the majority of member functions and
* many functions that do require objects of thse types do not modify them
* (so they can be passed as a const qualified parameter)
*/
-struct GameRunData
-{
+struct GameRunData {
u16 dig_index;
u16 new_playeritem;
PointedThing pointed_old;
@@ -662,24 +673,27 @@ struct ClientEventHandler
void (Game::*handler)(ClientEvent *, CameraOrientation *);
};
-class Game
-{
+class Game {
public:
Game();
~Game();
- bool startup(bool *kill, InputHandler *input, const GameStartData &game_params,
- std::string &error_message, bool *reconnect,
+ bool startup(bool *kill,
+ InputHandler *input,
+ const GameStartData &game_params,
+ std::string &error_message,
+ bool *reconnect,
ChatBackend *chat_backend);
+
void run();
void shutdown();
void extendedResourceCleanup();
// Basic initialisation
- bool init(const std::string &map_dir, const std::string &address, u16 port,
- const SubgameSpec &gamespec);
+ bool init(const std::string &map_dir, const std::string &address,
+ u16 port, const SubgameSpec &gamespec);
bool initSound();
bool createSingleplayerServer(const std::string &map_dir,
const SubgameSpec &gamespec, u16 port);
@@ -689,8 +703,8 @@ public:
bool initGui();
// Client connection
- bool connectToServer(
- const GameStartData &start_data, bool *connect_ok, bool *aborted);
+ bool connectToServer(const GameStartData &start_data,
+ bool *connect_ok, bool *aborted);
bool getServerContent(bool *aborted);
// Main loop
@@ -699,8 +713,7 @@ public:
bool checkConnection();
bool handleCallbacks();
void processQueues();
- void updateProfilers(
- const RunStats &stats, const FpsControl &draw_times, f32 dtime);
+ void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
void updateProfilerGraphs(ProfilerGraph *graph);
@@ -712,7 +725,7 @@ public:
void dropSelectedItem(bool single_item = false);
void openInventory();
void openEnderchest();
- void openConsole(float scale, const wchar_t *line = NULL);
+ void openConsole(float scale, const wchar_t *line=NULL);
void toggleFreeMove();
void toggleFreeMoveAlt();
void togglePitchMove();
@@ -757,19 +770,16 @@ public:
* @param[out] selected_object the selected object or
* NULL if not found
*/
- PointedThing updatePointedThing(const core::line3d<f32> &shootline,
- bool liquids_pointable, bool look_for_object,
- const v3s16 &camera_offset);
+ PointedThing updatePointedThing(
+ const core::line3d<f32> &shootline, bool liquids_pointable,
+ bool look_for_object, const v3s16 &camera_offset);
void handlePointingAtNothing(const ItemStack &playerItem);
void handlePointingAtNode(const PointedThing &pointed,
- const ItemStack &selected_item, const ItemStack &hand_item,
- f32 dtime);
- void handlePointingAtObject(const PointedThing &pointed,
- const ItemStack &playeritem, const v3f &player_position,
- bool show_debug);
+ const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
+ void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
+ const v3f &player_position, bool show_debug);
void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
- const ItemStack &selected_item, const ItemStack &hand_item,
- f32 dtime);
+ const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
const CameraOrientation &cam);
@@ -781,19 +791,23 @@ public:
static void freecamChangedCallback(const std::string &setting_name, void *data);
static void settingChangedCallback(const std::string &setting_name, void *data);
- static void updateAllMapBlocksCallback(
- const std::string &setting_name, void *data);
+ static void updateAllMapBlocksCallback(const std::string &setting_name, void *data);
void readSettings();
- inline bool isKeyDown(GameKeyType k) { return input->isKeyDown(k); }
- inline bool wasKeyDown(GameKeyType k) { return input->wasKeyDown(k); }
+ inline bool isKeyDown(GameKeyType k)
+ {
+ return input->isKeyDown(k);
+ }
+ inline bool wasKeyDown(GameKeyType k)
+ {
+ return input->wasKeyDown(k);
+ }
#ifdef __ANDROID__
void handleAndroidChatInput();
#endif
- struct Flags
- {
+ struct Flags {
bool force_fog_off = false;
bool disable_camera_update = false;
};
@@ -804,14 +818,12 @@ public:
// ClientEvent handlers
void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
- void handleClientEvent_PlayerForceMove(
- ClientEvent *event, CameraOrientation *cam);
+ void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
- void handleClientEvent_ShowLocalFormSpec(
- ClientEvent *event, CameraOrientation *cam);
- void handleClientEvent_HandleParticleEvent(
- ClientEvent *event, CameraOrientation *cam);
+ void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
+ void handleClientEvent_HandleParticleEvent(ClientEvent *event,
+ CameraOrientation *cam);
void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
@@ -819,16 +831,15 @@ public:
void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam);
- void handleClientEvent_OverrideDayNigthRatio(
- ClientEvent *event, CameraOrientation *cam);
+ void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
+ CameraOrientation *cam);
void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
void updateChat(f32 dtime, const v2u32 &screensize);
- bool nodePlacement(const ItemDefinition &selected_def,
- const ItemStack &selected_item, const v3s16 &nodepos,
- const v3s16 &neighbourpos, const PointedThing &pointed,
- const NodeMetadata *meta);
+ bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
+ const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
+ const NodeMetadata *meta);
static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
InputHandler *input = nullptr;
@@ -847,10 +858,10 @@ public:
ISoundManager *sound = nullptr;
bool sound_is_dummy = false;
SoundMaker *soundmaker = nullptr;
-
+
ChatBackend *chat_backend = nullptr;
LogOutputBuffer m_chat_log_buf;
-
+
EventManager *eventmgr = nullptr;
QuicktuneShortcutter *quicktune = nullptr;
bool registration_confirmation_shown = false;
@@ -860,8 +871,8 @@ public:
CheatMenu *m_cheat_menu = nullptr;
MapDrawControl *draw_control = nullptr;
Camera *camera = nullptr;
- Clouds *clouds = nullptr; // Free using ->Drop()
- Sky *sky = nullptr; // Free using ->Drop()
+ Clouds *clouds = nullptr; // Free using ->Drop()
+ Sky *sky = nullptr; // Free using ->Drop()
Hud *hud = nullptr;
Minimap *mapper = nullptr;
@@ -903,11 +914,11 @@ public:
bool m_cache_enable_fog;
bool m_cache_enable_noclip;
bool m_cache_enable_free_move;
- f32 m_cache_mouse_sensitivity;
- f32 m_cache_joystick_frustum_sensitivity;
- f32 m_repeat_right_click_time;
- f32 m_cache_cam_smoothing;
- f32 m_cache_fog_start;
+ f32 m_cache_mouse_sensitivity;
+ f32 m_cache_joystick_frustum_sensitivity;
+ f32 m_repeat_right_click_time;
+ f32 m_cache_cam_smoothing;
+ f32 m_cache_fog_start;
bool m_invert_mouse = false;
bool m_first_loop_after_window_activation = false;
@@ -915,8 +926,8 @@ public:
bool m_does_lost_focus_pause_game = false;
- CameraOrientation cam_view_target = {0};
- CameraOrientation cam_view = {0};
+ CameraOrientation cam_view_target = { 0 };
+ CameraOrientation cam_view = { 0 };
#ifdef __ANDROID__
bool m_cache_hold_aux1;
@@ -925,6 +936,9 @@ public:
};
extern Game *g_game;
-void the_game(bool *kill, InputHandler *input, const GameStartData &start_data,
- std::string &error_message, ChatBackend &chat_backend,
+void the_game(bool *kill,
+ InputHandler *input,
+ const GameStartData &start_data,
+ std::string &error_message,
+ ChatBackend &chat_backend,
bool *reconnect_requested);
diff --git a/src/client/gameui.cpp b/src/client/gameui.cpp
index b72fcd999..a9057052e 100644
--- a/src/client/gameui.cpp
+++ b/src/client/gameui.cpp
@@ -34,7 +34,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
inline static const char *yawToDirectionString(int yaw)
{
- static const char *direction[4] = {"North +Z", "West -X", "South -Z", "East +X"};
+ static const char *direction[4] =
+ {"North +Z", "West -X", "South -Z", "East +X"};
yaw = wrapDegrees_0_360(yaw);
yaw = (yaw + 45) % 360 / 90;
@@ -45,58 +46,56 @@ inline static const char *yawToDirectionString(int yaw)
GameUI::GameUI()
{
if (guienv && guienv->getSkin())
- m_statustext_initial_color =
- guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
+ m_statustext_initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
else
m_statustext_initial_color = video::SColor(255, 0, 0, 0);
+
}
void GameUI::init()
{
- m_guitext_coords = gui::StaticText::add(
- guienv, L"", core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
-
+ m_guitext_coords = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0), false,
+ false, guiroot);
+
// First line of debug text
m_guitext = gui::StaticText::add(guienv, utf8_to_wide(PROJECT_NAME_C).c_str(),
- core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
+ core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
// Second line of debug text
- m_guitext2 = gui::StaticText::add(
- guienv, L"", core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
+ m_guitext2 = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0), false,
+ false, guiroot);
// At the middle of the screen
// Object infos are shown in this
m_guitext_info = gui::StaticText::add(guienv, L"",
- core::rect<s32>(0, 0, 400,
- g_fontengine->getTextHeight() * 5 + 5) +
- v2s32(100, 200),
- false, true, guiroot);
+ core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5)
+ + v2s32(100, 200), false, true, guiroot);
// Status text (displays info when showing and hiding GUI stuff, etc.)
m_guitext_status = gui::StaticText::add(guienv, L"<Status>",
- core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
+ core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
m_guitext_status->setVisible(false);
// Chat text
m_guitext_chat = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0),
- // false, false); // Disable word wrap as of now
- false, true, guiroot);
+ //false, false); // Disable word wrap as of now
+ false, true, guiroot);
u16 chat_font_size = g_settings->getU16("chat_font_size");
if (chat_font_size != 0) {
- m_guitext_chat->setOverrideFont(
- g_fontengine->getFont(chat_font_size, FM_Unspecified));
+ m_guitext_chat->setOverrideFont(g_fontengine->getFont(
+ chat_font_size, FM_Unspecified));
}
// Profiler text (size is updated when text is updated)
m_guitext_profiler = gui::StaticText::add(guienv, L"<Profiler>",
- core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
+ core::rect<s32>(0, 0, 0, 0), false, false, guiroot);
m_guitext_profiler->setOverrideFont(g_fontengine->getFont(
- g_fontengine->getDefaultFontSize() * 0.9f, FM_Mono));
+ g_fontengine->getDefaultFontSize() * 0.9f, FM_Mono));
m_guitext_profiler->setVisible(false);
}
void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_control,
- const CameraOrientation &cam, const PointedThing &pointed_old,
- const GUIChatConsole *chat_console, float dtime)
+ const CameraOrientation &cam, const PointedThing &pointed_old,
+ const GUIChatConsole *chat_console, float dtime)
{
LocalPlayer *player = client->getEnv().getLocalPlayer();
v3f player_position = player->getPosition();
@@ -106,15 +105,14 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_
if (show_coords) {
std::ostringstream os(std::ios_base::binary);
- os << std::setprecision(1) << std::fixed << (player_position.X / BS)
- << ", " << (player_position.Y / BS) << ", "
- << (player_position.Z / BS);
+ os << std::setprecision(1) << std::fixed
+ << (player_position.X / BS)
+ << ", " << (player_position.Y / BS)
+ << ", " << (player_position.Z / BS);
setStaticText(m_guitext_coords, utf8_to_wide(os.str()).c_str());
- m_guitext_coords->setRelativePosition(core::rect<s32>(5,
- screensize.Y - 5 - g_fontengine->getTextHeight(),
- screensize.X, screensize.Y));
+ m_guitext_coords->setRelativePosition(core::rect<s32>(5, screensize.Y - 5 - g_fontengine->getTextHeight(), screensize.X, screensize.Y));
}
-
+
m_guitext_coords->setVisible(show_coords);
if (m_flags.show_debug) {
@@ -123,17 +121,23 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_
u16 fps = 1.0 / stats.dtime_jitter.avg;
std::ostringstream os(std::ios_base::binary);
- os << std::fixed << PROJECT_NAME_C " " << g_version_hash
- << " | FPS: " << fps << std::setprecision(0)
- << " | drawtime: " << drawtime_avg << "ms" << std::setprecision(1)
- << " | dtime jitter: " << (stats.dtime_jitter.max_fraction * 100.0)
- << "%" << std::setprecision(1) << " | view range: "
- << (draw_control->range_all ? "All" : itos(draw_control->wanted_range))
- << std::setprecision(3) << " | RTT: " << client->getRTT() << "s";
+ os << std::fixed
+ << PROJECT_NAME_C " " << g_version_hash
+ << " | FPS: " << fps
+ << std::setprecision(0)
+ << " | drawtime: " << drawtime_avg << "ms"
+ << std::setprecision(1)
+ << " | dtime jitter: "
+ << (stats.dtime_jitter.max_fraction * 100.0) << "%"
+ << std::setprecision(1)
+ << " | view range: "
+ << (draw_control->range_all ? "All" : itos(draw_control->wanted_range))
+ << std::setprecision(3)
+ << " | RTT: " << client->getRTT() << "s";
setStaticText(m_guitext, utf8_to_wide(os.str()).c_str());
- m_guitext->setRelativePosition(core::rect<s32>(
- 5, 5, screensize.X, 5 + g_fontengine->getTextHeight()));
+ m_guitext->setRelativePosition(core::rect<s32>(5, 5, screensize.X,
+ 5 + g_fontengine->getTextHeight()));
}
// Finally set the guitext visible depending on the flag
@@ -141,31 +145,32 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_
if (m_flags.show_debug) {
std::ostringstream os(std::ios_base::binary);
- os << std::setprecision(1) << std::fixed << "pos: ("
- << (player_position.X / BS) << ", " << (player_position.Y / BS) << ", "
- << (player_position.Z / BS)
- << ") | yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "\xC2\xB0 "
- << yawToDirectionString(cam.camera_yaw)
- << " | pitch: " << (-wrapDegrees_180(cam.camera_pitch)) << "\xC2\xB0"
- << " | seed: " << ((u64)client->getMapSeed());
+ os << std::setprecision(1) << std::fixed
+ << "pos: (" << (player_position.X / BS)
+ << ", " << (player_position.Y / BS)
+ << ", " << (player_position.Z / BS)
+ << ") | yaw: " << (wrapDegrees_0_360(cam.camera_yaw)) << "\xC2\xB0 "
+ << yawToDirectionString(cam.camera_yaw)
+ << " | pitch: " << (-wrapDegrees_180(cam.camera_pitch)) << "\xC2\xB0"
+ << " | seed: " << ((u64)client->getMapSeed());
if (pointed_old.type == POINTEDTHING_NODE) {
ClientMap &map = client->getEnv().getClientMap();
const NodeDefManager *nodedef = client->getNodeDefManager();
MapNode n = map.getNode(pointed_old.node_undersurface);
- if (n.getContent() != CONTENT_IGNORE &&
- nodedef->get(n).name != "unknown") {
+ if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
os << ", pointed: " << nodedef->get(n).name
- << ", param2: " << (u64)n.getParam2();
+ << ", param2: " << (u64) n.getParam2();
}
}
setStaticText(m_guitext2, utf8_to_wide(os.str()).c_str());
m_guitext2->setRelativePosition(core::rect<s32>(5,
- 5 + g_fontengine->getTextHeight(), screensize.X,
- 5 + g_fontengine->getTextHeight() * 2));
+ 5 + g_fontengine->getTextHeight(), screensize.X,
+ 5 + g_fontengine->getTextHeight() * 2
+ ));
}
m_guitext2->setVisible(m_flags.show_debug);
@@ -188,22 +193,19 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_
m_guitext_status->setVisible(!m_statustext.empty());
if (!m_statustext.empty()) {
- s32 status_width = m_guitext_status->getTextWidth();
+ s32 status_width = m_guitext_status->getTextWidth();
s32 status_height = m_guitext_status->getTextHeight();
s32 status_y = screensize.Y - 150;
s32 status_x = (screensize.X - status_width) / 2;
- m_guitext_status->setRelativePosition(
- core::rect<s32>(status_x, status_y - status_height,
- status_x + status_width, status_y));
+ m_guitext_status->setRelativePosition(core::rect<s32>(status_x ,
+ status_y - status_height, status_x + status_width, status_y));
// Fade out
video::SColor final_color = m_statustext_initial_color;
final_color.setAlpha(0);
- video::SColor fade_color =
- m_statustext_initial_color.getInterpolated_quadratic(
- m_statustext_initial_color, final_color,
- m_statustext_time / statustext_time_max);
+ video::SColor fade_color = m_statustext_initial_color.getInterpolated_quadratic(
+ m_statustext_initial_color, final_color, m_statustext_time / statustext_time_max);
m_guitext_status->setOverrideColor(fade_color);
m_guitext_status->enableOverrideColor(true);
}
@@ -233,17 +235,18 @@ void GameUI::setChatText(const EnrichedString &chat_text, u32 recent_chat_count)
{
// Update gui element size and position
-
+
const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
-
+
s32 chat_y = window_size.Y - 150 - m_guitext_chat->getTextHeight();
if (m_flags.show_debug)
chat_y += 2 * g_fontengine->getLineHeight();
- core::rect<s32> chat_size(10, chat_y, window_size.X - 20, 0);
- chat_size.LowerRightCorner.Y = std::min(
- (s32)window_size.Y, m_guitext_chat->getTextHeight() + chat_y);
+ core::rect<s32> chat_size(10, chat_y,
+ window_size.X - 20, 0);
+ chat_size.LowerRightCorner.Y = std::min((s32)window_size.Y,
+ m_guitext_chat->getTextHeight() + chat_y);
m_guitext_chat->setRelativePosition(chat_size);
setStaticText(m_guitext_chat, chat_text);
@@ -255,27 +258,24 @@ void GameUI::updateProfiler()
{
if (m_profiler_current_page != 0) {
std::ostringstream os(std::ios_base::binary);
- os << " Profiler page " << (int)m_profiler_current_page
- << ", elapsed: " << g_profiler->getElapsedMs() << " ms)" << std::endl;
+ os << " Profiler page " << (int)m_profiler_current_page <<
+ ", elapsed: " << g_profiler->getElapsedMs() << " ms)" << std::endl;
- int lines = g_profiler->print(
- os, m_profiler_current_page, m_profiler_max_page);
+ int lines = g_profiler->print(os, m_profiler_current_page, m_profiler_max_page);
++lines;
EnrichedString str(utf8_to_wide(os.str()));
str.setBackground(video::SColor(120, 0, 0, 0));
setStaticText(m_guitext_profiler, str);
- core::dimension2d<u32> size =
- m_guitext_profiler->getOverrideFont()->getDimension(
- str.c_str());
+ core::dimension2d<u32> size = m_guitext_profiler->getOverrideFont()->
+ getDimension(str.c_str());
core::position2di upper_left(6, 50);
core::position2di lower_right = upper_left;
lower_right.X += size.Width + 10;
- lower_right.Y += size.Height;
+ lower_right.Y += size.Height;
- m_guitext_profiler->setRelativePosition(
- core::rect<s32>(upper_left, lower_right));
+ m_guitext_profiler->setRelativePosition(core::rect<s32>(upper_left, lower_right));
}
m_guitext_profiler->setVisible(m_profiler_current_page != 0);
@@ -310,17 +310,16 @@ void GameUI::toggleHud()
void GameUI::toggleProfiler()
{
- m_profiler_current_page =
- (m_profiler_current_page + 1) % (m_profiler_max_page + 1);
+ m_profiler_current_page = (m_profiler_current_page + 1) % (m_profiler_max_page + 1);
// FIXME: This updates the profiler with incomplete values
updateProfiler();
if (m_profiler_current_page != 0) {
wchar_t buf[255];
- const wchar_t *str = wgettext("Profiler shown (page %d of %d)");
- swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, m_profiler_current_page,
- m_profiler_max_page);
+ const wchar_t* str = wgettext("Profiler shown (page %d of %d)");
+ swprintf(buf, sizeof(buf) / sizeof(wchar_t), str,
+ m_profiler_current_page, m_profiler_max_page);
delete[] str;
showStatusText(buf);
} else {
@@ -328,6 +327,7 @@ void GameUI::toggleProfiler()
}
}
+
void GameUI::deleteFormspec()
{
if (m_formspec) {
diff --git a/src/client/gameui.h b/src/client/gameui.h
index 2278ad1d6..8a1b5650d 100644
--- a/src/client/gameui.h
+++ b/src/client/gameui.h
@@ -85,8 +85,7 @@ public:
const bool isChatVisible()
{
- return m_flags.show_chat && m_recent_chat_count != 0 &&
- m_profiler_current_page == 0;
+ return m_flags.show_chat && m_recent_chat_count != 0 && m_profiler_current_page == 0;
}
void setChatText(const EnrichedString &chat_text, u32 recent_chat_count);
@@ -113,7 +112,7 @@ private:
gui::IGUIStaticText *m_guitext = nullptr; // First line of debug text
gui::IGUIStaticText *m_guitext2 = nullptr; // Second line of debug text
gui::IGUIStaticText *m_guitext_coords = nullptr;
-
+
gui::IGUIStaticText *m_guitext_info = nullptr; // At the middle of the screen
std::wstring m_infotext;
diff --git a/src/client/guiscalingfilter.cpp b/src/client/guiscalingfilter.cpp
index 6b426fdf4..4262331bd 100644
--- a/src/client/guiscalingfilter.cpp
+++ b/src/client/guiscalingfilter.cpp
@@ -40,13 +40,12 @@ std::map<io::path, video::ITexture *> g_txrCache;
/* Manually insert an image into the cache, useful to avoid texture-to-image
* conversion whenever we can intercept it.
*/
-void guiScalingCache(
- const io::path &key, video::IVideoDriver *driver, video::IImage *value)
+void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value)
{
if (!g_settings->getBool("gui_scaling_filter"))
return;
- video::IImage *copied = driver->createImage(
- value->getColorFormat(), value->getDimension());
+ video::IImage *copied = driver->createImage(value->getColorFormat(),
+ value->getDimension());
value->copyTo(copied);
g_imgCache[key] = copied;
}
@@ -70,8 +69,9 @@ void guiScalingCacheClear()
* texture is not already cached, attempt to create it. Returns a pre-scaled texture,
* or the original texture if unable to pre-scale it.
*/
-video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITexture *src,
- const core::rect<s32> &srcrect, const core::rect<s32> &destrect)
+video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver,
+ video::ITexture *src, const core::rect<s32> &srcrect,
+ const core::rect<s32> &destrect)
{
if (src == NULL)
return src;
@@ -81,9 +81,12 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
// Calculate scaled texture name.
char rectstr[200];
porting::mt_snprintf(rectstr, sizeof(rectstr), "%d:%d:%d:%d:%d:%d",
- srcrect.UpperLeftCorner.X, srcrect.UpperLeftCorner.Y,
- srcrect.getWidth(), srcrect.getHeight(), destrect.getWidth(),
- destrect.getHeight());
+ srcrect.UpperLeftCorner.X,
+ srcrect.UpperLeftCorner.Y,
+ srcrect.getWidth(),
+ srcrect.getHeight(),
+ destrect.getWidth(),
+ destrect.getHeight());
io::path origname = src->getName().getPath();
io::path scalename = origname + "@guiScalingFilter:" + rectstr;
@@ -94,12 +97,12 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
// Try to find the texture converted to an image in the cache.
// If the image was not found, try to extract it from the texture.
- video::IImage *srcimg = g_imgCache[origname];
+ video::IImage* srcimg = g_imgCache[origname];
if (srcimg == NULL) {
if (!g_settings->getBool("gui_scaling_filter_txr2img"))
return src;
srcimg = driver->createImageFromData(src->getColorFormat(),
- src->getSize(), src->lock(), false);
+ src->getSize(), src->lock(), false);
src->unlock();
g_imgCache[origname] = srcimg;
}
@@ -108,7 +111,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
imageCleanTransparent(srcimg, 0);
video::IImage *destimg = driver->createImage(src->getColorFormat(),
core::dimension2d<u32>((u32)destrect.getWidth(),
- (u32)destrect.getHeight()));
+ (u32)destrect.getHeight()));
imageScaleNNAA(srcimg, srcrect, destimg);
#if ENABLE_GLES
@@ -117,7 +120,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
if (!hasNPotSupport()) {
video::IImage *po2img = driver->createImage(src->getColorFormat(),
core::dimension2d<u32>(npot2((u32)destrect.getWidth()),
- npot2((u32)destrect.getHeight())));
+ npot2((u32)destrect.getHeight())));
po2img->fill(video::SColor(0, 0, 0, 0));
destimg->copyTo(po2img);
destimg->drop();
@@ -136,15 +139,14 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
/* Convenience wrapper for guiScalingResizeCached that accepts parameters that
* are available at GUI imagebutton creation time.
*/
-video::ITexture *guiScalingImageButton(
- video::IVideoDriver *driver, video::ITexture *src, s32 width, s32 height)
+video::ITexture *guiScalingImageButton(video::IVideoDriver *driver,
+ video::ITexture *src, s32 width, s32 height)
{
if (src == NULL)
return src;
return guiScalingResizeCached(driver, src,
- core::rect<s32>(0, 0, src->getSize().Width,
- src->getSize().Height),
- core::rect<s32>(0, 0, width, height));
+ core::rect<s32>(0, 0, src->getSize().Width, src->getSize().Height),
+ core::rect<s32>(0, 0, width, height));
}
/* Replacement for driver->draw2DImage() that uses the high-quality pre-scaled
@@ -161,10 +163,9 @@ void draw2DImageFilterScaled(video::IVideoDriver *driver, video::ITexture *txr,
return;
// Correct source rect based on scaled image.
- const core::rect<s32> mysrcrect =
- (scaled != txr) ? core::rect<s32>(0, 0, destrect.getWidth(),
- destrect.getHeight())
- : srcrect;
+ const core::rect<s32> mysrcrect = (scaled != txr)
+ ? core::rect<s32>(0, 0, destrect.getWidth(), destrect.getHeight())
+ : srcrect;
driver->draw2DImage(scaled, destrect, mysrcrect, cliprect, colors, usealpha);
}
@@ -173,13 +174,11 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture,
const core::rect<s32> &rect, const core::rect<s32> &middle,
const core::rect<s32> *cliprect)
{
- const video::SColor color(255, 255, 255, 255);
- const video::SColor colors[] = {color, color, color, color};
+ const video::SColor color(255,255,255,255);
+ const video::SColor colors[] = {color,color,color,color};
auto originalSize = texture->getOriginalSize();
- core::vector2di lowerRightOffset =
- core::vector2di(originalSize.Width, originalSize.Height) -
- middle.LowerRightCorner;
+ core::vector2di lowerRightOffset = core::vector2di(originalSize.Width, originalSize.Height) - middle.LowerRightCorner;
for (int y = 0; y < 3; ++y) {
for (int x = 0; x < 3; ++x) {
@@ -188,8 +187,7 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture,
switch (x) {
case 0:
- dest.LowerRightCorner.X = rect.UpperLeftCorner.X +
- middle.UpperLeftCorner.X;
+ dest.LowerRightCorner.X = rect.UpperLeftCorner.X + middle.UpperLeftCorner.X;
src.LowerRightCorner.X = middle.UpperLeftCorner.X;
break;
@@ -201,16 +199,14 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture,
break;
case 2:
- dest.UpperLeftCorner.X = rect.LowerRightCorner.X -
- lowerRightOffset.X;
+ dest.UpperLeftCorner.X = rect.LowerRightCorner.X - lowerRightOffset.X;
src.UpperLeftCorner.X = middle.LowerRightCorner.X;
break;
}
switch (y) {
case 0:
- dest.LowerRightCorner.Y = rect.UpperLeftCorner.Y +
- middle.UpperLeftCorner.Y;
+ dest.LowerRightCorner.Y = rect.UpperLeftCorner.Y + middle.UpperLeftCorner.Y;
src.LowerRightCorner.Y = middle.UpperLeftCorner.Y;
break;
@@ -222,14 +218,12 @@ void draw2DImage9Slice(video::IVideoDriver *driver, video::ITexture *texture,
break;
case 2:
- dest.UpperLeftCorner.Y = rect.LowerRightCorner.Y -
- lowerRightOffset.Y;
+ dest.UpperLeftCorner.Y = rect.LowerRightCorner.Y - lowerRightOffset.Y;
src.UpperLeftCorner.Y = middle.LowerRightCorner.Y;
break;
}
- draw2DImageFilterScaled(driver, texture, dest, src, cliprect,
- colors, true);
+ draw2DImageFilterScaled(driver, texture, dest, src, cliprect, colors, true);
}
}
}
diff --git a/src/client/guiscalingfilter.h b/src/client/guiscalingfilter.h
index 703cbfb93..b703d91f0 100644
--- a/src/client/guiscalingfilter.h
+++ b/src/client/guiscalingfilter.h
@@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
/* Manually insert an image into the cache, useful to avoid texture-to-image
* conversion whenever we can intercept it.
*/
-void guiScalingCache(
- const io::path &key, video::IVideoDriver *driver, video::IImage *value);
+void guiScalingCache(const io::path &key, video::IVideoDriver *driver, video::IImage *value);
// Manually clear the cache, e.g. when switching to different worlds.
void guiScalingCacheClear();
@@ -39,16 +38,16 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, video::ITex
/* Convenience wrapper for guiScalingResizeCached that accepts parameters that
* are available at GUI imagebutton creation time.
*/
-video::ITexture *guiScalingImageButton(
- video::IVideoDriver *driver, video::ITexture *src, s32 width, s32 height);
+video::ITexture *guiScalingImageButton(video::IVideoDriver *driver, video::ITexture *src,
+ s32 width, s32 height);
/* Replacement for driver->draw2DImage() that uses the high-quality pre-scaled
* texture, if configured.
*/
void draw2DImageFilterScaled(video::IVideoDriver *driver, video::ITexture *txr,
const core::rect<s32> &destrect, const core::rect<s32> &srcrect,
- const core::rect<s32> *cliprect = 0,
- const video::SColor *const colors = 0, bool usealpha = false);
+ const core::rect<s32> *cliprect = 0, const video::SColor *const colors = 0,
+ bool usealpha = false);
/*
* 9-slice / segment drawing
diff --git a/src/client/hud.cpp b/src/client/hud.cpp
index db5c5ef9f..2b347c1e0 100644
--- a/src/client/hud.cpp
+++ b/src/client/hud.cpp
@@ -47,16 +47,16 @@ with this program; if not, write to the Free Software Foundation, Inc.,
Hud::Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player,
Inventory *inventory)
{
- driver = RenderingEngine::get_video_driver();
- this->guienv = guienv;
- this->client = client;
- this->player = player;
- this->inventory = inventory;
-
- m_hud_scaling = g_settings->getFloat("hud_scaling");
- m_scale_factor = m_hud_scaling * RenderingEngine::getDisplayDensity();
- m_hotbar_imagesize = std::floor(
- HOTBAR_IMAGE_SIZE * RenderingEngine::getDisplayDensity() + 0.5f);
+ driver = RenderingEngine::get_video_driver();
+ this->guienv = guienv;
+ this->client = client;
+ this->player = player;
+ this->inventory = inventory;
+
+ m_hud_scaling = g_settings->getFloat("hud_scaling");
+ m_scale_factor = m_hud_scaling * RenderingEngine::getDisplayDensity();
+ m_hotbar_imagesize = std::floor(HOTBAR_IMAGE_SIZE *
+ RenderingEngine::getDisplayDensity() + 0.5f);
m_hotbar_imagesize *= m_hud_scaling;
m_padding = m_hotbar_imagesize / 12;
@@ -98,19 +98,16 @@ Hud::Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player,
if (g_settings->getBool("enable_shaders")) {
IShaderSource *shdrsrc = client->getShaderSource();
- u16 shader_id = shdrsrc->getShader(m_mode == HIGHLIGHT_HALO
- ? "selection_shader"
- : "default_shader",
- 1, 1);
- m_selection_material.MaterialType =
- shdrsrc->getShaderInfo(shader_id).material;
+ u16 shader_id = shdrsrc->getShader(
+ m_mode == HIGHLIGHT_HALO ? "selection_shader" : "default_shader", 1, 1);
+ m_selection_material.MaterialType = shdrsrc->getShaderInfo(shader_id).material;
} else {
m_selection_material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
}
if (m_mode == HIGHLIGHT_BOX) {
m_selection_material.Thickness =
- rangelim(g_settings->getS16("selectionbox_width"), 1, 5);
+ rangelim(g_settings->getS16("selectionbox_width"), 1, 5);
} else if (m_mode == HIGHLIGHT_HALO) {
m_selection_material.setTexture(0, tsrc->getTextureForMesh("halo.png"));
m_selection_material.setFlag(video::EMF_BACK_FACE_CULLING, true);
@@ -125,50 +122,51 @@ Hud::~Hud()
m_selection_mesh->drop();
}
-void Hud::drawItem(const ItemStack &item, const core::rect<s32> &rect, bool selected)
+void Hud::drawItem(const ItemStack &item, const core::rect<s32>& rect,
+ bool selected)
{
if (selected) {
/* draw hihlighting around selected item */
if (use_hotbar_selected_image) {
core::rect<s32> imgrect2 = rect;
- imgrect2.UpperLeftCorner.X -= (m_padding * 2);
- imgrect2.UpperLeftCorner.Y -= (m_padding * 2);
- imgrect2.LowerRightCorner.X += (m_padding * 2);
- imgrect2.LowerRightCorner.Y += (m_padding * 2);
- video::ITexture *texture =
- tsrc->getTexture(hotbar_selected_image);
- core::dimension2di imgsize(texture->getOriginalSize());
+ imgrect2.UpperLeftCorner.X -= (m_padding*2);
+ imgrect2.UpperLeftCorner.Y -= (m_padding*2);
+ imgrect2.LowerRightCorner.X += (m_padding*2);
+ imgrect2.LowerRightCorner.Y += (m_padding*2);
+ video::ITexture *texture = tsrc->getTexture(hotbar_selected_image);
+ core::dimension2di imgsize(texture->getOriginalSize());
draw2DImageFilterScaled(driver, texture, imgrect2,
- core::rect<s32>(core::position2d<s32>(0, 0),
- imgsize),
+ core::rect<s32>(core::position2d<s32>(0,0), imgsize),
NULL, hbar_colors, true);
} else {
- video::SColor c_outside(255, 255, 0, 0);
- // video::SColor c_outside(255,0,0,0);
- // video::SColor c_inside(255,192,192,192);
+ video::SColor c_outside(255,255,0,0);
+ //video::SColor c_outside(255,0,0,0);
+ //video::SColor c_inside(255,192,192,192);
s32 x1 = rect.UpperLeftCorner.X;
s32 y1 = rect.UpperLeftCorner.Y;
s32 x2 = rect.LowerRightCorner.X;
s32 y2 = rect.LowerRightCorner.Y;
// Black base borders
driver->draw2DRectangle(c_outside,
- core::rect<s32>(v2s32(x1 - m_padding,
- y1 - m_padding),
- v2s32(x2 + m_padding, y1)),
- NULL);
+ core::rect<s32>(
+ v2s32(x1 - m_padding, y1 - m_padding),
+ v2s32(x2 + m_padding, y1)
+ ), NULL);
driver->draw2DRectangle(c_outside,
- core::rect<s32>(v2s32(x1 - m_padding, y2),
- v2s32(x2 + m_padding,
- y2 + m_padding)),
- NULL);
+ core::rect<s32>(
+ v2s32(x1 - m_padding, y2),
+ v2s32(x2 + m_padding, y2 + m_padding)
+ ), NULL);
driver->draw2DRectangle(c_outside,
- core::rect<s32>(v2s32(x1 - m_padding, y1),
- v2s32(x1, y2)),
- NULL);
+ core::rect<s32>(
+ v2s32(x1 - m_padding, y1),
+ v2s32(x1, y2)
+ ), NULL);
driver->draw2DRectangle(c_outside,
- core::rect<s32>(v2s32(x2, y1),
- v2s32(x2 + m_padding, y2)),
- NULL);
+ core::rect<s32>(
+ v2s32(x2, y1),
+ v2s32(x2 + m_padding, y2)
+ ), NULL);
/*// Light inside borders
driver->draw2DRectangle(c_inside,
core::rect<s32>(
@@ -197,11 +195,11 @@ void Hud::drawItem(const ItemStack &item, const core::rect<s32> &rect, bool sele
video::SColor bgcolor2(128, 0, 0, 0);
if (!use_hotbar_image)
driver->draw2DRectangle(bgcolor2, rect, NULL);
- drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL, client,
- selected ? IT_ROT_SELECTED : IT_ROT_NONE);
+ drawItemStack(driver, g_fontengine->getFont(), item, rect, NULL,
+ client, selected ? IT_ROT_SELECTED : IT_ROT_NONE);
}
-// NOTE: selectitem = 0 -> no selected; selectitem 1-based
+//NOTE: selectitem = 0 -> no selected; selectitem 1-based
void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
s32 inv_offset, InventoryList *mainlist, u16 selectitem, u16 direction)
{
@@ -210,8 +208,8 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
g_touchscreengui->resetHud();
#endif
- s32 height = m_hotbar_imagesize + m_padding * 2;
- s32 width = (itemcount - inv_offset) * (m_hotbar_imagesize + m_padding * 2);
+ s32 height = m_hotbar_imagesize + m_padding * 2;
+ s32 width = (itemcount - inv_offset) * (m_hotbar_imagesize + m_padding * 2);
if (direction == HUD_DIR_TOP_BOTTOM || direction == HUD_DIR_BOTTOM_TOP) {
s32 tmp = height;
@@ -237,14 +235,14 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
// draw customized item background
if (use_hotbar_image) {
- core::rect<s32> imgrect2(-m_padding / 2, -m_padding / 2,
- width + m_padding / 2, height + m_padding / 2);
+ core::rect<s32> imgrect2(-m_padding/2, -m_padding/2,
+ width+m_padding/2, height+m_padding/2);
core::rect<s32> rect2 = imgrect2 + pos;
video::ITexture *texture = tsrc->getTexture(hotbar_image);
core::dimension2di imgsize(texture->getOriginalSize());
draw2DImageFilterScaled(driver, texture, rect2,
- core::rect<s32>(core::position2d<s32>(0, 0), imgsize),
- NULL, hbar_colors, true);
+ core::rect<s32>(core::position2d<s32>(0,0), imgsize),
+ NULL, hbar_colors, true);
}
// Draw items
@@ -255,25 +253,20 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
v2s32 steppos;
switch (direction) {
case HUD_DIR_RIGHT_LEFT:
- steppos = v2s32(-(m_padding + (i - inv_offset) * fullimglen),
- m_padding);
+ steppos = v2s32(-(m_padding + (i - inv_offset) * fullimglen), m_padding);
break;
case HUD_DIR_TOP_BOTTOM:
- steppos = v2s32(m_padding,
- m_padding + (i - inv_offset) * fullimglen);
+ steppos = v2s32(m_padding, m_padding + (i - inv_offset) * fullimglen);
break;
case HUD_DIR_BOTTOM_TOP:
- steppos = v2s32(m_padding,
- -(m_padding + (i - inv_offset) * fullimglen));
+ steppos = v2s32(m_padding, -(m_padding + (i - inv_offset) * fullimglen));
break;
default:
- steppos = v2s32(m_padding + (i - inv_offset) * fullimglen,
- m_padding);
+ steppos = v2s32(m_padding + (i - inv_offset) * fullimglen, m_padding);
break;
}
- drawItem(mainlist->getItem(i), (imgrect + pos + steppos),
- (i + 1) == selectitem);
+ drawItem(mainlist->getItem(i), (imgrect + pos + steppos), (i + 1) == selectitem);
#ifdef HAVE_TOUCHSCREENGUI
if (g_touchscreengui)
@@ -282,22 +275,21 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
}
}
-// Calculates screen position of waypoint. Returns true if waypoint is visible (in front
-// of the player), else false.
+// Calculates screen position of waypoint. Returns true if waypoint is visible (in front of the player), else false.
bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *pos)
{
v3f w_pos = e->world_pos * BS;
- scene::ICameraSceneNode *camera =
- RenderingEngine::get_scene_manager()->getActiveCamera();
+ scene::ICameraSceneNode* camera =
+ RenderingEngine::get_scene_manager()->getActiveCamera();
w_pos -= intToFloat(camera_offset, BS);
core::matrix4 trans = camera->getProjectionMatrix();
trans *= camera->getViewMatrix();
- f32 transformed_pos[4] = {w_pos.X, w_pos.Y, w_pos.Z, 1.0f};
+ f32 transformed_pos[4] = { w_pos.X, w_pos.Y, w_pos.Z, 1.0f };
trans.multiplyWith1x4Matrix(transformed_pos);
if (transformed_pos[3] < 0)
return false;
- f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f
- : core::reciprocal(transformed_pos[3]);
+ f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
+ core::reciprocal(transformed_pos[3]);
pos->X = m_screensize.X * (0.5 * transformed_pos[0] * zDiv + 0.5);
pos->Y = m_screensize.Y * (0.5 - transformed_pos[1] * zDiv * 0.5);
return true;
@@ -306,7 +298,7 @@ bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *p
void Hud::drawLuaElements(const v3s16 &camera_offset)
{
u32 text_height = g_fontengine->getTextHeight();
- irr::gui::IGUIFont *font = g_fontengine->getFont();
+ irr::gui::IGUIFont* font = g_fontengine->getFont();
// Reorder elements by z_index
std::vector<size_t> ids;
@@ -326,150 +318,122 @@ void Hud::drawLuaElements(const v3s16 &camera_offset)
for (size_t i : ids) {
HudElement *e = player->getHud(i);
- v2s32 pos(floor(e->pos.X * (float)m_screensize.X + 0.5),
- floor(e->pos.Y * (float)m_screensize.Y + 0.5));
+ v2s32 pos(floor(e->pos.X * (float) m_screensize.X + 0.5),
+ floor(e->pos.Y * (float) m_screensize.Y + 0.5));
switch (e->type) {
- case HUD_ELEM_TEXT: {
- irr::gui::IGUIFont *textfont = font;
- unsigned int font_size = g_fontengine->getDefaultFontSize();
+ case HUD_ELEM_TEXT: {
+ irr::gui::IGUIFont *textfont = font;
+ unsigned int font_size = g_fontengine->getDefaultFontSize();
- if (e->size.X > 0)
- font_size *= e->size.X;
+ if (e->size.X > 0)
+ font_size *= e->size.X;
- if (font_size != g_fontengine->getDefaultFontSize())
- textfont = g_fontengine->getFont(font_size);
+ if (font_size != g_fontengine->getDefaultFontSize())
+ textfont = g_fontengine->getFont(font_size);
- video::SColor color(255, (e->number >> 16) & 0xFF,
- (e->number >> 8) & 0xFF, (e->number >> 0) & 0xFF);
- std::wstring text = unescape_translate(utf8_to_wide(e->text));
- core::dimension2d<u32> textsize =
- textfont->getDimension(text.c_str());
+ video::SColor color(255, (e->number >> 16) & 0xFF,
+ (e->number >> 8) & 0xFF,
+ (e->number >> 0) & 0xFF);
+ std::wstring text = unescape_translate(utf8_to_wide(e->text));
+ core::dimension2d<u32> textsize = textfont->getDimension(text.c_str());
#ifdef __ANDROID__
- // The text size on Android is not proportional with the actual
- // scaling
- irr::gui::IGUIFont *font_scaled =
- font_size <= 3 ? textfont
- : g_fontengine->getFont(
- font_size - 3);
- if (e->offset.X < -20)
- textsize = font_scaled->getDimension(text.c_str());
+ // The text size on Android is not proportional with the actual scaling
+ irr::gui::IGUIFont *font_scaled = font_size <= 3 ?
+ textfont : g_fontengine->getFont(font_size - 3);
+ if (e->offset.X < -20)
+ textsize = font_scaled->getDimension(text.c_str());
#endif
- v2s32 offset((e->align.X - 1.0) * (textsize.Width / 2),
- (e->align.Y - 1.0) * (textsize.Height / 2));
- core::rect<s32> size(0, 0, e->scale.X * m_scale_factor,
- text_height * e->scale.Y * m_scale_factor);
- v2s32 offs(e->offset.X * m_scale_factor,
- e->offset.Y * m_scale_factor);
+ v2s32 offset((e->align.X - 1.0) * (textsize.Width / 2),
+ (e->align.Y - 1.0) * (textsize.Height / 2));
+ core::rect<s32> size(0, 0, e->scale.X * m_scale_factor,
+ text_height * e->scale.Y * m_scale_factor);
+ v2s32 offs(e->offset.X * m_scale_factor,
+ e->offset.Y * m_scale_factor);
#ifdef __ANDROID__
- if (e->offset.X < -20)
- font_scaled->draw(text.c_str(),
- size + pos + offset + offs, color);
- else
+ if (e->offset.X < -20)
+ font_scaled->draw(text.c_str(), size + pos + offset + offs, color);
+ else
#endif
- {
- textfont->draw(text.c_str(), size + pos + offset + offs,
- color);
- }
- break;
- }
- case HUD_ELEM_STATBAR: {
- v2s32 offs(e->offset.X, e->offset.Y);
- drawStatbar(pos, HUD_CORNER_UPPER, e->dir, e->text, e->text2,
+ {
+ textfont->draw(text.c_str(), size + pos + offset + offs, color);
+ }
+ break; }
+ case HUD_ELEM_STATBAR: {
+ v2s32 offs(e->offset.X, e->offset.Y);
+ drawStatbar(pos, HUD_CORNER_UPPER, e->dir, e->text, e->text2,
e->number, e->item, offs, e->size);
- break;
- }
- case HUD_ELEM_INVENTORY: {
- InventoryList *inv = inventory->getList(e->text);
- drawItems(pos, v2s32(e->offset.X, e->offset.Y), e->number, 0, inv,
- e->item, e->dir);
- break;
- }
- case HUD_ELEM_WAYPOINT: {
- if (!calculateScreenPos(camera_offset, e, &pos))
- break;
- v3f p_pos = player->getPosition() / BS;
- pos += v2s32(e->offset.X, e->offset.Y);
- video::SColor color(255, (e->number >> 16) & 0xFF,
- (e->number >> 8) & 0xFF, (e->number >> 0) & 0xFF);
- std::wstring text = unescape_translate(utf8_to_wide(e->name));
- const std::string &unit = e->text;
- // waypoints reuse the item field to store precision, item =
- // precision + 1
- u32 item = e->item;
- float precision = (item == 0) ? 10.0f : (item - 1.f);
- bool draw_precision = precision > 0;
-
- core::rect<s32> bounds(0, 0,
- font->getDimension(text.c_str()).Width,
- (draw_precision ? 2 : 1) * text_height);
- pos.Y += (e->align.Y - 1.0) * bounds.getHeight() / 2;
- bounds += pos;
- font->draw(text.c_str(),
- bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() /
- 2,
- 0),
- color);
- if (draw_precision) {
- std::ostringstream os;
- float distance =
- std::floor(precision *
- p_pos.getDistanceFrom(
- e->world_pos)) /
- precision;
- os << distance << unit;
- text = unescape_translate(utf8_to_wide(os.str()));
- bounds.LowerRightCorner.X =
- bounds.UpperLeftCorner.X +
- font->getDimension(text.c_str()).Width;
- font->draw(text.c_str(),
- bounds + v2s32((e->align.X - 1.0f) * bounds.getWidth() /
- 2,
- text_height),
- color);
+ break; }
+ case HUD_ELEM_INVENTORY: {
+ InventoryList *inv = inventory->getList(e->text);
+ drawItems(pos, v2s32(e->offset.X, e->offset.Y), e->number, 0,
+ inv, e->item, e->dir);
+ break; }
+ case HUD_ELEM_WAYPOINT: {
+ if (!calculateScreenPos(camera_offset, e, &pos))
+ break;
+ v3f p_pos = player->getPosition() / BS;
+ pos += v2s32(e->offset.X, e->offset.Y);
+ video::SColor color(255, (e->number >> 16) & 0xFF,
+ (e->number >> 8) & 0xFF,
+ (e->number >> 0) & 0xFF);
+ std::wstring text = unescape_translate(utf8_to_wide(e->name));
+ const std::string &unit = e->text;
+ // waypoints reuse the item field to store precision, item = precision + 1
+ u32 item = e->item;
+ float precision = (item == 0) ? 10.0f : (item - 1.f);
+ bool draw_precision = precision > 0;
+
+ core::rect<s32> bounds(0, 0, font->getDimension(text.c_str()).Width, (draw_precision ? 2:1) * text_height);
+ pos.Y += (e->align.Y - 1.0) * bounds.getHeight() / 2;
+ bounds += pos;
+ font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() / 2, 0), color);
+ if (draw_precision) {
+ std::ostringstream os;
+ float distance = std::floor(precision * p_pos.getDistanceFrom(e->world_pos)) / precision;
+ os << distance << unit;
+ text = unescape_translate(utf8_to_wide(os.str()));
+ bounds.LowerRightCorner.X = bounds.UpperLeftCorner.X + font->getDimension(text.c_str()).Width;
+ font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0f) * bounds.getWidth() / 2, text_height), color);
+ }
+ break; }
+ case HUD_ELEM_IMAGE_WAYPOINT: {
+ if (!calculateScreenPos(camera_offset, e, &pos))
+ break;
}
- break;
- }
- case HUD_ELEM_IMAGE_WAYPOINT: {
- if (!calculateScreenPos(camera_offset, e, &pos))
- break;
- }
- case HUD_ELEM_IMAGE: {
- video::ITexture *texture = tsrc->getTexture(e->text);
- if (!texture)
- continue;
-
- const video::SColor color(255, 255, 255, 255);
- const video::SColor colors[] = {color, color, color, color};
- core::dimension2di imgsize(texture->getOriginalSize());
- v2s32 dstsize(imgsize.Width * e->scale.X * m_scale_factor,
- imgsize.Height * e->scale.Y * m_scale_factor);
- if (e->scale.X < 0)
- dstsize.X = m_screensize.X * (e->scale.X * -0.01);
- if (e->scale.Y < 0)
- dstsize.Y = m_screensize.Y * (e->scale.Y * -0.01);
- v2s32 offset((e->align.X - 1.0) * dstsize.X / 2,
- (e->align.Y - 1.0) * dstsize.Y / 2);
- core::rect<s32> rect(0, 0, dstsize.X, dstsize.Y);
- rect += pos + offset +
- v2s32(e->offset.X * m_scale_factor,
- e->offset.Y * m_scale_factor);
- draw2DImageFilterScaled(driver, texture, rect,
- core::rect<s32>(core::position2d<s32>(0, 0),
- imgsize),
+ case HUD_ELEM_IMAGE: {
+ video::ITexture *texture = tsrc->getTexture(e->text);
+ if (!texture)
+ continue;
+
+ const video::SColor color(255, 255, 255, 255);
+ const video::SColor colors[] = {color, color, color, color};
+ core::dimension2di imgsize(texture->getOriginalSize());
+ v2s32 dstsize(imgsize.Width * e->scale.X * m_scale_factor,
+ imgsize.Height * e->scale.Y * m_scale_factor);
+ if (e->scale.X < 0)
+ dstsize.X = m_screensize.X * (e->scale.X * -0.01);
+ if (e->scale.Y < 0)
+ dstsize.Y = m_screensize.Y * (e->scale.Y * -0.01);
+ v2s32 offset((e->align.X - 1.0) * dstsize.X / 2,
+ (e->align.Y - 1.0) * dstsize.Y / 2);
+ core::rect<s32> rect(0, 0, dstsize.X, dstsize.Y);
+ rect += pos + offset + v2s32(e->offset.X * m_scale_factor,
+ e->offset.Y * m_scale_factor);
+ draw2DImageFilterScaled(driver, texture, rect,
+ core::rect<s32>(core::position2d<s32>(0,0), imgsize),
NULL, colors, true);
- break;
- }
- default:
- infostream << "Hud::drawLuaElements: ignoring drawform "
- << e->type << " of hud element ID " << i
- << " due to unrecognized type" << std::endl;
+ break; }
+ default:
+ infostream << "Hud::drawLuaElements: ignoring drawform " << e->type <<
+ " of hud element ID " << i << " due to unrecognized type" << std::endl;
}
}
}
-void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture,
- const std::string &bgtexture, s32 count, s32 maxcount, v2s32 offset,
- v2s32 size)
+
+void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir,
+ const std::string &texture, const std::string &bgtexture,
+ s32 count, s32 maxcount, v2s32 offset, v2s32 size)
{
const video::SColor color(255, 255, 255, 255);
const video::SColor colors[] = {color, color, color, color};
@@ -488,12 +452,12 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex
if (size == v2s32()) {
dstd = srcd;
dstd.Height *= m_scale_factor;
- dstd.Width *= m_scale_factor;
+ dstd.Width *= m_scale_factor;
offset.X *= m_scale_factor;
offset.Y *= m_scale_factor;
} else {
dstd.Height = size.Y * m_scale_factor;
- dstd.Width = size.X * m_scale_factor;
+ dstd.Width = size.X * m_scale_factor;
offset.X *= m_scale_factor;
offset.Y *= m_scale_factor;
}
@@ -506,27 +470,29 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex
v2s32 steppos;
switch (drawdir) {
- case HUD_DIR_RIGHT_LEFT:
- steppos = v2s32(-1, 0);
- break;
- case HUD_DIR_TOP_BOTTOM:
- steppos = v2s32(0, 1);
- break;
- case HUD_DIR_BOTTOM_TOP:
- steppos = v2s32(0, -1);
- break;
- default:
- // From left to right
- steppos = v2s32(1, 0);
- break;
+ case HUD_DIR_RIGHT_LEFT:
+ steppos = v2s32(-1, 0);
+ break;
+ case HUD_DIR_TOP_BOTTOM:
+ steppos = v2s32(0, 1);
+ break;
+ case HUD_DIR_BOTTOM_TOP:
+ steppos = v2s32(0, -1);
+ break;
+ default:
+ // From left to right
+ steppos = v2s32(1, 0);
+ break;
}
- auto calculate_clipping_rect = [](core::dimension2di src,
- v2s32 steppos) -> core::rect<s32> {
+ auto calculate_clipping_rect = [] (core::dimension2di src,
+ v2s32 steppos) -> core::rect<s32> {
+
// Create basic rectangle
core::rect<s32> rect(0, 0,
- src.Width - std::abs(steppos.X) * src.Width / 2,
- src.Height - std::abs(steppos.Y) * src.Height / 2);
+ src.Width - std::abs(steppos.X) * src.Width / 2,
+ src.Height - std::abs(steppos.Y) * src.Height / 2
+ );
// Move rectangle left or down
if (steppos.X == -1)
rect += v2s32(src.Width / 2, 0);
@@ -541,8 +507,8 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex
if (count % 2 == 1) {
// Need to draw halves: Calculate rectangles
- srchalfrect = calculate_clipping_rect(srcd, steppos);
- dsthalfrect = calculate_clipping_rect(dstd, steppos);
+ srchalfrect = calculate_clipping_rect(srcd, steppos);
+ dsthalfrect = calculate_clipping_rect(dstd, steppos);
srchalfrect2 = calculate_clipping_rect(srcd, steppos * -1);
dsthalfrect2 = calculate_clipping_rect(dstd, steppos * -1);
}
@@ -556,19 +522,20 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex
core::rect<s32> dstrect(0, 0, dstd.Width, dstd.Height);
dstrect += p;
- draw2DImageFilterScaled(driver, stat_texture, dstrect, srcrect, NULL,
- colors, true);
+ draw2DImageFilterScaled(driver, stat_texture,
+ dstrect, srcrect, NULL, colors, true);
p += steppos;
}
if (count % 2 == 1) {
// Draw half a texture
- draw2DImageFilterScaled(driver, stat_texture, dsthalfrect + p,
- srchalfrect, NULL, colors, true);
+ draw2DImageFilterScaled(driver, stat_texture,
+ dsthalfrect + p, srchalfrect, NULL, colors, true);
if (stat_texture_bg && maxcount > count) {
- draw2DImageFilterScaled(driver, stat_texture_bg, dsthalfrect2 + p,
- srchalfrect2, NULL, colors, true);
+ draw2DImageFilterScaled(driver, stat_texture_bg,
+ dsthalfrect2 + p, srchalfrect2,
+ NULL, colors, true);
p += steppos;
}
}
@@ -585,26 +552,28 @@ void Hud::drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &tex
core::rect<s32> dstrect(0, 0, dstd.Width, dstd.Height);
dstrect += p;
- draw2DImageFilterScaled(driver, stat_texture_bg, dstrect, srcrect,
+ draw2DImageFilterScaled(driver, stat_texture_bg,
+ dstrect, srcrect,
NULL, colors, true);
p += steppos;
}
if (maxcount % 2 == 1) {
- draw2DImageFilterScaled(driver, stat_texture_bg, dsthalfrect + p,
- srchalfrect, NULL, colors, true);
+ draw2DImageFilterScaled(driver, stat_texture_bg,
+ dsthalfrect + p, srchalfrect,
+ NULL, colors, true);
}
}
}
-void Hud::drawHotbar(u16 playeritem)
-{
+
+void Hud::drawHotbar(u16 playeritem) {
v2s32 centerlowerpos(m_displaycenter.X, m_screensize.Y);
InventoryList *mainlist = inventory->getList("main");
if (mainlist == NULL) {
- // silently ignore this we may not be initialized completely
+ //silently ignore this we may not be initialized completely
return;
}
@@ -613,57 +582,49 @@ void Hud::drawHotbar(u16 playeritem)
v2s32 pos = centerlowerpos - v2s32(width / 2, m_hotbar_imagesize + m_padding * 3);
const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
- if ((float)width / (float)window_size.X <=
+ if ((float) width / (float) window_size.X <=
g_settings->getFloat("hud_hotbar_max_width")) {
if (player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE) {
- drawItems(pos, v2s32(0, 0), hotbar_itemcount, 0, mainlist,
- playeritem + 1, 0);
+ drawItems(pos, v2s32(0, 0), hotbar_itemcount, 0, mainlist, playeritem + 1, 0);
}
} else {
- pos.X += width / 4;
+ pos.X += width/4;
v2s32 secondpos = pos;
pos = pos - v2s32(0, m_hotbar_imagesize + m_padding);
if (player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE) {
- drawItems(pos, v2s32(0, 0), hotbar_itemcount / 2, 0, mainlist,
- playeritem + 1, 0);
+ drawItems(pos, v2s32(0, 0), hotbar_itemcount / 2, 0,
+ mainlist, playeritem + 1, 0);
drawItems(secondpos, v2s32(0, 0), hotbar_itemcount,
- hotbar_itemcount / 2, mainlist, playeritem + 1,
- 0);
+ hotbar_itemcount / 2, mainlist, playeritem + 1, 0);
}
}
}
+
void Hud::drawCrosshair()
{
if (pointing_at_object) {
if (use_object_crosshair_image) {
- video::ITexture *object_crosshair =
- tsrc->getTexture("object_crosshair.png");
- v2u32 size = object_crosshair->getOriginalSize();
+ video::ITexture *object_crosshair = tsrc->getTexture("object_crosshair.png");
+ v2u32 size = object_crosshair->getOriginalSize();
v2s32 lsize = v2s32(m_displaycenter.X - (size.X / 2),
m_displaycenter.Y - (size.Y / 2));
driver->draw2DImage(object_crosshair, lsize,
- core::rect<s32>(0, 0, size.X, size.Y), nullptr,
- crosshair_argb, true);
+ core::rect<s32>(0, 0, size.X, size.Y),
+ nullptr, crosshair_argb, true);
} else {
driver->draw2DLine(
- m_displaycenter -
- v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
- OBJECT_CROSSHAIR_LINE_SIZE),
- m_displaycenter +
- v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
- OBJECT_CROSSHAIR_LINE_SIZE),
- crosshair_argb);
+ m_displaycenter - v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
+ OBJECT_CROSSHAIR_LINE_SIZE),
+ m_displaycenter + v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
+ OBJECT_CROSSHAIR_LINE_SIZE), crosshair_argb);
driver->draw2DLine(
- m_displaycenter +
- v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
- -OBJECT_CROSSHAIR_LINE_SIZE),
- m_displaycenter +
- v2s32(-OBJECT_CROSSHAIR_LINE_SIZE,
- OBJECT_CROSSHAIR_LINE_SIZE),
- crosshair_argb);
+ m_displaycenter + v2s32(OBJECT_CROSSHAIR_LINE_SIZE,
+ -OBJECT_CROSSHAIR_LINE_SIZE),
+ m_displaycenter + v2s32(-OBJECT_CROSSHAIR_LINE_SIZE,
+ OBJECT_CROSSHAIR_LINE_SIZE), crosshair_argb);
}
return;
@@ -671,19 +632,17 @@ void Hud::drawCrosshair()
if (use_crosshair_image) {
video::ITexture *crosshair = tsrc->getTexture("crosshair.png");
- v2u32 size = crosshair->getOriginalSize();
+ v2u32 size = crosshair->getOriginalSize();
v2s32 lsize = v2s32(m_displaycenter.X - (size.X / 2),
m_displaycenter.Y - (size.Y / 2));
driver->draw2DImage(crosshair, lsize,
- core::rect<s32>(0, 0, size.X, size.Y), nullptr,
- crosshair_argb, true);
+ core::rect<s32>(0, 0, size.X, size.Y),
+ nullptr, crosshair_argb, true);
} else {
driver->draw2DLine(m_displaycenter - v2s32(CROSSHAIR_LINE_SIZE, 0),
- m_displaycenter + v2s32(CROSSHAIR_LINE_SIZE, 0),
- crosshair_argb);
+ m_displaycenter + v2s32(CROSSHAIR_LINE_SIZE, 0), crosshair_argb);
driver->draw2DLine(m_displaycenter - v2s32(0, CROSSHAIR_LINE_SIZE),
- m_displaycenter + v2s32(0, CROSSHAIR_LINE_SIZE),
- crosshair_argb);
+ m_displaycenter + v2s32(0, CROSSHAIR_LINE_SIZE), crosshair_argb);
}
}
@@ -700,11 +659,10 @@ void Hud::drawSelectionMesh()
// Draw 3D selection boxes
video::SMaterial oldmaterial = driver->getMaterial2D();
driver->setMaterial(m_selection_material);
- for (auto &selection_box : m_selection_boxes) {
- aabb3f box = aabb3f(selection_box.MinEdge +
- m_selection_pos_with_offset,
- selection_box.MaxEdge +
- m_selection_pos_with_offset);
+ for (auto & selection_box : m_selection_boxes) {
+ aabb3f box = aabb3f(
+ selection_box.MinEdge + m_selection_pos_with_offset,
+ selection_box.MaxEdge + m_selection_pos_with_offset);
u32 r = (selectionbox_argb.getRed() *
m_selection_mesh_color.getRed() / 255);
@@ -721,12 +679,12 @@ void Hud::drawSelectionMesh()
driver->setMaterial(m_selection_material);
setMeshColor(m_selection_mesh, m_selection_mesh_color);
video::SColor face_color(0,
- MYMIN(255, m_selection_mesh_color.getRed() * 1.5),
- MYMIN(255, m_selection_mesh_color.getGreen() * 1.5),
- MYMIN(255, m_selection_mesh_color.getBlue() * 1.5));
- setMeshColorByNormal(
- m_selection_mesh, m_selected_face_normal, face_color);
- scene::IMesh *mesh = cloneMesh(m_selection_mesh);
+ MYMIN(255, m_selection_mesh_color.getRed() * 1.5),
+ MYMIN(255, m_selection_mesh_color.getGreen() * 1.5),
+ MYMIN(255, m_selection_mesh_color.getBlue() * 1.5));
+ setMeshColorByNormal(m_selection_mesh, m_selected_face_normal,
+ face_color);
+ scene::IMesh* mesh = cloneMesh(m_selection_mesh);
translateMesh(mesh, m_selection_pos_with_offset);
u32 mc = m_selection_mesh->getMeshBufferCount();
for (u32 i = 0; i < mc; i++) {
@@ -757,8 +715,14 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset)
// New pointed object, create new mesh.
// Texture UV coordinates for selection boxes
- static f32 texture_uv[24] = {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
- 1, 1, 0, 0, 1, 1};
+ static f32 texture_uv[24] = {
+ 0,0,1,1,
+ 0,0,1,1,
+ 0,0,1,1,
+ 0,0,1,1,
+ 0,0,1,1,
+ 0,0,1,1
+ };
// Use single halo box instead of multiple overlapping boxes.
// Temporary solution - problem can be solved with multiple
@@ -773,34 +737,37 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset)
}
m_halo_boxes.push_back(halo_box);
- m_selection_mesh = convertNodeboxesToMesh(m_halo_boxes, texture_uv, 0.5);
+ m_selection_mesh = convertNodeboxesToMesh(
+ m_halo_boxes, texture_uv, 0.5);
}
-void Hud::resizeHotbar()
-{
+void Hud::resizeHotbar() {
const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
if (m_screensize != window_size) {
- m_hotbar_imagesize = floor(
- HOTBAR_IMAGE_SIZE * RenderingEngine::getDisplayDensity() +
- 0.5);
+ m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE *
+ RenderingEngine::getDisplayDensity() + 0.5);
m_hotbar_imagesize *= m_hud_scaling;
m_padding = m_hotbar_imagesize / 12;
m_screensize = window_size;
- m_displaycenter = v2s32(m_screensize.X / 2, m_screensize.Y / 2);
+ m_displaycenter = v2s32(m_screensize.X/2,m_screensize.Y/2);
}
}
-struct MeshTimeInfo
-{
+struct MeshTimeInfo {
u64 time;
scene::IMesh *mesh = nullptr;
};
-void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
- const ItemStack &item, const core::rect<s32> &rect,
- const core::rect<s32> *clip, Client *client,
- ItemRotationKind rotation_kind, const v3s16 &angle,
+void drawItemStack(
+ video::IVideoDriver *driver,
+ gui::IGUIFont *font,
+ const ItemStack &item,
+ const core::rect<s32> &rect,
+ const core::rect<s32> *clip,
+ Client *client,
+ ItemRotationKind rotation_kind,
+ const v3s16 &angle,
const v3s16 &rotation_speed)
{
static MeshTimeInfo rotation_time_infos[IT_ROT_NONE];
@@ -825,9 +792,7 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
ti.mesh = mesh;
ti.time = porting::getTimeMs();
} else {
- delta = porting::getDeltaMs(
- ti.time, porting::getTimeMs()) %
- 100000;
+ delta = porting::getDeltaMs(ti.time, porting::getTimeMs()) % 100000;
}
}
core::rect<s32> oldViewPort = driver->getViewPort();
@@ -842,26 +807,18 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
core::matrix4 ViewMatrix;
ViewMatrix.buildProjectionMatrixOrthoLH(
- 2.0f * viewrect.getWidth() / rect.getWidth(),
- 2.0f * viewrect.getHeight() / rect.getHeight(), -1.0f,
- 100.0f);
+ 2.0f * viewrect.getWidth() / rect.getWidth(),
+ 2.0f * viewrect.getHeight() / rect.getHeight(),
+ -1.0f,
+ 100.0f);
ViewMatrix.setTranslation(core::vector3df(
- 1.0f *
- (rect.LowerRightCorner.X +
- rect.UpperLeftCorner.X -
- viewrect.LowerRightCorner
- .X -
- viewrect.UpperLeftCorner
- .X) /
- viewrect.getWidth(),
- 1.0f *
- (viewrect.LowerRightCorner.Y +
- viewrect.UpperLeftCorner
- .Y -
- rect.LowerRightCorner.Y -
- rect.UpperLeftCorner.Y) /
- viewrect.getHeight(),
- 0.0f));
+ 1.0f * (rect.LowerRightCorner.X + rect.UpperLeftCorner.X -
+ viewrect.LowerRightCorner.X - viewrect.UpperLeftCorner.X) /
+ viewrect.getWidth(),
+ 1.0f * (viewrect.LowerRightCorner.Y + viewrect.UpperLeftCorner.Y -
+ rect.LowerRightCorner.Y - rect.UpperLeftCorner.Y) /
+ viewrect.getHeight(),
+ 0.0f));
driver->setTransform(video::ETS_PROJECTION, ProjMatrix);
driver->setTransform(video::ETS_VIEW, ViewMatrix);
@@ -870,20 +827,22 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
matrix.makeIdentity();
static thread_local bool enable_animations =
- g_settings->getBool("inventory_items_animations");
+ g_settings->getBool("inventory_items_animations");
if (enable_animations) {
- float timer_f = (float)delta / 5000.f;
+ float timer_f = (float) delta / 5000.f;
matrix.setRotationDegrees(v3f(
- angle.X + rotation_speed.X * 3.60f * timer_f,
- angle.Y + rotation_speed.Y * 3.60f * timer_f,
- angle.Z + rotation_speed.Z * 3.60f * timer_f));
+ angle.X + rotation_speed.X * 3.60f * timer_f,
+ angle.Y + rotation_speed.Y * 3.60f * timer_f,
+ angle.Z + rotation_speed.Z * 3.60f * timer_f)
+ );
}
driver->setTransform(video::ETS_WORLD, matrix);
driver->setViewPort(viewrect);
- video::SColor basecolor = client->idef()->getItemstackColor(item, client);
+ video::SColor basecolor =
+ client->idef()->getItemstackColor(item, client);
u32 mc = mesh->getMeshBufferCount();
for (u32 j = 0; j < mc; ++j) {
@@ -919,13 +878,10 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
if (def.type == ITEM_NODE && def.inventory_image.empty() &&
!def.inventory_overlay.empty()) {
ITextureSource *tsrc = client->getTextureSource();
- video::ITexture *overlay_texture =
- tsrc->getTexture(def.inventory_overlay);
- core::dimension2d<u32> dimens =
- overlay_texture->getOriginalSize();
+ video::ITexture *overlay_texture = tsrc->getTexture(def.inventory_overlay);
+ core::dimension2d<u32> dimens = overlay_texture->getOriginalSize();
core::rect<s32> srcrect(0, 0, dimens.Width, dimens.Height);
- draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect,
- clip, 0, true);
+ draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect, clip, 0, true);
}
}
@@ -935,15 +891,17 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
float barpad_x = rect.getWidth() / 16;
float barpad_y = rect.getHeight() / 16;
- core::rect<s32> progressrect(rect.UpperLeftCorner.X + barpad_x,
- rect.LowerRightCorner.Y - barpad_y - barheight,
- rect.LowerRightCorner.X - barpad_x,
- rect.LowerRightCorner.Y - barpad_y);
+ core::rect<s32> progressrect(
+ rect.UpperLeftCorner.X + barpad_x,
+ rect.LowerRightCorner.Y - barpad_y - barheight,
+ rect.LowerRightCorner.X - barpad_x,
+ rect.LowerRightCorner.Y - barpad_y);
// Shrink progressrect by amount of tool damage
float wear = item.wear / 65535.0f;
- int progressmid = wear * progressrect.UpperLeftCorner.X +
- (1 - wear) * progressrect.LowerRightCorner.X;
+ int progressmid =
+ wear * progressrect.UpperLeftCorner.X +
+ (1 - wear) * progressrect.LowerRightCorner.X;
// Compute progressbar color
// wear = 0.0: green
@@ -975,9 +933,11 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
v2s32 sdim(dim.X, dim.Y);
core::rect<s32> rect2(
- /*rect.UpperLeftCorner,
- core::dimension2d<u32>(rect.getWidth(), 15)*/
- rect.LowerRightCorner - sdim, sdim);
+ /*rect.UpperLeftCorner,
+ core::dimension2d<u32>(rect.getWidth(), 15)*/
+ rect.LowerRightCorner - sdim,
+ sdim
+ );
video::SColor bgcolor(128, 0, 0, 0);
driver->draw2DRectangle(bgcolor, rect2, clip);
@@ -987,11 +947,15 @@ void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
}
}
-void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
- const ItemStack &item, const core::rect<s32> &rect,
- const core::rect<s32> *clip, Client *client,
+void drawItemStack(
+ video::IVideoDriver *driver,
+ gui::IGUIFont *font,
+ const ItemStack &item,
+ const core::rect<s32> &rect,
+ const core::rect<s32> *clip,
+ Client *client,
ItemRotationKind rotation_kind)
{
drawItemStack(driver, font, item, rect, clip, client, rotation_kind,
- v3s16(0, 0, 0), v3s16(0, 100, 0));
+ v3s16(0, 0, 0), v3s16(0, 100, 0));
}
diff --git a/src/client/hud.h b/src/client/hud.h
index 818e3dea3..ba34d479d 100644
--- a/src/client/hud.h
+++ b/src/client/hud.h
@@ -85,9 +85,9 @@ public:
private:
bool calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *pos);
- void drawStatbar(v2s32 pos, u16 corner, u16 drawdir, const std::string &texture,
- const std::string &bgtexture, s32 count, s32 maxcount,
- v2s32 offset, v2s32 size = v2s32());
+ void drawStatbar(v2s32 pos, u16 corner, u16 drawdir,
+ const std::string &texture, const std::string& bgtexture,
+ s32 count, s32 maxcount, v2s32 offset, v2s32 size = v2s32());
void drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount,
s32 inv_offset, InventoryList *mainlist, u16 selectitem,
@@ -100,8 +100,7 @@ private:
v3s16 m_camera_offset;
v2u32 m_screensize;
v2s32 m_displaycenter;
- s32 m_hotbar_imagesize; // Takes hud_scaling into account, updated by
- // resizeHotbar()
+ s32 m_hotbar_imagesize; // Takes hud_scaling into account, updated by resizeHotbar()
s32 m_padding; // Takes hud_scaling into account, updated by resizeHotbar()
video::SColor hbar_colors[4];
@@ -133,13 +132,22 @@ enum ItemRotationKind
IT_ROT_NONE, // Must be last, also serves as number
};
-void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
- const ItemStack &item, const core::rect<s32> &rect,
- const core::rect<s32> *clip, Client *client,
+void drawItemStack(video::IVideoDriver *driver,
+ gui::IGUIFont *font,
+ const ItemStack &item,
+ const core::rect<s32> &rect,
+ const core::rect<s32> *clip,
+ Client *client,
ItemRotationKind rotation_kind);
-void drawItemStack(video::IVideoDriver *driver, gui::IGUIFont *font,
- const ItemStack &item, const core::rect<s32> &rect,
- const core::rect<s32> *clip, Client *client,
- ItemRotationKind rotation_kind, const v3s16 &angle,
+void drawItemStack(
+ video::IVideoDriver *driver,
+ gui::IGUIFont *font,
+ const ItemStack &item,
+ const core::rect<s32> &rect,
+ const core::rect<s32> *clip,
+ Client *client,
+ ItemRotationKind rotation_kind,
+ const v3s16 &angle,
const v3s16 &rotation_speed);
+
diff --git a/src/client/imagefilters.cpp b/src/client/imagefilters.cpp
index a75e7f8d6..0fa501410 100644
--- a/src/client/imagefilters.cpp
+++ b/src/client/imagefilters.cpp
@@ -38,45 +38,44 @@ void imageCleanTransparent(video::IImage *src, u32 threshold)
// Walk each pixel looking for fully transparent ones.
// Note: loop y around x for better cache locality.
for (u32 ctry = 0; ctry < dim.Height; ctry++)
- for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) {
+ for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) {
- // Ignore opaque pixels.
- irr::video::SColor c = src->getPixel(ctrx, ctry);
- if (c.getAlpha() > threshold)
+ // Ignore opaque pixels.
+ irr::video::SColor c = src->getPixel(ctrx, ctry);
+ if (c.getAlpha() > threshold)
+ continue;
+
+ // Sample size and total weighted r, g, b values.
+ u32 ss = 0, sr = 0, sg = 0, sb = 0;
+
+ // Walk each neighbor pixel (clipped to image bounds).
+ for (u32 sy = (ctry < 1) ? 0 : (ctry - 1);
+ sy <= (ctry + 1) && sy < dim.Height; sy++)
+ for (u32 sx = (ctrx < 1) ? 0 : (ctrx - 1);
+ sx <= (ctrx + 1) && sx < dim.Width; sx++) {
+
+ // Ignore transparent pixels.
+ irr::video::SColor d = src->getPixel(sx, sy);
+ if (d.getAlpha() <= threshold)
continue;
- // Sample size and total weighted r, g, b values.
- u32 ss = 0, sr = 0, sg = 0, sb = 0;
-
- // Walk each neighbor pixel (clipped to image bounds).
- for (u32 sy = (ctry < 1) ? 0 : (ctry - 1);
- sy <= (ctry + 1) && sy < dim.Height; sy++)
- for (u32 sx = (ctrx < 1) ? 0 : (ctrx - 1);
- sx <= (ctrx + 1) && sx < dim.Width;
- sx++) {
-
- // Ignore transparent pixels.
- irr::video::SColor d = src->getPixel(sx, sy);
- if (d.getAlpha() <= threshold)
- continue;
-
- // Add RGB values weighted by alpha.
- u32 a = d.getAlpha();
- ss += a;
- sr += a * d.getRed();
- sg += a * d.getGreen();
- sb += a * d.getBlue();
- }
-
- // If we found any neighbor RGB data, set pixel to average
- // weighted by alpha.
- if (ss > 0) {
- c.setRed(sr / ss);
- c.setGreen(sg / ss);
- c.setBlue(sb / ss);
- src->setPixel(ctrx, ctry, c);
- }
+ // Add RGB values weighted by alpha.
+ u32 a = d.getAlpha();
+ ss += a;
+ sr += a * d.getRed();
+ sg += a * d.getGreen();
+ sb += a * d.getBlue();
}
+
+ // If we found any neighbor RGB data, set pixel to average
+ // weighted by alpha.
+ if (ss > 0) {
+ c.setRed(sr / ss);
+ c.setGreen(sg / ss);
+ c.setBlue(sb / ss);
+ src->setPixel(ctrx, ctry, c);
+ }
+ }
}
/* Scale a region of an image into another image, using nearest-neighbor with
@@ -86,8 +85,7 @@ void imageCleanTransparent(video::IImage *src, u32 threshold)
* filter is designed to produce the most accurate results for both upscaling
* and downscaling.
*/
-void imageScaleNNAA(
- video::IImage *src, const core::rect<s32> &srcrect, video::IImage *dest)
+void imageScaleNNAA(video::IImage *src, const core::rect<s32> &srcrect, video::IImage *dest)
{
double sx, sy, minsx, maxsx, minsy, maxsy, area, ra, ga, ba, aa, pw, ph, pa;
u32 dy, dx;
@@ -103,73 +101,72 @@ void imageScaleNNAA(
// Note: loop y around x for better cache locality.
core::dimension2d<u32> dim = dest->getDimension();
for (dy = 0; dy < dim.Height; dy++)
- for (dx = 0; dx < dim.Width; dx++) {
-
- // Calculate floating-point source rectangle bounds.
- // Do some basic clipping, and for mirrored/flipped rects,
- // make sure min/max are in the right order.
- minsx = sox + (dx * sw / dim.Width);
- minsx = rangelim(minsx, 0, sox + sw);
- maxsx = minsx + sw / dim.Width;
- maxsx = rangelim(maxsx, 0, sox + sw);
- if (minsx > maxsx)
- SWAP(double, minsx, maxsx);
- minsy = soy + (dy * sh / dim.Height);
- minsy = rangelim(minsy, 0, soy + sh);
- maxsy = minsy + sh / dim.Height;
- maxsy = rangelim(maxsy, 0, soy + sh);
- if (minsy > maxsy)
- SWAP(double, minsy, maxsy);
-
- // Total area, and integral of r, g, b values over that area,
- // initialized to zero, to be summed up in next loops.
- area = 0;
- ra = 0;
- ga = 0;
- ba = 0;
- aa = 0;
-
- // Loop over the integral pixel positions described by those
- // bounds.
- for (sy = floor(minsy); sy < maxsy; sy++)
- for (sx = floor(minsx); sx < maxsx; sx++) {
-
- // Calculate width, height, then area of dest
- // pixel that's covered by this source pixel.
- pw = 1;
- if (minsx > sx)
- pw += sx - minsx;
- if (maxsx < (sx + 1))
- pw += maxsx - sx - 1;
- ph = 1;
- if (minsy > sy)
- ph += sy - minsy;
- if (maxsy < (sy + 1))
- ph += maxsy - sy - 1;
- pa = pw * ph;
-
- // Get source pixel and add it to totals, weighted
- // by covered area and alpha.
- pxl = src->getPixel((u32)sx, (u32)sy);
- area += pa;
- ra += pa * pxl.getRed();
- ga += pa * pxl.getGreen();
- ba += pa * pxl.getBlue();
- aa += pa * pxl.getAlpha();
- }
-
- // Set the destination image pixel to the average color.
- if (area > 0) {
- pxl.setRed(ra / area + 0.5);
- pxl.setGreen(ga / area + 0.5);
- pxl.setBlue(ba / area + 0.5);
- pxl.setAlpha(aa / area + 0.5);
- } else {
- pxl.setRed(0);
- pxl.setGreen(0);
- pxl.setBlue(0);
- pxl.setAlpha(0);
- }
- dest->setPixel(dx, dy, pxl);
+ for (dx = 0; dx < dim.Width; dx++) {
+
+ // Calculate floating-point source rectangle bounds.
+ // Do some basic clipping, and for mirrored/flipped rects,
+ // make sure min/max are in the right order.
+ minsx = sox + (dx * sw / dim.Width);
+ minsx = rangelim(minsx, 0, sox + sw);
+ maxsx = minsx + sw / dim.Width;
+ maxsx = rangelim(maxsx, 0, sox + sw);
+ if (minsx > maxsx)
+ SWAP(double, minsx, maxsx);
+ minsy = soy + (dy * sh / dim.Height);
+ minsy = rangelim(minsy, 0, soy + sh);
+ maxsy = minsy + sh / dim.Height;
+ maxsy = rangelim(maxsy, 0, soy + sh);
+ if (minsy > maxsy)
+ SWAP(double, minsy, maxsy);
+
+ // Total area, and integral of r, g, b values over that area,
+ // initialized to zero, to be summed up in next loops.
+ area = 0;
+ ra = 0;
+ ga = 0;
+ ba = 0;
+ aa = 0;
+
+ // Loop over the integral pixel positions described by those bounds.
+ for (sy = floor(minsy); sy < maxsy; sy++)
+ for (sx = floor(minsx); sx < maxsx; sx++) {
+
+ // Calculate width, height, then area of dest pixel
+ // that's covered by this source pixel.
+ pw = 1;
+ if (minsx > sx)
+ pw += sx - minsx;
+ if (maxsx < (sx + 1))
+ pw += maxsx - sx - 1;
+ ph = 1;
+ if (minsy > sy)
+ ph += sy - minsy;
+ if (maxsy < (sy + 1))
+ ph += maxsy - sy - 1;
+ pa = pw * ph;
+
+ // Get source pixel and add it to totals, weighted
+ // by covered area and alpha.
+ pxl = src->getPixel((u32)sx, (u32)sy);
+ area += pa;
+ ra += pa * pxl.getRed();
+ ga += pa * pxl.getGreen();
+ ba += pa * pxl.getBlue();
+ aa += pa * pxl.getAlpha();
+ }
+
+ // Set the destination image pixel to the average color.
+ if (area > 0) {
+ pxl.setRed(ra / area + 0.5);
+ pxl.setGreen(ga / area + 0.5);
+ pxl.setBlue(ba / area + 0.5);
+ pxl.setAlpha(aa / area + 0.5);
+ } else {
+ pxl.setRed(0);
+ pxl.setGreen(0);
+ pxl.setBlue(0);
+ pxl.setAlpha(0);
}
+ dest->setPixel(dx, dy, pxl);
+ }
}
diff --git a/src/client/imagefilters.h b/src/client/imagefilters.h
index 67f031890..5676faf85 100644
--- a/src/client/imagefilters.h
+++ b/src/client/imagefilters.h
@@ -40,5 +40,4 @@ void imageCleanTransparent(video::IImage *src, u32 threshold);
* filter is designed to produce the most accurate results for both upscaling
* and downscaling.
*/
-void imageScaleNNAA(
- video::IImage *src, const core::rect<s32> &srcrect, video::IImage *dest);
+void imageScaleNNAA(video::IImage *src, const core::rect<s32> &srcrect, video::IImage *dest);
diff --git a/src/client/inputhandler.h b/src/client/inputhandler.h
index ef5f6fb32..e006affb2 100644
--- a/src/client/inputhandler.h
+++ b/src/client/inputhandler.h
@@ -218,7 +218,10 @@ public:
virtual ~InputHandler() = default;
- virtual bool isRandom() const { return false; }
+ virtual bool isRandom() const
+ {
+ return false;
+ }
virtual bool isKeyDown(GameKeyType k) = 0;
virtual void setKeypress(const KeyPress &keyCode) = 0;
@@ -374,7 +377,7 @@ public:
m_receiver->clearInput();
}
-private:
+ private:
MyEventReceiver *m_receiver = nullptr;
v2s32 m_mousepos;
};
@@ -384,11 +387,20 @@ class RandomInputHandler : public InputHandler
public:
RandomInputHandler() = default;
- bool isRandom() const { return true; }
+ bool isRandom() const
+ {
+ return true;
+ }
virtual bool isKeyDown(GameKeyType k) { return keydown[keycache.key[k]]; }
- virtual void setKeypress(const KeyPress &keyCode) { keydown.set(keyCode); }
- virtual void unsetKeypress(const KeyPress &keyCode) { keydown.unset(keyCode); }
+ virtual void setKeypress(const KeyPress &keyCode)
+ {
+ keydown.set(keyCode);
+ }
+ virtual void unsetKeypress(const KeyPress &keyCode)
+ {
+ keydown.unset(keyCode);
+ }
virtual bool wasKeyDown(GameKeyType k) { return false; }
virtual bool cancelPressed() { return false; }
virtual v2s32 getMousePos() { return mousepos; }
diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp
index 5bff6fbba..c29e8b639 100644
--- a/src/client/joystick_controller.cpp
+++ b/src/client/joystick_controller.cpp
@@ -41,7 +41,7 @@ bool JoystickAxisCmb::isTriggered(const irr::SEvent::SJoystickEvent &ev) const
}
// spares many characters
-#define JLO_B_PB(A, B, C) jlo.button_keys.emplace_back(A, B, C)
+#define JLO_B_PB(A, B, C) jlo.button_keys.emplace_back(A, B, C)
#define JLO_A_PB(A, B, C, D) jlo.axis_keys.emplace_back(A, B, C, D)
JoystickLayout create_default_layout()
@@ -51,41 +51,41 @@ JoystickLayout create_default_layout()
jlo.axes_dead_border = 1024;
const JoystickAxisLayout axes[JA_COUNT] = {
- {0, 1}, // JA_SIDEWARD_MOVE
- {1, 1}, // JA_FORWARD_MOVE
- {3, 1}, // JA_FRUSTUM_HORIZONTAL
- {4, 1}, // JA_FRUSTUM_VERTICAL
+ {0, 1}, // JA_SIDEWARD_MOVE
+ {1, 1}, // JA_FORWARD_MOVE
+ {3, 1}, // JA_FRUSTUM_HORIZONTAL
+ {4, 1}, // JA_FRUSTUM_VERTICAL
};
memcpy(jlo.axes, axes, sizeof(jlo.axes));
- u32 sb = 1 << 7; // START button mask
- u32 fb = 1 << 3; // FOUR button mask
+ u32 sb = 1 << 7; // START button mask
+ u32 fb = 1 << 3; // FOUR button mask
u32 bm = sb | fb; // Mask for Both Modifiers
// The back button means "ESC".
- JLO_B_PB(KeyType::ESC, 1 << 6, 1 << 6);
+ JLO_B_PB(KeyType::ESC, 1 << 6, 1 << 6);
// The start button counts as modifier as well as use key.
// JLO_B_PB(KeyType::USE, sb, sb));
// Accessible without start modifier button pressed
// regardless whether four is pressed or not
- JLO_B_PB(KeyType::SNEAK, sb | 1 << 2, 1 << 2);
+ JLO_B_PB(KeyType::SNEAK, sb | 1 << 2, 1 << 2);
// Accessible without four modifier button pressed
// regardless whether start is pressed or not
- JLO_B_PB(KeyType::MOUSE_L, fb | 1 << 4, 1 << 4);
- JLO_B_PB(KeyType::MOUSE_R, fb | 1 << 5, 1 << 5);
+ JLO_B_PB(KeyType::MOUSE_L, fb | 1 << 4, 1 << 4);
+ JLO_B_PB(KeyType::MOUSE_R, fb | 1 << 5, 1 << 5);
// Accessible without any modifier pressed
- JLO_B_PB(KeyType::JUMP, bm | 1 << 0, 1 << 0);
- JLO_B_PB(KeyType::SPECIAL1, bm | 1 << 1, 1 << 1);
+ JLO_B_PB(KeyType::JUMP, bm | 1 << 0, 1 << 0);
+ JLO_B_PB(KeyType::SPECIAL1, bm | 1 << 1, 1 << 1);
// Accessible with start button not pressed, but four pressed
// TODO find usage for button 0
- JLO_B_PB(KeyType::DROP, bm | 1 << 1, fb | 1 << 1);
- JLO_B_PB(KeyType::SCROLL_UP, bm | 1 << 4, fb | 1 << 4);
- JLO_B_PB(KeyType::SCROLL_DOWN, bm | 1 << 5, fb | 1 << 5);
+ JLO_B_PB(KeyType::DROP, bm | 1 << 1, fb | 1 << 1);
+ JLO_B_PB(KeyType::SCROLL_UP, bm | 1 << 4, fb | 1 << 4);
+ JLO_B_PB(KeyType::SCROLL_DOWN,bm | 1 << 5, fb | 1 << 5);
// Accessible with start button and four pressed
// TODO find usage for buttons 0, 1 and 4, 5
@@ -93,13 +93,13 @@ JoystickLayout create_default_layout()
// Now about the buttons simulated by the axes
// Movement buttons, important for vessels
- JLO_A_PB(KeyType::FORWARD, 1, 1, 1024);
+ JLO_A_PB(KeyType::FORWARD, 1, 1, 1024);
JLO_A_PB(KeyType::BACKWARD, 1, -1, 1024);
- JLO_A_PB(KeyType::LEFT, 0, 1, 1024);
- JLO_A_PB(KeyType::RIGHT, 0, -1, 1024);
+ JLO_A_PB(KeyType::LEFT, 0, 1, 1024);
+ JLO_A_PB(KeyType::RIGHT, 0, -1, 1024);
// Scroll buttons
- JLO_A_PB(KeyType::SCROLL_UP, 2, -1, 1024);
+ JLO_A_PB(KeyType::SCROLL_UP, 2, -1, 1024);
JLO_A_PB(KeyType::SCROLL_DOWN, 5, -1, 1024);
return jlo;
@@ -112,44 +112,44 @@ JoystickLayout create_xbox_layout()
jlo.axes_dead_border = 7000;
const JoystickAxisLayout axes[JA_COUNT] = {
- {0, 1}, // JA_SIDEWARD_MOVE
- {1, 1}, // JA_FORWARD_MOVE
- {2, 1}, // JA_FRUSTUM_HORIZONTAL
- {3, 1}, // JA_FRUSTUM_VERTICAL
+ {0, 1}, // JA_SIDEWARD_MOVE
+ {1, 1}, // JA_FORWARD_MOVE
+ {2, 1}, // JA_FRUSTUM_HORIZONTAL
+ {3, 1}, // JA_FRUSTUM_VERTICAL
};
memcpy(jlo.axes, axes, sizeof(jlo.axes));
// The back button means "ESC".
- JLO_B_PB(KeyType::ESC, 1 << 8, 1 << 8); // back
- JLO_B_PB(KeyType::ESC, 1 << 9, 1 << 9); // start
+ JLO_B_PB(KeyType::ESC, 1 << 8, 1 << 8); // back
+ JLO_B_PB(KeyType::ESC, 1 << 9, 1 << 9); // start
// 4 Buttons
- JLO_B_PB(KeyType::JUMP, 1 << 0, 1 << 0); // A/green
- JLO_B_PB(KeyType::ESC, 1 << 1, 1 << 1); // B/red
- JLO_B_PB(KeyType::SPECIAL1, 1 << 2, 1 << 2); // X/blue
- JLO_B_PB(KeyType::INVENTORY, 1 << 3, 1 << 3); // Y/yellow
+ JLO_B_PB(KeyType::JUMP, 1 << 0, 1 << 0); // A/green
+ JLO_B_PB(KeyType::ESC, 1 << 1, 1 << 1); // B/red
+ JLO_B_PB(KeyType::SPECIAL1, 1 << 2, 1 << 2); // X/blue
+ JLO_B_PB(KeyType::INVENTORY, 1 << 3, 1 << 3); // Y/yellow
// Analog Sticks
- JLO_B_PB(KeyType::SPECIAL1, 1 << 11, 1 << 11); // left
- JLO_B_PB(KeyType::SNEAK, 1 << 12, 1 << 12); // right
+ JLO_B_PB(KeyType::SPECIAL1, 1 << 11, 1 << 11); // left
+ JLO_B_PB(KeyType::SNEAK, 1 << 12, 1 << 12); // right
// Triggers
- JLO_B_PB(KeyType::MOUSE_L, 1 << 6, 1 << 6); // lt
- JLO_B_PB(KeyType::MOUSE_R, 1 << 7, 1 << 7); // rt
- JLO_B_PB(KeyType::SCROLL_UP, 1 << 4, 1 << 4); // lb
- JLO_B_PB(KeyType::SCROLL_DOWN, 1 << 5, 1 << 5); // rb
+ JLO_B_PB(KeyType::MOUSE_L, 1 << 6, 1 << 6); // lt
+ JLO_B_PB(KeyType::MOUSE_R, 1 << 7, 1 << 7); // rt
+ JLO_B_PB(KeyType::SCROLL_UP, 1 << 4, 1 << 4); // lb
+ JLO_B_PB(KeyType::SCROLL_DOWN, 1 << 5, 1 << 5); // rb
// D-PAD
- JLO_B_PB(KeyType::ZOOM, 1 << 15, 1 << 15); // up
- JLO_B_PB(KeyType::DROP, 1 << 13, 1 << 13); // left
- JLO_B_PB(KeyType::SCREENSHOT, 1 << 14, 1 << 14); // right
- JLO_B_PB(KeyType::FREEMOVE, 1 << 16, 1 << 16); // down
+ JLO_B_PB(KeyType::ZOOM, 1 << 15, 1 << 15); // up
+ JLO_B_PB(KeyType::DROP, 1 << 13, 1 << 13); // left
+ JLO_B_PB(KeyType::SCREENSHOT, 1 << 14, 1 << 14); // right
+ JLO_B_PB(KeyType::FREEMOVE, 1 << 16, 1 << 16); // down
// Movement buttons, important for vessels
- JLO_A_PB(KeyType::FORWARD, 1, 1, 1024);
+ JLO_A_PB(KeyType::FORWARD, 1, 1, 1024);
JLO_A_PB(KeyType::BACKWARD, 1, -1, 1024);
- JLO_A_PB(KeyType::LEFT, 0, 1, 1024);
- JLO_A_PB(KeyType::RIGHT, 0, -1, 1024);
+ JLO_A_PB(KeyType::LEFT, 0, 1, 1024);
+ JLO_A_PB(KeyType::RIGHT, 0, -1, 1024);
return jlo;
}
@@ -163,10 +163,9 @@ JoystickController::JoystickController() :
clear();
}
-void JoystickController::onJoystickConnect(
- const std::vector<irr::SJoystickInfo> &joystick_infos)
+void JoystickController::onJoystickConnect(const std::vector<irr::SJoystickInfo> &joystick_infos)
{
- s32 id = g_settings->getS32("joystick_id");
+ s32 id = g_settings->getS32("joystick_id");
std::string layout = g_settings->get("joystick_type");
if (id < 0 || (u16)id >= joystick_infos.size()) {
@@ -221,9 +220,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev)
for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
if (keys_pressed[i]) {
if (!m_past_pressed_keys[i] &&
- m_past_pressed_time[i] <
- m_internal_time -
- doubling_dtime) {
+ m_past_pressed_time[i] < m_internal_time - doubling_dtime) {
m_past_pressed_keys[i] = true;
m_past_pressed_time[i] = m_internal_time;
}
@@ -239,6 +236,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev)
m_axes_vals[i] = ax_la.invert * ev.Axis[ax_la.axis_id];
}
+
return true;
}
diff --git a/src/client/joystick_controller.h b/src/client/joystick_controller.h
index ea0833561..7baacd81b 100644
--- a/src/client/joystick_controller.h
+++ b/src/client/joystick_controller.h
@@ -24,8 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <bitset>
#include <vector>
-enum JoystickAxis
-{
+enum JoystickAxis {
JA_SIDEWARD_MOVE,
JA_FORWARD_MOVE,
@@ -36,28 +35,27 @@ enum JoystickAxis
JA_COUNT,
};
-struct JoystickAxisLayout
-{
+struct JoystickAxisLayout {
u16 axis_id;
// -1 if to invert, 1 if to keep it.
int invert;
};
-struct JoystickCombination
-{
- virtual bool isTriggered(const irr::SEvent::SJoystickEvent &ev) const = 0;
+struct JoystickCombination {
+
+ virtual bool isTriggered(const irr::SEvent::SJoystickEvent &ev) const=0;
GameKeyType key;
};
-struct JoystickButtonCmb : public JoystickCombination
-{
+struct JoystickButtonCmb : public JoystickCombination {
JoystickButtonCmb() = default;
JoystickButtonCmb(GameKeyType key, u32 filter_mask, u32 compare_mask) :
- filter_mask(filter_mask), compare_mask(compare_mask)
+ filter_mask(filter_mask),
+ compare_mask(compare_mask)
{
this->key = key;
}
@@ -70,14 +68,14 @@ struct JoystickButtonCmb : public JoystickCombination
u32 compare_mask;
};
-struct JoystickAxisCmb : public JoystickCombination
-{
+struct JoystickAxisCmb : public JoystickCombination {
JoystickAxisCmb() = default;
JoystickAxisCmb(GameKeyType key, u16 axis_to_compare, int direction, s16 thresh) :
- axis_to_compare(axis_to_compare), direction(direction),
- thresh(thresh)
+ axis_to_compare(axis_to_compare),
+ direction(direction),
+ thresh(thresh)
{
this->key = key;
}
@@ -94,16 +92,14 @@ struct JoystickAxisCmb : public JoystickCombination
s16 thresh;
};
-struct JoystickLayout
-{
+struct JoystickLayout {
std::vector<JoystickButtonCmb> button_keys;
std::vector<JoystickAxisCmb> axis_keys;
JoystickAxisLayout axes[JA_COUNT];
s16 axes_dead_border;
};
-class JoystickController
-{
+class JoystickController {
public:
JoystickController();
@@ -119,8 +115,14 @@ public:
m_past_pressed_keys[b] = false;
return r;
}
- bool getWasKeyDown(GameKeyType b) { return m_past_pressed_keys[b]; }
- void clearWasKeyDown(GameKeyType b) { m_past_pressed_keys[b] = false; }
+ bool getWasKeyDown(GameKeyType b)
+ {
+ return m_past_pressed_keys[b];
+ }
+ void clearWasKeyDown(GameKeyType b)
+ {
+ m_past_pressed_keys[b] = false;
+ }
bool wasKeyReleased(GameKeyType b)
{
@@ -128,12 +130,24 @@ public:
m_past_released_keys[b] = false;
return r;
}
- bool getWasKeyReleased(GameKeyType b) { return m_past_pressed_keys[b]; }
- void clearWasKeyReleased(GameKeyType b) { m_past_pressed_keys[b] = false; }
+ bool getWasKeyReleased(GameKeyType b)
+ {
+ return m_past_pressed_keys[b];
+ }
+ void clearWasKeyReleased(GameKeyType b)
+ {
+ m_past_pressed_keys[b] = false;
+ }
- bool isKeyDown(GameKeyType b) { return m_pressed_keys[b]; }
+ bool isKeyDown(GameKeyType b)
+ {
+ return m_pressed_keys[b];
+ }
- s16 getAxis(JoystickAxis axis) { return m_axes_vals[axis]; }
+ s16 getAxis(JoystickAxis axis)
+ {
+ return m_axes_vals[axis];
+ }
s16 getAxisWithoutDead(JoystickAxis axis);
diff --git a/src/client/keycode.cpp b/src/client/keycode.cpp
index bbd269e81..6a0e9f569 100644
--- a/src/client/keycode.cpp
+++ b/src/client/keycode.cpp
@@ -29,182 +29,224 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class UnknownKeycode : public BaseException
{
public:
- UnknownKeycode(const char *s) : BaseException(s){};
+ UnknownKeycode(const char *s) :
+ BaseException(s) {};
};
-struct table_key
-{
+struct table_key {
const char *Name;
irr::EKEY_CODE Key;
- wchar_t Char; // L'\0' means no character assigned
+ wchar_t Char; // L'\0' means no character assigned
const char *LangName; // NULL means it doesn't have a human description
};
-#define DEFINEKEY1(x, lang) /* Irrlicht key without character */ \
- {#x, irr::x, L'\0', lang},
-#define DEFINEKEY2(x, ch, lang) /* Irrlicht key with character */ {#x, irr::x, ch, lang},
-#define DEFINEKEY3(ch) /* single Irrlicht key (e.g. KEY_KEY_X) */ \
- {"KEY_KEY_" TOSTRING(ch), irr::KEY_KEY_##ch, (wchar_t)*TOSTRING(ch), \
- TOSTRING(ch)},
-#define DEFINEKEY4(ch) /* single Irrlicht function key (e.g. KEY_F3) */ \
- {"KEY_F" TOSTRING(ch), irr::KEY_F##ch, L'\0', "F" TOSTRING(ch)},
-#define DEFINEKEY5(ch) /* key without Irrlicht keycode */ \
- {ch, irr::KEY_KEY_CODES_COUNT, (wchar_t)*ch, ch},
+#define DEFINEKEY1(x, lang) /* Irrlicht key without character */ \
+ { #x, irr::x, L'\0', lang },
+#define DEFINEKEY2(x, ch, lang) /* Irrlicht key with character */ \
+ { #x, irr::x, ch, lang },
+#define DEFINEKEY3(ch) /* single Irrlicht key (e.g. KEY_KEY_X) */ \
+ { "KEY_KEY_" TOSTRING(ch), irr::KEY_KEY_ ## ch, (wchar_t) *TOSTRING(ch), TOSTRING(ch) },
+#define DEFINEKEY4(ch) /* single Irrlicht function key (e.g. KEY_F3) */ \
+ { "KEY_F" TOSTRING(ch), irr::KEY_F ## ch, L'\0', "F" TOSTRING(ch) },
+#define DEFINEKEY5(ch) /* key without Irrlicht keycode */ \
+ { ch, irr::KEY_KEY_CODES_COUNT, (wchar_t) *ch, ch },
#define N_(text) text
static const struct table_key table[] = {
- // Keys that can be reliably mapped between Char and Key
- DEFINEKEY3(0) DEFINEKEY3(1) DEFINEKEY3(2) DEFINEKEY3(3) DEFINEKEY3(4) DEFINEKEY3(5) DEFINEKEY3(
- 6) DEFINEKEY3(7) DEFINEKEY3(8) DEFINEKEY3(9) DEFINEKEY3(A) DEFINEKEY3(B) DEFINEKEY3(C)
- DEFINEKEY3(D) DEFINEKEY3(E) DEFINEKEY3(F) DEFINEKEY3(G) DEFINEKEY3(H) DEFINEKEY3(
- I) DEFINEKEY3(J) DEFINEKEY3(K) DEFINEKEY3(L) DEFINEKEY3(M)
- DEFINEKEY3(N) DEFINEKEY3(O) DEFINEKEY3(P) DEFINEKEY3(Q) DEFINEKEY3(
- R) DEFINEKEY3(S) DEFINEKEY3(T) DEFINEKEY3(U)
- DEFINEKEY3(V) DEFINEKEY3(W) DEFINEKEY3(X) DEFINEKEY3(
- Y) DEFINEKEY3(Z) DEFINEKEY2(KEY_PLUS,
- L'+',
- "+") DEFINEKEY2(KEY_COMMA,
- L',',
- ",") DEFINEKEY2(KEY_MINUS,
- L'-',
- "-") DEFINEKEY2(KEY_PERIOD,
- L'.', ".")
-
- // Keys without a Char
- DEFINEKEY1(KEY_LBUTTON, N_("Left Button")) DEFINEKEY1(
- KEY_RBUTTON, N_("Right Button")) DEFINEKEY1(KEY_CANCEL,
- N_("Cancel")) DEFINEKEY1(KEY_MBUTTON,
- N_("Middle Button")) DEFINEKEY1(KEY_XBUTTON1,
- N_("X Button 1")) DEFINEKEY1(KEY_XBUTTON2,
- N_("X Button 2")) DEFINEKEY1(KEY_BACK,
- N_("Backspace")) DEFINEKEY1(KEY_TAB,
- N_("Tab")) DEFINEKEY1(KEY_CLEAR, N_("Clear"))
- DEFINEKEY1(KEY_RETURN, N_("Return")) DEFINEKEY1(
- KEY_SHIFT, N_("Shift"))
- DEFINEKEY1(KEY_CONTROL, N_("Control"))
- //~ Key name, common on Windows keyboards
- DEFINEKEY1(KEY_MENU, N_("Menu")) DEFINEKEY1(
- KEY_PAUSE, N_("Pause")) DEFINEKEY1(KEY_CAPITAL,
- N_("Caps Lock")) DEFINEKEY1(KEY_SPACE,
- N_("Space")) DEFINEKEY1(KEY_PRIOR, N_("Page up"))
- DEFINEKEY1(KEY_NEXT, N_("Page down")) DEFINEKEY1(
- KEY_END, N_("End")) DEFINEKEY1(KEY_HOME,
- N_("Home")) DEFINEKEY1(KEY_LEFT,
- N_("Left")) DEFINEKEY1(KEY_UP,
- N_("Up")) DEFINEKEY1(KEY_RIGHT,
- N_("Right"))
- DEFINEKEY1(KEY_DOWN, N_("Down"))
- //~ Key name
- DEFINEKEY1(KEY_SELECT, N_("Select"))
- //~ "Print screen" key
- DEFINEKEY1(KEY_PRINT, N_("Print")) DEFINEKEY1(
- KEY_EXECUT, N_("Execute")) DEFINEKEY1(KEY_SNAPSHOT,
- N_("Snapshot")) DEFINEKEY1(KEY_INSERT,
- N_("Insert")) DEFINEKEY1(KEY_DELETE,
- N_("Delete")) DEFINEKEY1(KEY_HELP,
- N_("Help")) DEFINEKEY1(KEY_LWIN,
- N_("Left Windows")) DEFINEKEY1(KEY_RWIN,
- N_("Right Windows")) DEFINEKEY1(KEY_NUMPAD0,
- N_("Numpad 0")) // These are not assigned to a char
- DEFINEKEY1(KEY_NUMPAD1, N_("Numpad 1")) // to prevent interference with
- // KEY_KEY_[0-9].
- DEFINEKEY1(KEY_NUMPAD2, N_("Numpad 2")) DEFINEKEY1(
- KEY_NUMPAD3, N_("Numpad 3")) DEFINEKEY1(KEY_NUMPAD4,
- N_("Numpad 4")) DEFINEKEY1(KEY_NUMPAD5,
- N_("Numpad 5")) DEFINEKEY1(KEY_NUMPAD6,
- N_("Numpad 6")) DEFINEKEY1(KEY_NUMPAD7,
- N_("Numpad 7")) DEFINEKEY1(KEY_NUMPAD8,
- N_("Numpad 8")) DEFINEKEY1(KEY_NUMPAD9,
- N_("Numpad 9")) DEFINEKEY1(KEY_MULTIPLY,
- N_("Numpad *")) DEFINEKEY1(KEY_ADD,
- N_("Numpad +")) DEFINEKEY1(KEY_SEPARATOR,
- N_("Numpad .")) DEFINEKEY1(KEY_SUBTRACT,
- N_("Numpad -")) DEFINEKEY1(KEY_DECIMAL,
- NULL) DEFINEKEY1(KEY_DIVIDE,
- N_("Numpad /")) DEFINEKEY4(1) DEFINEKEY4(2) DEFINEKEY4(3) DEFINEKEY4(4)
- DEFINEKEY4(5) DEFINEKEY4(6) DEFINEKEY4(7) DEFINEKEY4(8) DEFINEKEY4(9) DEFINEKEY4(
- 10) DEFINEKEY4(11) DEFINEKEY4(12) DEFINEKEY4(13) DEFINEKEY4(14)
- DEFINEKEY4(15) DEFINEKEY4(16) DEFINEKEY4(17) DEFINEKEY4(
- 18) DEFINEKEY4(19) DEFINEKEY4(20) DEFINEKEY4(21)
- DEFINEKEY4(22) DEFINEKEY4(23) DEFINEKEY4(
- 24) DEFINEKEY1(KEY_NUMLOCK,
- N_("Num "
- "Loc"
- "k")) DEFINEKEY1(KEY_SCROLL,
- N_("Scrol"
- "l "
- "Loc"
- "k")) DEFINEKEY1(KEY_LSHIFT,
- N_("Left "
- "Shif"
- "t")) DEFINEKEY1(KEY_RSHIFT,
- N_("Right"
- " Shif"
- "t")) DEFINEKEY1(KEY_LCONTROL,
- N_("Left "
- "Contr"
- "ol")) DEFINEKEY1(KEY_RCONTROL,
- N_("Right"
- " Cont"
- "rol")) DEFINEKEY1(KEY_LMENU,
- N_("Left "
- "Men"
- "u")) DEFINEKEY1(KEY_RMENU,
- N_("Right"
- " Men"
- "u"))
-
- // Rare/weird keys
- DEFINEKEY1(KEY_KANA, "Kana") DEFINEKEY1(KEY_HANGUEL, "Hangul") DEFINEKEY1(
- KEY_HANGUL, "Hangul") DEFINEKEY1(KEY_JUNJA,
- "Junja") DEFINEKEY1(KEY_FINAL,
- "Final") DEFINEKEY1(KEY_KANJI,
- "Kanji") DEFINEKEY1(KEY_HANJA,
- "Hanja") DEFINEKEY1(KEY_ESCAPE,
- N_("IME Escape")) DEFINEKEY1(KEY_CONVERT,
- N_("IME Convert")) DEFINEKEY1(KEY_NONCONVERT,
- N_("IME Nonconvert")) DEFINEKEY1(KEY_ACCEPT,
- N_("IME Accept")) DEFINEKEY1(KEY_MODECHANGE,
- N_("IME Mode Change")) DEFINEKEY1(KEY_APPS,
- N_("Apps")) DEFINEKEY1(KEY_SLEEP, N_("Sleep"))
-#if !(IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 7 && \
- IRRLICHT_VERSION_REVISION < 3)
- DEFINEKEY1(KEY_OEM_1,
- "OEM 1") // KEY_OEM_[0-9] and KEY_OEM_102
- // are assigned to multiple
- DEFINEKEY1(KEY_OEM_2, "OEM 2") // different chars (on different platforms
- // too) and thus w/o char
- DEFINEKEY1(KEY_OEM_3, "OEM 3") DEFINEKEY1(KEY_OEM_4, "OEM 4") DEFINEKEY1(
- KEY_OEM_5, "OEM 5") DEFINEKEY1(KEY_OEM_6,
- "OEM 6") DEFINEKEY1(KEY_OEM_7,
- "OEM 7") DEFINEKEY1(KEY_OEM_8,
- "OEM 8") DEFINEKEY1(KEY_OEM_AX,
- "OEM AX") DEFINEKEY1(KEY_OEM_102, "OEM 102")
+ // Keys that can be reliably mapped between Char and Key
+ DEFINEKEY3(0)
+ DEFINEKEY3(1)
+ DEFINEKEY3(2)
+ DEFINEKEY3(3)
+ DEFINEKEY3(4)
+ DEFINEKEY3(5)
+ DEFINEKEY3(6)
+ DEFINEKEY3(7)
+ DEFINEKEY3(8)
+ DEFINEKEY3(9)
+ DEFINEKEY3(A)
+ DEFINEKEY3(B)
+ DEFINEKEY3(C)
+ DEFINEKEY3(D)
+ DEFINEKEY3(E)
+ DEFINEKEY3(F)
+ DEFINEKEY3(G)
+ DEFINEKEY3(H)
+ DEFINEKEY3(I)
+ DEFINEKEY3(J)
+ DEFINEKEY3(K)
+ DEFINEKEY3(L)
+ DEFINEKEY3(M)
+ DEFINEKEY3(N)
+ DEFINEKEY3(O)
+ DEFINEKEY3(P)
+ DEFINEKEY3(Q)
+ DEFINEKEY3(R)
+ DEFINEKEY3(S)
+ DEFINEKEY3(T)
+ DEFINEKEY3(U)
+ DEFINEKEY3(V)
+ DEFINEKEY3(W)
+ DEFINEKEY3(X)
+ DEFINEKEY3(Y)
+ DEFINEKEY3(Z)
+ DEFINEKEY2(KEY_PLUS, L'+', "+")
+ DEFINEKEY2(KEY_COMMA, L',', ",")
+ DEFINEKEY2(KEY_MINUS, L'-', "-")
+ DEFINEKEY2(KEY_PERIOD, L'.', ".")
+
+ // Keys without a Char
+ DEFINEKEY1(KEY_LBUTTON, N_("Left Button"))
+ DEFINEKEY1(KEY_RBUTTON, N_("Right Button"))
+ DEFINEKEY1(KEY_CANCEL, N_("Cancel"))
+ DEFINEKEY1(KEY_MBUTTON, N_("Middle Button"))
+ DEFINEKEY1(KEY_XBUTTON1, N_("X Button 1"))
+ DEFINEKEY1(KEY_XBUTTON2, N_("X Button 2"))
+ DEFINEKEY1(KEY_BACK, N_("Backspace"))
+ DEFINEKEY1(KEY_TAB, N_("Tab"))
+ DEFINEKEY1(KEY_CLEAR, N_("Clear"))
+ DEFINEKEY1(KEY_RETURN, N_("Return"))
+ DEFINEKEY1(KEY_SHIFT, N_("Shift"))
+ DEFINEKEY1(KEY_CONTROL, N_("Control"))
+ //~ Key name, common on Windows keyboards
+ DEFINEKEY1(KEY_MENU, N_("Menu"))
+ DEFINEKEY1(KEY_PAUSE, N_("Pause"))
+ DEFINEKEY1(KEY_CAPITAL, N_("Caps Lock"))
+ DEFINEKEY1(KEY_SPACE, N_("Space"))
+ DEFINEKEY1(KEY_PRIOR, N_("Page up"))
+ DEFINEKEY1(KEY_NEXT, N_("Page down"))
+ DEFINEKEY1(KEY_END, N_("End"))
+ DEFINEKEY1(KEY_HOME, N_("Home"))
+ DEFINEKEY1(KEY_LEFT, N_("Left"))
+ DEFINEKEY1(KEY_UP, N_("Up"))
+ DEFINEKEY1(KEY_RIGHT, N_("Right"))
+ DEFINEKEY1(KEY_DOWN, N_("Down"))
+ //~ Key name
+ DEFINEKEY1(KEY_SELECT, N_("Select"))
+ //~ "Print screen" key
+ DEFINEKEY1(KEY_PRINT, N_("Print"))
+ DEFINEKEY1(KEY_EXECUT, N_("Execute"))
+ DEFINEKEY1(KEY_SNAPSHOT, N_("Snapshot"))
+ DEFINEKEY1(KEY_INSERT, N_("Insert"))
+ DEFINEKEY1(KEY_DELETE, N_("Delete"))
+ DEFINEKEY1(KEY_HELP, N_("Help"))
+ DEFINEKEY1(KEY_LWIN, N_("Left Windows"))
+ DEFINEKEY1(KEY_RWIN, N_("Right Windows"))
+ DEFINEKEY1(KEY_NUMPAD0, N_("Numpad 0")) // These are not assigned to a char
+ DEFINEKEY1(KEY_NUMPAD1, N_("Numpad 1")) // to prevent interference with KEY_KEY_[0-9].
+ DEFINEKEY1(KEY_NUMPAD2, N_("Numpad 2"))
+ DEFINEKEY1(KEY_NUMPAD3, N_("Numpad 3"))
+ DEFINEKEY1(KEY_NUMPAD4, N_("Numpad 4"))
+ DEFINEKEY1(KEY_NUMPAD5, N_("Numpad 5"))
+ DEFINEKEY1(KEY_NUMPAD6, N_("Numpad 6"))
+ DEFINEKEY1(KEY_NUMPAD7, N_("Numpad 7"))
+ DEFINEKEY1(KEY_NUMPAD8, N_("Numpad 8"))
+ DEFINEKEY1(KEY_NUMPAD9, N_("Numpad 9"))
+ DEFINEKEY1(KEY_MULTIPLY, N_("Numpad *"))
+ DEFINEKEY1(KEY_ADD, N_("Numpad +"))
+ DEFINEKEY1(KEY_SEPARATOR, N_("Numpad ."))
+ DEFINEKEY1(KEY_SUBTRACT, N_("Numpad -"))
+ DEFINEKEY1(KEY_DECIMAL, NULL)
+ DEFINEKEY1(KEY_DIVIDE, N_("Numpad /"))
+ DEFINEKEY4(1)
+ DEFINEKEY4(2)
+ DEFINEKEY4(3)
+ DEFINEKEY4(4)
+ DEFINEKEY4(5)
+ DEFINEKEY4(6)
+ DEFINEKEY4(7)
+ DEFINEKEY4(8)
+ DEFINEKEY4(9)
+ DEFINEKEY4(10)
+ DEFINEKEY4(11)
+ DEFINEKEY4(12)
+ DEFINEKEY4(13)
+ DEFINEKEY4(14)
+ DEFINEKEY4(15)
+ DEFINEKEY4(16)
+ DEFINEKEY4(17)
+ DEFINEKEY4(18)
+ DEFINEKEY4(19)
+ DEFINEKEY4(20)
+ DEFINEKEY4(21)
+ DEFINEKEY4(22)
+ DEFINEKEY4(23)
+ DEFINEKEY4(24)
+ DEFINEKEY1(KEY_NUMLOCK, N_("Num Lock"))
+ DEFINEKEY1(KEY_SCROLL, N_("Scroll Lock"))
+ DEFINEKEY1(KEY_LSHIFT, N_("Left Shift"))
+ DEFINEKEY1(KEY_RSHIFT, N_("Right Shift"))
+ DEFINEKEY1(KEY_LCONTROL, N_("Left Control"))
+ DEFINEKEY1(KEY_RCONTROL, N_("Right Control"))
+ DEFINEKEY1(KEY_LMENU, N_("Left Menu"))
+ DEFINEKEY1(KEY_RMENU, N_("Right Menu"))
+
+ // Rare/weird keys
+ DEFINEKEY1(KEY_KANA, "Kana")
+ DEFINEKEY1(KEY_HANGUEL, "Hangul")
+ DEFINEKEY1(KEY_HANGUL, "Hangul")
+ DEFINEKEY1(KEY_JUNJA, "Junja")
+ DEFINEKEY1(KEY_FINAL, "Final")
+ DEFINEKEY1(KEY_KANJI, "Kanji")
+ DEFINEKEY1(KEY_HANJA, "Hanja")
+ DEFINEKEY1(KEY_ESCAPE, N_("IME Escape"))
+ DEFINEKEY1(KEY_CONVERT, N_("IME Convert"))
+ DEFINEKEY1(KEY_NONCONVERT, N_("IME Nonconvert"))
+ DEFINEKEY1(KEY_ACCEPT, N_("IME Accept"))
+ DEFINEKEY1(KEY_MODECHANGE, N_("IME Mode Change"))
+ DEFINEKEY1(KEY_APPS, N_("Apps"))
+ DEFINEKEY1(KEY_SLEEP, N_("Sleep"))
+#if !(IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 7 && IRRLICHT_VERSION_REVISION < 3)
+ DEFINEKEY1(KEY_OEM_1, "OEM 1") // KEY_OEM_[0-9] and KEY_OEM_102 are assigned to multiple
+ DEFINEKEY1(KEY_OEM_2, "OEM 2") // different chars (on different platforms too) and thus w/o char
+ DEFINEKEY1(KEY_OEM_3, "OEM 3")
+ DEFINEKEY1(KEY_OEM_4, "OEM 4")
+ DEFINEKEY1(KEY_OEM_5, "OEM 5")
+ DEFINEKEY1(KEY_OEM_6, "OEM 6")
+ DEFINEKEY1(KEY_OEM_7, "OEM 7")
+ DEFINEKEY1(KEY_OEM_8, "OEM 8")
+ DEFINEKEY1(KEY_OEM_AX, "OEM AX")
+ DEFINEKEY1(KEY_OEM_102, "OEM 102")
#endif
- DEFINEKEY1(KEY_ATTN, "Attn") DEFINEKEY1(
- KEY_CRSEL, "CrSel") DEFINEKEY1(KEY_EXSEL,
- "ExSel") DEFINEKEY1(KEY_EREOF,
- N_("Erase EOF")) DEFINEKEY1(KEY_PLAY,
- N_("Play")) DEFINEKEY1(KEY_ZOOM,
- N_("Zoom")) DEFINEKEY1(KEY_PA1, "PA1")
- DEFINEKEY1(KEY_OEM_CLEAR, N_("OEM Clear"))
-
- // Keys without Irrlicht keycode
- DEFINEKEY5("!") DEFINEKEY5("\"") DEFINEKEY5("#") DEFINEKEY5(
- "$") DEFINEKEY5("%") DEFINEKEY5("&") DEFINEKEY5("'")
- DEFINEKEY5("(") DEFINEKEY5(")") DEFINEKEY5(
- "*") DEFINEKEY5("/") DEFINEKEY5(":")
- DEFINEKEY5(";") DEFINEKEY5("<") DEFINEKEY5(
- "=") DEFINEKEY5(">")
- DEFINEKEY5("?") DEFINEKEY5("@") DEFINEKEY5(
- "[") DEFINEKEY5("\\")
- DEFINEKEY5("]") DEFINEKEY5(
- "^")
- DEFINEKEY5("_")};
+ DEFINEKEY1(KEY_ATTN, "Attn")
+ DEFINEKEY1(KEY_CRSEL, "CrSel")
+ DEFINEKEY1(KEY_EXSEL, "ExSel")
+ DEFINEKEY1(KEY_EREOF, N_("Erase EOF"))
+ DEFINEKEY1(KEY_PLAY, N_("Play"))
+ DEFINEKEY1(KEY_ZOOM, N_("Zoom"))
+ DEFINEKEY1(KEY_PA1, "PA1")
+ DEFINEKEY1(KEY_OEM_CLEAR, N_("OEM Clear"))
+
+ // Keys without Irrlicht keycode
+ DEFINEKEY5("!")
+ DEFINEKEY5("\"")
+ DEFINEKEY5("#")
+ DEFINEKEY5("$")
+ DEFINEKEY5("%")
+ DEFINEKEY5("&")
+ DEFINEKEY5("'")
+ DEFINEKEY5("(")
+ DEFINEKEY5(")")
+ DEFINEKEY5("*")
+ DEFINEKEY5("/")
+ DEFINEKEY5(":")
+ DEFINEKEY5(";")
+ DEFINEKEY5("<")
+ DEFINEKEY5("=")
+ DEFINEKEY5(">")
+ DEFINEKEY5("?")
+ DEFINEKEY5("@")
+ DEFINEKEY5("[")
+ DEFINEKEY5("\\")
+ DEFINEKEY5("]")
+ DEFINEKEY5("^")
+ DEFINEKEY5("_")
+};
#undef N_
+
struct table_key lookup_keyname(const char *name)
{
for (const auto &table_key : table) {
@@ -223,7 +265,7 @@ struct table_key lookup_keykey(irr::EKEY_CODE key)
}
std::ostringstream os;
- os << "<Keycode " << (int)key << ">";
+ os << "<Keycode " << (int) key << ">";
throw UnknownKeycode(os.str().c_str());
}
@@ -235,7 +277,7 @@ struct table_key lookup_keychar(wchar_t Char)
}
std::ostringstream os;
- os << "<Char " << hex_encode((char *)&Char, sizeof(wchar_t)) << ">";
+ os << "<Char " << hex_encode((char*) &Char, sizeof(wchar_t)) << ">";
throw UnknownKeycode(os.str().c_str());
}
@@ -257,8 +299,7 @@ KeyPress::KeyPress(const char *name)
m_name = k.Name;
Key = k.Key;
return;
- } catch (UnknownKeycode &e) {
- };
+ } catch (UnknownKeycode &e) {};
} else {
// Lookup by name
m_name = name;
@@ -267,8 +308,7 @@ KeyPress::KeyPress(const char *name)
Key = k.Key;
Char = k.Char;
return;
- } catch (UnknownKeycode &e) {
- };
+ } catch (UnknownKeycode &e) {};
}
// It's not a known key, complain and try to do something
@@ -276,8 +316,7 @@ KeyPress::KeyPress(const char *name)
int chars_read = mbtowc(&Char, name, 1);
FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character");
m_name = "";
- warningstream << "KeyPress: Unknown key '" << name
- << "', falling back to first char.";
+ warningstream << "KeyPress: Unknown key '" << name << "', falling back to first char.";
}
KeyPress::KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character)
diff --git a/src/client/keys.h b/src/client/keys.h
index e288ecda0..43a032a7b 100644
--- a/src/client/keys.h
+++ b/src/client/keys.h
@@ -79,7 +79,7 @@ public:
SELECT_LEFT,
SELECT_RIGHT,
SELECT_CONFIRM,
-
+
QUICKTUNE_NEXT,
QUICKTUNE_PREV,
QUICKTUNE_INC,
diff --git a/src/client/localplayer.cpp b/src/client/localplayer.cpp
index 324055796..00195cd02 100644
--- a/src/client/localplayer.cpp
+++ b/src/client/localplayer.cpp
@@ -34,8 +34,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
LocalPlayer
*/
-LocalPlayer::LocalPlayer(Client *client, const char *name) :
- Player(name, client->idef()), m_client(client)
+LocalPlayer::LocalPlayer(Client *client, const char *name):
+ Player(name, client->idef()),
+ m_client(client)
{
}
@@ -56,11 +57,20 @@ static aabb3f getNodeBoundingBox(const std::vector<aabb3f> &nodeboxes)
return b_max;
}
-bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &sneak_max)
+bool LocalPlayer::updateSneakNode(Map *map, const v3f &position,
+ const v3f &sneak_max)
{
- static const v3s16 dir9_center[9] = {v3s16(0, 0, 0), v3s16(1, 0, 0),
- v3s16(-1, 0, 0), v3s16(0, 0, 1), v3s16(0, 0, -1), v3s16(1, 0, 1),
- v3s16(-1, 0, 1), v3s16(1, 0, -1), v3s16(-1, 0, -1)};
+ static const v3s16 dir9_center[9] = {
+ v3s16( 0, 0, 0),
+ v3s16( 1, 0, 0),
+ v3s16(-1, 0, 0),
+ v3s16( 0, 0, 1),
+ v3s16( 0, 0, -1),
+ v3s16( 1, 0, 1),
+ v3s16(-1, 0, 1),
+ v3s16( 1, 0, -1),
+ v3s16(-1, 0, -1)
+ };
const NodeDefManager *nodemgr = m_client->ndef();
MapNode node;
@@ -73,8 +83,7 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea
position_y_mod = m_sneak_node_bb_top.MaxEdge.Y - position_y_mod;
// Get position of current standing node
- const v3s16 current_node =
- floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS);
+ const v3s16 current_node = floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS);
if (current_node != m_sneak_node) {
new_sneak_node_exists = false;
@@ -103,19 +112,18 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea
fabs(diff.Y) > (0.5f + 0.1f) * BS + sneak_max.Z)
continue;
+
// The node to be sneaked on has to be walkable
node = map->getNode(p, &is_valid_position);
- if (!is_valid_position || !nodemgr->get(node).walkable)
+ if (!is_valid_position || ! nodemgr->get(node).walkable)
continue;
// And the node(s) above have to be nonwalkable
bool ok = true;
if (!physics_override_sneak_glitch) {
- u16 height = ceilf((m_collisionbox.MaxEdge.Y -
- m_collisionbox.MinEdge.Y) /
- BS);
+ u16 height =
+ ceilf((m_collisionbox.MaxEdge.Y - m_collisionbox.MinEdge.Y) / BS);
for (u16 y = 1; y <= height; y++) {
- node = map->getNode(
- p + v3s16(0, y, 0), &is_valid_position);
+ node = map->getNode(p + v3s16(0, y, 0), &is_valid_position);
if (!is_valid_position || nodemgr->get(node).walkable) {
ok = false;
break;
@@ -124,7 +132,7 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea
} else {
// legacy behaviour: check just one node
node = map->getNode(p + v3s16(0, 1, 0), &is_valid_position);
- ok = is_valid_position && !nodemgr->get(node).walkable;
+ ok = is_valid_position && ! nodemgr->get(node).walkable;
}
if (!ok)
continue;
@@ -146,13 +154,14 @@ bool LocalPlayer::updateSneakNode(Map *map, const v3f &position, const v3f &snea
if (physics_override_sneak_glitch) {
// Detect sneak ladder:
// Node two meters above sneak node must be solid
- node = map->getNode(m_sneak_node + v3s16(0, 2, 0), &is_valid_position);
+ node = map->getNode(m_sneak_node + v3s16(0, 2, 0),
+ &is_valid_position);
if (is_valid_position && nodemgr->get(node).walkable) {
// Node three meters above: must be non-solid
node = map->getNode(m_sneak_node + v3s16(0, 3, 0),
- &is_valid_position);
- m_sneak_ladder_detected =
- is_valid_position && !nodemgr->get(node).walkable;
+ &is_valid_position);
+ m_sneak_ladder_detected = is_valid_position &&
+ ! nodemgr->get(node).walkable;
}
}
return true;
@@ -163,7 +172,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
{
if (m_cao && m_cao->m_waiting_for_reattach > 0)
m_cao->m_waiting_for_reattach -= dtime;
-
+
// Node at feet position, update each ClientEnvironment::step()
if (!collision_info || collision_info->empty())
m_standing_node = floatToInt(m_position, BS);
@@ -218,13 +227,13 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
*/
// If in liquid, the threshold of coming out is at higher y
- if (in_liquid) {
+ if (in_liquid)
+ {
pp = floatToInt(position + v3f(0.0f, BS * 0.1f, 0.0f), BS);
node = map->getNode(pp, &is_valid_position);
if (is_valid_position) {
in_liquid = nodemgr->get(node.getContent()).isLiquid();
- liquid_viscosity =
- nodemgr->get(node.getContent()).liquid_viscosity;
+ liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity;
} else {
in_liquid = false;
}
@@ -235,13 +244,13 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
node = map->getNode(pp, &is_valid_position);
if (is_valid_position) {
in_liquid = nodemgr->get(node.getContent()).isLiquid();
- liquid_viscosity =
- nodemgr->get(node.getContent()).liquid_viscosity;
+ liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity;
} else {
in_liquid = false;
}
}
+
/*
Check if player is in liquid (the stable value)
*/
@@ -267,16 +276,14 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
is_climbing = false;
} else {
is_climbing = (nodemgr->get(node.getContent()).climbable ||
- nodemgr->get(node2.getContent())
- .climbable) &&
- !free_move;
+ nodemgr->get(node2.getContent()).climbable) && !free_move;
}
/*
Collision uncertainty radius
Make it a bit larger than the maximum distance of movement
*/
- // f32 d = pos_max_d * 1.1;
+ //f32 d = pos_max_d * 1.1;
// A fairly large value in here makes moving smoother
f32 d = 0.15f * BS;
@@ -285,21 +292,19 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
// Player object property step height is multiplied by BS in
// /src/script/common/c_content.cpp and /src/content_sao.cpp
- float player_stepheight =
- (m_cao == nullptr) ? 0.0f
- : (touching_ground ? m_cao->getStepHeight()
- : (0.2f * BS));
+ float player_stepheight = (m_cao == nullptr) ? 0.0f :
+ (touching_ground ? m_cao->getStepHeight() : (0.2f * BS));
v3f accel_f;
const v3f initial_position = position;
const v3f initial_speed = m_speed;
- collisionMoveResult result = collisionMoveSimple(env, m_client, pos_max_d,
- m_collisionbox, player_stepheight, dtime, &position, &m_speed,
- accel_f, NULL, true, true);
+ collisionMoveResult result = collisionMoveSimple(env, m_client,
+ pos_max_d, m_collisionbox, player_stepheight, dtime,
+ &position, &m_speed, accel_f, NULL, true, true);
- bool could_sneak = control.sneak && !free_move && !in_liquid && !is_climbing &&
- physics_override_sneak;
+ bool could_sneak = control.sneak && !free_move && !in_liquid &&
+ !is_climbing && physics_override_sneak;
// Add new collisions to the vector
if (collision_info && !free_move) {
@@ -362,10 +367,10 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
// (BS * 0.6f) is the basic stepheight while standing on ground
if (y_diff < BS * 0.6f) {
// Only center player when they're on the node
- position.X = rangelim(position.X, bmin.X - sneak_max.X,
- bmax.X + sneak_max.X);
- position.Z = rangelim(position.Z, bmin.Z - sneak_max.Z,
- bmax.Z + sneak_max.Z);
+ position.X = rangelim(position.X,
+ bmin.X - sneak_max.X, bmax.X + sneak_max.X);
+ position.Z = rangelim(position.Z,
+ bmin.Z - sneak_max.Z, bmax.Z + sneak_max.Z);
if (position.X != old_pos.X)
m_speed.X = 0.0f;
@@ -388,7 +393,8 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
if (m_speed.Y == 0.0f || m_sneak_ladder_detected)
sneak_can_jump = true;
- if (collision_info && m_speed.Y - old_speed.Y > BS) {
+ if (collision_info &&
+ m_speed.Y - old_speed.Y > BS) {
// Collide with sneak node, report fall damage
CollisionInfo sn_info;
sn_info.node_p = m_sneak_node;
@@ -417,8 +423,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
*/
if (!result.standing_on_object && !touching_ground_was && touching_ground) {
- m_client->getEventManager()->put(
- new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND));
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND));
// Set camera impact value to be used for view bobbing
camera_impact = getSpeed().Y * -1;
@@ -438,18 +443,16 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
Check properties of the node on which the player is standing
*/
const ContentFeatures &f = nodemgr->get(map->getNode(m_standing_node));
- const ContentFeatures &f1 =
- nodemgr->get(map->getNode(m_standing_node + v3s16(0, 1, 0)));
+ const ContentFeatures &f1 = nodemgr->get(map->getNode(m_standing_node + v3s16(0, 1, 0)));
// Determine if jumping is possible
m_disable_jump = itemgroup_get(f.groups, "disable_jump") ||
- itemgroup_get(f1.groups, "disable_jump");
- m_can_jump = ((touching_ground && !is_climbing) || sneak_can_jump) &&
- !m_disable_jump;
+ itemgroup_get(f1.groups, "disable_jump");
+ m_can_jump = ((touching_ground && !is_climbing) || sneak_can_jump) && !m_disable_jump;
// Jump key pressed while jumping off from a bouncy block
if (m_can_jump && control.jump && itemgroup_get(f.groups, "bouncy") &&
- m_speed.Y >= -0.5f * BS) {
+ m_speed.Y >= -0.5f * BS) {
float jumpspeed = movement_speed_jump * physics_override_jump;
if (m_speed.Y > 1.0f) {
// Reduce boost when speed already is high
@@ -458,7 +461,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
m_speed.Y += jumpspeed;
}
setSpeed(m_speed);
- if (!m_freecam)
+ if (! m_freecam)
m_legit_speed = m_speed;
m_can_jump = false;
}
@@ -500,8 +503,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
bool free_move = fly_allowed && player_settings.free_move;
bool fast_move = fast_allowed && player_settings.fast_move;
bool pitch_move = (free_move || in_liquid) && player_settings.pitch_move;
- // When aux1_descends is enabled the fast key is used to go down, so fast isn't
- // possible
+ // When aux1_descends is enabled the fast key is used to go down, so fast isn't possible
bool fast_climb = fast_move && control.aux1 && !player_settings.aux1_descends;
bool always_fly_fast = player_settings.always_fly_fast;
@@ -578,8 +580,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
speedH -= v3f(0.0f, 0.0f, 1.0f);
if (!control.up && !control.down)
- speedH -= v3f(0.0f, 0.0f, 1.0f) *
- (control.forw_move_joystick_axis / 32767.f);
+ speedH -= v3f(0.0f, 0.0f, 1.0f) * (control.forw_move_joystick_axis / 32767.f);
if (control.left)
speedH += v3f(-1.0f, 0.0f, 0.0f);
@@ -588,8 +589,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
speedH += v3f(1.0f, 0.0f, 0.0f);
if (!control.left && !control.right)
- speedH += v3f(1.0f, 0.0f, 0.0f) *
- (control.sidew_move_joystick_axis / 32767.f);
+ speedH += v3f(1.0f, 0.0f, 0.0f) * (control.sidew_move_joystick_axis / 32767.f);
if (m_autojump) {
// release autojump after a given time
@@ -621,8 +621,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
if (speedJ.Y >= -0.5f * BS) {
speedJ.Y = movement_speed_jump * physics_override_jump;
setSpeed(speedJ);
- m_client->getEventManager()->put(new SimpleTriggerEvent(
- MtEvent::PLAYER_JUMP));
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_JUMP));
}
} else if (in_liquid && !m_disable_jump) {
if (fast_climb)
@@ -642,8 +641,7 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
if (superspeed || (is_climbing && fast_climb) ||
((in_liquid || in_liquid_stable) && fast_climb))
speedH = speedH.normalize() * movement_speed_fast;
- else if (control.sneak && !free_move && !in_liquid && !in_liquid_stable &&
- !g_settings->getBool("no_slow"))
+ else if (control.sneak && !free_move && !in_liquid && !in_liquid_stable && !g_settings->getBool("no_slow"))
speedH = speedH.normalize() * movement_speed_crouch;
else
speedH = speedH.normalize() * movement_speed_walk;
@@ -679,8 +677,8 @@ void LocalPlayer::applyControl(float dtime, Environment *env)
// Accelerate to target speed with maximum increment
accelerate((speedH + speedV) * physics_override_speed,
- incH * physics_override_speed * slip_factor,
- incV * physics_override_speed, pitch_move);
+ incH * physics_override_speed * slip_factor, incV * physics_override_speed,
+ pitch_move);
}
v3s16 LocalPlayer::getStandingNodePos()
@@ -715,15 +713,13 @@ v3s16 LocalPlayer::getLightPosition() const
v3f LocalPlayer::getEyeOffset() const
{
- float eye_height =
- camera_barely_in_ceiling ? m_eye_height - 0.125f : m_eye_height;
+ float eye_height = camera_barely_in_ceiling ? m_eye_height - 0.125f : m_eye_height;
return v3f(0.0f, BS * eye_height, 0.0f);
}
ClientActiveObject *LocalPlayer::getParent() const
{
- return (m_cao && !g_settings->getBool("entity_speed")) ? m_cao->getParent()
- : nullptr;
+ return (m_cao && ! g_settings->getBool("entity_speed")) ? m_cao->getParent() : nullptr;
}
bool LocalPlayer::isDead() const
@@ -741,19 +737,17 @@ void LocalPlayer::tryReattach(int id)
bool LocalPlayer::isWaitingForReattach() const
{
- return g_settings->getBool("entity_speed") && m_cao && !m_cao->getParent() &&
- m_cao->m_waiting_for_reattach > 0;
+ return g_settings->getBool("entity_speed") && m_cao && ! m_cao->getParent() && m_cao->m_waiting_for_reattach > 0;
}
// 3D acceleration
void LocalPlayer::accelerate(const v3f &target_speed, const f32 max_increase_H,
- const f32 max_increase_V, const bool use_pitch)
+ const f32 max_increase_V, const bool use_pitch)
{
const f32 yaw = getYaw();
const f32 pitch = getPitch();
v3f flat_speed = m_speed;
- // Rotate speed vector by -yaw and -pitch to make it relative to the player's yaw
- // and pitch
+ // Rotate speed vector by -yaw and -pitch to make it relative to the player's yaw and pitch
flat_speed.rotateXZBy(-yaw);
if (use_pitch)
flat_speed.rotateYZBy(-pitch);
@@ -790,7 +784,7 @@ void LocalPlayer::accelerate(const v3f &target_speed, const f32 max_increase_H,
// Temporary option for old move code
void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
- std::vector<CollisionInfo> *collision_info)
+ std::vector<CollisionInfo> *collision_info)
{
Map *map = &env->getMap();
const NodeDefManager *nodemgr = m_client->ndef();
@@ -840,8 +834,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
node = map->getNode(pp, &is_valid_position);
if (is_valid_position) {
in_liquid = nodemgr->get(node.getContent()).isLiquid();
- liquid_viscosity =
- nodemgr->get(node.getContent()).liquid_viscosity;
+ liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity;
} else {
in_liquid = false;
}
@@ -851,8 +844,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
node = map->getNode(pp, &is_valid_position);
if (is_valid_position) {
in_liquid = nodemgr->get(node.getContent()).isLiquid();
- liquid_viscosity =
- nodemgr->get(node.getContent()).liquid_viscosity;
+ liquid_viscosity = nodemgr->get(node.getContent()).liquid_viscosity;
} else {
in_liquid = false;
}
@@ -881,15 +873,13 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
is_climbing = false;
else
is_climbing = (nodemgr->get(node.getContent()).climbable ||
- nodemgr->get(node2.getContent())
- .climbable) &&
- !free_move;
+ nodemgr->get(node2.getContent()).climbable) && !free_move;
/*
Collision uncertainty radius
Make it a bit larger than the maximum distance of movement
*/
- // f32 d = pos_max_d * 1.1;
+ //f32 d = pos_max_d * 1.1;
// A fairly large value in here makes moving smoother
f32 d = 0.15f * BS;
// This should always apply, otherwise there are glitches
@@ -917,8 +907,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
/*
Collision seems broken, since player is sinking when
sneaking over the edges of current sneaking_node.
- TODO (when fixed): Set Y-speed only to 0 when position.Y <
- new_y.
+ TODO (when fixed): Set Y-speed only to 0 when position.Y < new_y.
*/
if (m_speed.Y < 0.0f)
m_speed.Y = 0.0f;
@@ -932,9 +921,9 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
const v3f initial_position = position;
const v3f initial_speed = m_speed;
- collisionMoveResult result = collisionMoveSimple(env, m_client, pos_max_d,
- m_collisionbox, player_stepheight, dtime, &position, &m_speed,
- accel_f, NULL, true, true);
+ collisionMoveResult result = collisionMoveSimple(env, m_client,
+ pos_max_d, m_collisionbox, player_stepheight, dtime,
+ &position, &m_speed, accel_f, NULL, true, true);
// Positition was slightly changed; update standing node pos
if (touching_ground)
@@ -951,7 +940,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
bool touching_ground_was = touching_ground;
touching_ground = result.touching_ground;
- // bool standing_on_unloaded = result.standing_on_unloaded;
+ //bool standing_on_unloaded = result.standing_on_unloaded;
/*
Check the nodes under the player to see from which node the
@@ -977,51 +966,44 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
if (m_need_to_get_new_sneak_node && physics_override_sneak) {
m_sneak_node_bb_ymax = 0.0f;
- v3s16 pos_i_bottom = floatToInt(
- position - v3f(0.0f, position_y_mod, 0.0f), BS);
+ v3s16 pos_i_bottom = floatToInt(position - v3f(0.0f, position_y_mod, 0.0f), BS);
v2f player_p2df(position.X, position.Z);
f32 min_distance_f = 100000.0f * BS;
// If already seeking from some node, compare to it.
v3s16 new_sneak_node = m_sneak_node;
- for (s16 x = -1; x <= 1; x++)
- for (s16 z = -1; z <= 1; z++) {
- v3s16 p = pos_i_bottom + v3s16(x, 0, z);
- v3f pf = intToFloat(p, BS);
- v2f node_p2df(pf.X, pf.Z);
- f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
- f32 max_axis_distance_f = MYMAX(
- std::fabs(player_p2df.X - node_p2df.X),
- std::fabs(player_p2df.Y - node_p2df.Y));
-
- if (distance_f > min_distance_f ||
- max_axis_distance_f >
- 0.5f * BS + sneak_max +
- 0.1f * BS)
- continue;
+ for (s16 x= -1; x <= 1; x++)
+ for (s16 z= -1; z <= 1; z++) {
+ v3s16 p = pos_i_bottom + v3s16(x, 0, z);
+ v3f pf = intToFloat(p, BS);
+ v2f node_p2df(pf.X, pf.Z);
+ f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
+ f32 max_axis_distance_f = MYMAX(
+ std::fabs(player_p2df.X - node_p2df.X),
+ std::fabs(player_p2df.Y - node_p2df.Y));
+
+ if (distance_f > min_distance_f ||
+ max_axis_distance_f > 0.5f * BS + sneak_max + 0.1f * BS)
+ continue;
- // The node to be sneaked on has to be walkable
- node = map->getNode(p, &is_valid_position);
- if (!is_valid_position || !nodemgr->get(node).walkable)
- continue;
- // And the node above it has to be nonwalkable
- node = map->getNode(
- p + v3s16(0, 1, 0), &is_valid_position);
+ // The node to be sneaked on has to be walkable
+ node = map->getNode(p, &is_valid_position);
+ if (!is_valid_position || !nodemgr->get(node).walkable)
+ continue;
+ // And the node above it has to be nonwalkable
+ node = map->getNode(p + v3s16(0, 1, 0), &is_valid_position);
+ if (!is_valid_position || nodemgr->get(node).walkable)
+ continue;
+ // If not 'sneak_glitch' the node 2 nodes above it has to be nonwalkable
+ if (!physics_override_sneak_glitch) {
+ node = map->getNode(p + v3s16(0, 2, 0), &is_valid_position);
if (!is_valid_position || nodemgr->get(node).walkable)
continue;
- // If not 'sneak_glitch' the node 2 nodes above it has to
- // be nonwalkable
- if (!physics_override_sneak_glitch) {
- node = map->getNode(p + v3s16(0, 2, 0),
- &is_valid_position);
- if (!is_valid_position ||
- nodemgr->get(node).walkable)
- continue;
- }
-
- min_distance_f = distance_f;
- new_sneak_node = p;
}
+ min_distance_f = distance_f;
+ new_sneak_node = p;
+ }
+
bool sneak_node_found = (min_distance_f < 100000.0f * BS * 0.9f);
m_sneak_node = new_sneak_node;
@@ -1065,8 +1047,7 @@ void LocalPlayer::old_move(f32 dtime, Environment *env, f32 pos_max_d,
}
if (!result.standing_on_object && !touching_ground_was && touching_ground) {
- m_client->getEventManager()->put(
- new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND));
+ m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND));
// Set camera impact value to be used for view bobbing
camera_impact = getSpeed().Y * -1.0f;
}
@@ -1134,8 +1115,8 @@ float LocalPlayer::getSlipFactor(Environment *env, const v3f &speedH)
}
void LocalPlayer::handleAutojump(f32 dtime, Environment *env,
- const collisionMoveResult &result, const v3f &initial_position,
- const v3f &initial_speed, f32 pos_max_d)
+ const collisionMoveResult &result, const v3f &initial_position,
+ const v3f &initial_speed, f32 pos_max_d)
{
PlayerSettings &player_settings = getPlayerSettings();
if (!player_settings.autojump)
@@ -1145,11 +1126,11 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env,
return;
bool control_forward = control.up ||
- (!control.up && !control.down &&
- control.forw_move_joystick_axis < -0.05f);
+ (!control.up && !control.down &&
+ control.forw_move_joystick_axis < -0.05f);
bool could_autojump =
- m_can_jump && !control.jump && !control.sneak && control_forward;
+ m_can_jump && !control.jump && !control.sneak && control_forward;
if (!could_autojump)
return;
@@ -1176,14 +1157,12 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env,
bool is_position_valid;
for (s16 z = ceilpos_min.Z; z <= ceilpos_max.Z; ++z) {
for (s16 x = ceilpos_min.X; x <= ceilpos_max.X; ++x) {
- MapNode n = env->getMap().getNode(
- v3s16(x, ceilpos_max.Y, z), &is_position_valid);
+ MapNode n = env->getMap().getNode(v3s16(x, ceilpos_max.Y, z), &is_position_valid);
if (!is_position_valid)
- break; // won't collide with the void outside
+ break; // won't collide with the void outside
if (n.getContent() == CONTENT_IGNORE)
- return; // players collide with ignore blocks -> same as
- // walkable
+ return; // players collide with ignore blocks -> same as walkable
const ContentFeatures &f = ndef->get(n);
if (f.walkable)
return; // would bump head, don't jump
@@ -1196,8 +1175,7 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env,
// try at peak of jump, zero step height
collisionMoveResult jump_result = collisionMoveSimple(env, m_client, pos_max_d,
- m_collisionbox, 0.0f, dtime, &jump_pos, &jump_speed, v3f(0.0f),
- NULL, true, true);
+ m_collisionbox, 0.0f, dtime, &jump_pos, &jump_speed, v3f(0.0f), NULL, true, true);
// see if we can get a little bit farther horizontally if we had
// jumped
@@ -1210,3 +1188,4 @@ void LocalPlayer::handleAutojump(f32 dtime, Environment *env,
m_autojump_time = 0.1f;
}
}
+
diff --git a/src/client/localplayer.h b/src/client/localplayer.h
index 8b2d932ab..0e071d2b4 100644
--- a/src/client/localplayer.h
+++ b/src/client/localplayer.h
@@ -132,7 +132,7 @@ public:
inline void setPosition(const v3f &position)
{
m_position = position;
- if (!m_freecam)
+ if (! m_freecam)
m_legit_position = position;
m_sneak_node_exists = false;
}
@@ -140,7 +140,7 @@ public:
v3f getPosition() const { return m_position; }
v3f getLegitPosition() const { return m_legit_position; }
-
+
v3f getLegitSpeed() const { return m_legit_speed; }
inline void setLegitPosition(const v3f &position)
@@ -151,15 +151,18 @@ public:
setPosition(position);
}
- inline void freecamEnable() { m_freecam = true; }
-
- inline void freecamDisable()
+ inline void freecamEnable()
+ {
+ m_freecam = true;
+ }
+
+ inline void freecamDisable()
{
m_freecam = false;
setPosition(m_legit_position);
setSpeed(m_legit_speed);
}
-
+
// Non-transformed eye offset getters
// For accurate positions, use the Camera functions
v3f getEyePosition() const { return m_position + getEyeOffset(); }
@@ -168,7 +171,7 @@ public:
void setCollisionbox(const aabb3f &box) { m_collisionbox = box; }
- const aabb3f &getCollisionbox() const { return m_collisionbox; }
+ const aabb3f& getCollisionbox() const { return m_collisionbox; }
float getZoomFOV() const { return m_zoom_fov; }
void setZoomFOV(float zoom_fov) { m_zoom_fov = zoom_fov; }
@@ -177,23 +180,26 @@ public:
bool isDead() const;
- inline void addVelocity(const v3f &vel) { added_velocity += vel; }
-
+ inline void addVelocity(const v3f &vel)
+ {
+ added_velocity += vel;
+ }
+
void tryReattach(int id);
-
+
bool isWaitingForReattach() const;
-
+
bool canWalkOn(const ContentFeatures &f);
-
+
private:
void accelerate(const v3f &target_speed, const f32 max_increase_H,
- const f32 max_increase_V, const bool use_pitch);
+ const f32 max_increase_V, const bool use_pitch);
bool updateSneakNode(Map *map, const v3f &position, const v3f &sneak_max);
float getSlipFactor(Environment *env, const v3f &speedH);
void handleAutojump(f32 dtime, Environment *env,
- const collisionMoveResult &result,
- const v3f &position_before_move, const v3f &speed_before_move,
- f32 pos_max_d);
+ const collisionMoveResult &result,
+ const v3f &position_before_move, const v3f &speed_before_move,
+ f32 pos_max_d);
bool m_freecam = false;
v3f m_position;
@@ -228,7 +234,7 @@ private:
f32 m_pitch = 0.0f;
bool camera_barely_in_ceiling = false;
aabb3f m_collisionbox = aabb3f(-BS * 0.30f, 0.0f, -BS * 0.30f, BS * 0.30f,
- BS * 1.75f, BS * 0.30f);
+ BS * 1.75f, BS * 0.30f);
float m_eye_height = 1.625f;
float m_zoom_fov = 0.0f;
bool m_autojump = false;
diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp
index 9487eae22..fbd7e2ab7 100644
--- a/src/client/mapblock_mesh.cpp
+++ b/src/client/mapblock_mesh.cpp
@@ -35,40 +35,40 @@ with this program; if not, write to the Free Software Foundation, Inc.,
MeshMakeData
*/
-MeshMakeData::MeshMakeData(Client *client, bool use_shaders, bool use_tangent_vertices) :
- m_client(client), m_use_shaders(use_shaders),
- m_use_tangent_vertices(use_tangent_vertices)
-{
-}
+MeshMakeData::MeshMakeData(Client *client, bool use_shaders,
+ bool use_tangent_vertices):
+ m_client(client),
+ m_use_shaders(use_shaders),
+ m_use_tangent_vertices(use_tangent_vertices)
+{}
void MeshMakeData::fillBlockDataBegin(const v3s16 &blockpos)
{
m_blockpos = blockpos;
- v3s16 blockpos_nodes = m_blockpos * MAP_BLOCKSIZE;
+ v3s16 blockpos_nodes = m_blockpos*MAP_BLOCKSIZE;
m_vmanip.clear();
- VoxelArea voxel_area(blockpos_nodes - v3s16(1, 1, 1) * MAP_BLOCKSIZE,
- blockpos_nodes + v3s16(1, 1, 1) * MAP_BLOCKSIZE * 2 -
- v3s16(1, 1, 1));
+ VoxelArea voxel_area(blockpos_nodes - v3s16(1,1,1) * MAP_BLOCKSIZE,
+ blockpos_nodes + v3s16(1,1,1) * MAP_BLOCKSIZE*2-v3s16(1,1,1));
m_vmanip.addArea(voxel_area);
}
void MeshMakeData::fillBlockData(const v3s16 &block_offset, MapNode *data)
{
v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
- VoxelArea data_area(v3s16(0, 0, 0), data_size - v3s16(1, 1, 1));
+ VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
v3s16 bp = m_blockpos + block_offset;
v3s16 blockpos_nodes = bp * MAP_BLOCKSIZE;
- m_vmanip.copyFrom(data, data_area, v3s16(0, 0, 0), blockpos_nodes, data_size);
+ m_vmanip.copyFrom(data, data_area, v3s16(0,0,0), blockpos_nodes, data_size);
}
void MeshMakeData::fill(MapBlock *block)
{
fillBlockDataBegin(block->getPos());
- fillBlockData(v3s16(0, 0, 0), block->getData());
+ fillBlockData(v3s16(0,0,0), block->getData());
// Get map for reading neighbor blocks
Map *map = block->getParent();
@@ -76,21 +76,20 @@ void MeshMakeData::fill(MapBlock *block)
for (const v3s16 &dir : g_26dirs) {
v3s16 bp = m_blockpos + dir;
MapBlock *b = map->getBlockNoCreateNoEx(bp);
- if (b)
+ if(b)
fillBlockData(dir, b->getData());
}
}
void MeshMakeData::fillSingleNode(MapNode *node)
{
- m_blockpos = v3s16(0, 0, 0);
+ m_blockpos = v3s16(0,0,0);
- v3s16 blockpos_nodes = v3s16(0, 0, 0);
- VoxelArea area(blockpos_nodes - v3s16(1, 1, 1) * MAP_BLOCKSIZE,
- blockpos_nodes + v3s16(1, 1, 1) * MAP_BLOCKSIZE * 2 -
- v3s16(1, 1, 1));
+ v3s16 blockpos_nodes = v3s16(0,0,0);
+ VoxelArea area(blockpos_nodes-v3s16(1,1,1)*MAP_BLOCKSIZE,
+ blockpos_nodes+v3s16(1,1,1)*MAP_BLOCKSIZE*2-v3s16(1,1,1));
s32 volume = area.getVolume();
- s32 our_node_index = area.index(1, 1, 1);
+ s32 our_node_index = area.index(1,1,1);
// Allocate this block + neighbors
m_vmanip.clear();
@@ -98,7 +97,8 @@ void MeshMakeData::fillSingleNode(MapNode *node)
// Fill in data
MapNode *data = new MapNode[volume];
- for (s32 i = 0; i < volume; i++) {
+ for(s32 i = 0; i < volume; i++)
+ {
if (i == our_node_index)
data[i] = *node;
else
@@ -111,12 +111,12 @@ void MeshMakeData::fillSingleNode(MapNode *node)
void MeshMakeData::setCrack(int crack_level, v3s16 crack_pos)
{
if (crack_level >= 0)
- m_crack_pos_relative = crack_pos - m_blockpos * MAP_BLOCKSIZE;
+ m_crack_pos_relative = crack_pos - m_blockpos*MAP_BLOCKSIZE;
}
void MeshMakeData::setSmoothLighting(bool smooth_lighting)
{
- m_smooth_lighting = smooth_lighting && !g_settings->getBool("fullbright");
+ m_smooth_lighting = smooth_lighting && ! g_settings->getBool("fullbright");
}
/*
@@ -127,13 +127,13 @@ void MeshMakeData::setSmoothLighting(bool smooth_lighting)
Calculate non-smooth lighting at interior of node.
Single light bank.
*/
-static u8 getInteriorLight(
- enum LightBank bank, MapNode n, s32 increment, const NodeDefManager *ndef)
+static u8 getInteriorLight(enum LightBank bank, MapNode n, s32 increment,
+ const NodeDefManager *ndef)
{
u8 light = n.getLight(bank, ndef);
if (light > 0)
light = rangelim(light + increment, 0, LIGHT_SUN);
- if (g_settings->getBool("fullbright"))
+ if(g_settings->getBool("fullbright"))
return 255;
return decode_light(light);
}
@@ -153,22 +153,23 @@ u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef)
Calculate non-smooth lighting at face of node.
Single light bank.
*/
-static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, v3s16 face_dir,
- const NodeDefManager *ndef)
+static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2,
+ v3s16 face_dir, const NodeDefManager *ndef)
{
u8 light;
u8 l1 = n.getLight(bank, ndef);
u8 l2 = n2.getLight(bank, ndef);
- if (l1 > l2)
+ if(l1 > l2)
light = l1;
else
light = l2;
// Boost light level for light sources
- u8 light_source = MYMAX(ndef->get(n).light_source, ndef->get(n2).light_source);
- if (light_source > light)
+ u8 light_source = MYMAX(ndef->get(n).light_source,
+ ndef->get(n2).light_source);
+ if(light_source > light)
light = light_source;
- if (g_settings->getBool("fullbright"))
+ if(g_settings->getBool("fullbright"))
return 255;
return decode_light(light);
}
@@ -177,7 +178,8 @@ static u8 getFaceLight(enum LightBank bank, MapNode n, MapNode n2, v3s16 face_di
Calculate non-smooth lighting at face of node.
Both light banks.
*/
-u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefManager *ndef)
+u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir,
+ const NodeDefManager *ndef)
{
u16 day = getFaceLight(LIGHTBANK_DAY, n, n2, face_dir, ndef);
u16 night = getFaceLight(LIGHTBANK_NIGHT, n, n2, face_dir, ndef);
@@ -188,8 +190,8 @@ u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefMana
Calculate smooth lighting at the XYZ- corner of p.
Both light banks
*/
-static u16 getSmoothLightCombined(
- const v3s16 &p, const std::array<v3s16, 8> &dirs, MeshMakeData *data)
+static u16 getSmoothLightCombined(const v3s16 &p,
+ const std::array<v3s16,8> &dirs, MeshMakeData *data)
{
const NodeDefManager *ndef = data->m_client->ndef();
@@ -200,7 +202,7 @@ static u16 getSmoothLightCombined(
u16 light_night = 0;
bool direct_sunlight = false;
- auto add_node = [&](u8 i, bool obstructed = false) -> bool {
+ auto add_node = [&] (u8 i, bool obstructed = false) -> bool {
if (obstructed) {
ambient_occlusion++;
return false;
@@ -226,7 +228,7 @@ static u16 getSmoothLightCombined(
return f.light_propagates;
};
- bool obstructed[4] = {true, true, true, true};
+ bool obstructed[4] = { true, true, true, true };
add_node(0);
bool opaque1 = !add_node(1);
bool opaque2 = !add_node(2);
@@ -262,34 +264,31 @@ static u16 getSmoothLightCombined(
}
bool skip_ambient_occlusion_night = false;
- if (decode_light(light_source_max) >= light_night) {
+ if(decode_light(light_source_max) >= light_night) {
light_night = decode_light(light_source_max);
skip_ambient_occlusion_night = true;
}
if (ambient_occlusion > 4) {
- static thread_local const float ao_gamma =
- rangelim(g_settings->getFloat("ambient_occlusion_gamma"),
- 0.25, 4.0);
+ static thread_local const float ao_gamma = rangelim(
+ g_settings->getFloat("ambient_occlusion_gamma"), 0.25, 4.0);
// Table of gamma space multiply factors.
static thread_local const float light_amount[3] = {
- powf(0.75, 1.0 / ao_gamma), powf(0.5, 1.0 / ao_gamma),
- powf(0.25, 1.0 / ao_gamma)};
+ powf(0.75, 1.0 / ao_gamma),
+ powf(0.5, 1.0 / ao_gamma),
+ powf(0.25, 1.0 / ao_gamma)
+ };
- // calculate table index for gamma space multiplier
+ //calculate table index for gamma space multiplier
ambient_occlusion -= 5;
if (!skip_ambient_occlusion_day)
- light_day = rangelim(
- core::round32(light_day *
- light_amount[ambient_occlusion]),
- 0, 255);
+ light_day = rangelim(core::round32(
+ light_day * light_amount[ambient_occlusion]), 0, 255);
if (!skip_ambient_occlusion_night)
- light_night = rangelim(
- core::round32(light_night *
- light_amount[ambient_occlusion]),
- 0, 255);
+ light_night = rangelim(core::round32(
+ light_night * light_amount[ambient_occlusion]), 0, 255);
}
return light_day | (light_night << 8);
@@ -300,8 +299,7 @@ static u16 getSmoothLightCombined(
Both light banks.
Node at p is solid, and thus the lighting is face-dependent.
*/
-u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner,
- MeshMakeData *data)
+u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data)
{
return getSmoothLightTransparent(p + face_dir, corner - 2 * face_dir, data);
}
@@ -313,19 +311,23 @@ u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corn
*/
u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data)
{
- const std::array<v3s16, 8> dirs = {{// Always shine light
- v3s16(0, 0, 0), v3s16(corner.X, 0, 0), v3s16(0, corner.Y, 0),
- v3s16(0, 0, corner.Z),
-
- // Can be obstructed
- v3s16(corner.X, corner.Y, 0), v3s16(corner.X, 0, corner.Z),
- v3s16(0, corner.Y, corner.Z),
- v3s16(corner.X, corner.Y, corner.Z)}};
+ const std::array<v3s16,8> dirs = {{
+ // Always shine light
+ v3s16(0,0,0),
+ v3s16(corner.X,0,0),
+ v3s16(0,corner.Y,0),
+ v3s16(0,0,corner.Z),
+
+ // Can be obstructed
+ v3s16(corner.X,corner.Y,0),
+ v3s16(corner.X,0,corner.Z),
+ v3s16(0,corner.Y,corner.Z),
+ v3s16(corner.X,corner.Y,corner.Z)
+ }};
return getSmoothLightCombined(p, dirs, data);
}
-void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio)
-{
+void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio){
f32 rg = daynight_ratio / 1000.0f - 0.04f;
f32 b = (0.98f * daynight_ratio) / 1000.0f + 0.078f;
sunlight->r = rg;
@@ -333,15 +335,17 @@ void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio)
sunlight->b = b;
}
-void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio)
+void final_color_blend(video::SColor *result,
+ u16 light, u32 daynight_ratio)
{
video::SColorf dayLight;
get_sunlight_color(&dayLight, daynight_ratio);
- final_color_blend(result, encode_light(light, 0), dayLight);
+ final_color_blend(result,
+ encode_light(light, 0), dayLight);
}
-void final_color_blend(video::SColor *result, const video::SColor &data,
- const video::SColorf &dayLight)
+void final_color_blend(video::SColor *result,
+ const video::SColor &data, const video::SColorf &dayLight)
{
static const video::SColorf artificialColor(1.04f, 1.04f, 1.04f);
@@ -355,48 +359,16 @@ void final_color_blend(video::SColor *result, const video::SColor &data,
// Emphase blue a bit in darker places
// Each entry of this array represents a range of 8 blue levels
static const u8 emphase_blue_when_dark[32] = {
- 1,
- 4,
- 6,
- 6,
- 6,
- 5,
- 4,
- 3,
- 2,
- 1,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
+ 1, 4, 6, 6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
- b += emphase_blue_when_dark[irr::core::clamp((s32)((r + g + b) / 3 * 255), 0,
- 255) /
- 8] /
- 255.0f;
+ b += emphase_blue_when_dark[irr::core::clamp((s32) ((r + g + b) / 3 * 255),
+ 0, 255) / 8] / 255.0f;
- result->setRed(core::clamp((s32)(r * 255.0f), 0, 255));
- result->setGreen(core::clamp((s32)(g * 255.0f), 0, 255));
- result->setBlue(core::clamp((s32)(b * 255.0f), 0, 255));
+ result->setRed(core::clamp((s32) (r * 255.0f), 0, 255));
+ result->setGreen(core::clamp((s32) (g * 255.0f), 0, 255));
+ result->setBlue(core::clamp((s32) (b * 255.0f), 0, 255));
}
/*
@@ -407,20 +379,27 @@ void final_color_blend(video::SColor *result, const video::SColor &data,
// a mutex to initialize this table at runtime right in the hot path.
// For details search the internet for "cxa_guard_acquire".
static const v3s16 vertex_dirs_table[] = {
- // ( 1, 0, 0)
- v3s16(1, -1, 1), v3s16(1, -1, -1), v3s16(1, 1, -1), v3s16(1, 1, 1),
- // ( 0, 1, 0)
- v3s16(1, 1, -1), v3s16(-1, 1, -1), v3s16(-1, 1, 1), v3s16(1, 1, 1),
- // ( 0, 0, 1)
- v3s16(-1, -1, 1), v3s16(1, -1, 1), v3s16(1, 1, 1), v3s16(-1, 1, 1),
- // invalid
- v3s16(), v3s16(), v3s16(), v3s16(),
- // ( 0, 0,-1)
- v3s16(1, -1, -1), v3s16(-1, -1, -1), v3s16(-1, 1, -1), v3s16(1, 1, -1),
- // ( 0,-1, 0)
- v3s16(1, -1, 1), v3s16(-1, -1, 1), v3s16(-1, -1, -1), v3s16(1, -1, -1),
- // (-1, 0, 0)
- v3s16(-1, -1, -1), v3s16(-1, -1, 1), v3s16(-1, 1, 1), v3s16(-1, 1, -1)};
+ // ( 1, 0, 0)
+ v3s16( 1,-1, 1), v3s16( 1,-1,-1),
+ v3s16( 1, 1,-1), v3s16( 1, 1, 1),
+ // ( 0, 1, 0)
+ v3s16( 1, 1,-1), v3s16(-1, 1,-1),
+ v3s16(-1, 1, 1), v3s16( 1, 1, 1),
+ // ( 0, 0, 1)
+ v3s16(-1,-1, 1), v3s16( 1,-1, 1),
+ v3s16( 1, 1, 1), v3s16(-1, 1, 1),
+ // invalid
+ v3s16(), v3s16(), v3s16(), v3s16(),
+ // ( 0, 0,-1)
+ v3s16( 1,-1,-1), v3s16(-1,-1,-1),
+ v3s16(-1, 1,-1), v3s16( 1, 1,-1),
+ // ( 0,-1, 0)
+ v3s16( 1,-1, 1), v3s16(-1,-1, 1),
+ v3s16(-1,-1,-1), v3s16( 1,-1,-1),
+ // (-1, 0, 0)
+ v3s16(-1,-1,-1), v3s16(-1,-1, 1),
+ v3s16(-1, 1, 1), v3s16(-1, 1,-1)
+};
/*
vertex_dirs: v3s16[4]
@@ -446,27 +425,26 @@ static void getNodeVertexDirs(const v3s16 &dir, v3s16 *vertex_dirs)
memcpy(vertex_dirs, &vertex_dirs_table[idx], 4 * sizeof(v3s16));
}
-static void getNodeTextureCoords(
- v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v)
+static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v)
{
if (dir.X > 0 || dir.Y > 0 || dir.Z < 0)
base -= scale;
- if (dir == v3s16(0, 0, 1)) {
+ if (dir == v3s16(0,0,1)) {
*u = -base.X - 1;
*v = -base.Y - 1;
- } else if (dir == v3s16(0, 0, -1)) {
+ } else if (dir == v3s16(0,0,-1)) {
*u = base.X + 1;
*v = -base.Y - 2;
- } else if (dir == v3s16(1, 0, 0)) {
+ } else if (dir == v3s16(1,0,0)) {
*u = base.Z + 1;
*v = -base.Y - 2;
- } else if (dir == v3s16(-1, 0, 0)) {
+ } else if (dir == v3s16(-1,0,0)) {
*u = -base.Z - 1;
*v = -base.Y - 1;
- } else if (dir == v3s16(0, 1, 0)) {
+ } else if (dir == v3s16(0,1,0)) {
*u = base.X + 1;
*v = -base.Z - 2;
- } else if (dir == v3s16(0, -1, 0)) {
+ } else if (dir == v3s16(0,-1,0)) {
*u = base.X;
*v = base.Z;
}
@@ -485,8 +463,7 @@ struct FastFace
};
static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li3,
- const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale,
- std::vector<FastFace> &dest)
+ const v3f &tp, const v3f &p, const v3s16 &dir, const v3f &scale, std::vector<FastFace> &dest)
{
// Position is at the center of the cube.
v3f pos = p * BS;
@@ -507,51 +484,51 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
switch (tile.rotation) {
case 0:
break;
- case 1: // R90
+ case 1: //R90
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[3];
vertex_dirs[3] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[1];
vertex_dirs[1] = t;
- t1 = li0;
+ t1 = li0;
li0 = li3;
li3 = li2;
li2 = li1;
li1 = t1;
break;
- case 2: // R180
+ case 2: //R180
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[2];
vertex_dirs[2] = t;
t = vertex_dirs[1];
vertex_dirs[1] = vertex_dirs[3];
vertex_dirs[3] = t;
- t1 = li0;
+ t1 = li0;
li0 = li2;
li2 = t1;
- t1 = li1;
+ t1 = li1;
li1 = li3;
li3 = t1;
break;
- case 3: // R270
+ case 3: //R270
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[1];
vertex_dirs[1] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[3];
vertex_dirs[3] = t;
- t1 = li0;
+ t1 = li0;
li0 = li1;
li1 = li2;
li2 = li3;
li3 = t1;
break;
- case 4: // FXR90
+ case 4: //FXR90
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[3];
vertex_dirs[3] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[1];
vertex_dirs[1] = t;
- t1 = li0;
+ t1 = li0;
li0 = li3;
li3 = li2;
li2 = li1;
@@ -559,13 +536,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
y0 += h;
h *= -1;
break;
- case 5: // FXR270
+ case 5: //FXR270
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[1];
vertex_dirs[1] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[3];
vertex_dirs[3] = t;
- t1 = li0;
+ t1 = li0;
li0 = li1;
li1 = li2;
li2 = li3;
@@ -573,13 +550,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
y0 += h;
h *= -1;
break;
- case 6: // FYR90
+ case 6: //FYR90
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[3];
vertex_dirs[3] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[1];
vertex_dirs[1] = t;
- t1 = li0;
+ t1 = li0;
li0 = li3;
li3 = li2;
li2 = li1;
@@ -587,13 +564,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
x0 += w;
w *= -1;
break;
- case 7: // FYR270
+ case 7: //FYR270
t = vertex_dirs[0];
vertex_dirs[0] = vertex_dirs[1];
vertex_dirs[1] = vertex_dirs[2];
vertex_dirs[2] = vertex_dirs[3];
vertex_dirs[3] = t;
- t1 = li0;
+ t1 = li0;
li0 = li1;
li1 = li2;
li2 = li3;
@@ -601,11 +578,11 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
x0 += w;
w *= -1;
break;
- case 8: // FX
+ case 8: //FX
y0 += h;
h *= -1;
break;
- case 9: // FY
+ case 9: //FY
x0 += w;
w *= -1;
break;
@@ -614,8 +591,11 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
}
for (u16 i = 0; i < 4; i++) {
- vertex_pos[i] = v3f(BS / 2 * vertex_dirs[i].X, BS / 2 * vertex_dirs[i].Y,
- BS / 2 * vertex_dirs[i].Z);
+ vertex_pos[i] = v3f(
+ BS / 2 * vertex_dirs[i].X,
+ BS / 2 * vertex_dirs[i].Y,
+ BS / 2 * vertex_dirs[i].Z
+ );
}
for (v3f &vpos : vertex_pos) {
@@ -626,16 +606,13 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
}
f32 abs_scale = 1.0f;
- if (scale.X < 0.999f || scale.X > 1.001f)
- abs_scale = scale.X;
- else if (scale.Y < 0.999f || scale.Y > 1.001f)
- abs_scale = scale.Y;
- else if (scale.Z < 0.999f || scale.Z > 1.001f)
- abs_scale = scale.Z;
+ if (scale.X < 0.999f || scale.X > 1.001f) abs_scale = scale.X;
+ else if (scale.Y < 0.999f || scale.Y > 1.001f) abs_scale = scale.Y;
+ else if (scale.Z < 0.999f || scale.Z > 1.001f) abs_scale = scale.Z;
v3f normal(dir.X, dir.Y, dir.Z);
- u16 li[4] = {li0, li1, li2, li3};
+ u16 li[4] = { li0, li1, li2, li3 };
u16 day[4];
u16 night[4];
@@ -644,16 +621,18 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
night[i] = li[i] & 0xFF;
}
- bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2]) <
- abs(day[1] - day[3]) + abs(night[1] - night[3]);
+ bool vertex_0_2_connected = abs(day[0] - day[2]) + abs(night[0] - night[2])
+ < abs(day[1] - day[3]) + abs(night[1] - night[3]);
- v2f32 f[4] = {core::vector2d<f32>(x0 + w * abs_scale, y0 + h),
- core::vector2d<f32>(x0, y0 + h), core::vector2d<f32>(x0, y0),
- core::vector2d<f32>(x0 + w * abs_scale, y0)};
+ v2f32 f[4] = {
+ core::vector2d<f32>(x0 + w * abs_scale, y0 + h),
+ core::vector2d<f32>(x0, y0 + h),
+ core::vector2d<f32>(x0, y0),
+ core::vector2d<f32>(x0 + w * abs_scale, y0) };
// equivalent to dest.push_back(FastFace()) but faster
dest.emplace_back();
- FastFace &face = *dest.rbegin();
+ FastFace& face = *dest.rbegin();
for (u8 i = 0; i < 4; i++) {
video::SColor c = encode_light(li[i], tile.emissive_light);
@@ -682,8 +661,8 @@ static void makeFastFace(const TileSpec &tile, u16 li0, u16 li1, u16 li2, u16 li
TODO: Add 3: Both faces drawn with backface culling, remove equivalent
*/
-static u8 face_contents(
- content_t m1, content_t m2, bool *equivalent, const NodeDefManager *ndef)
+static u8 face_contents(content_t m1, content_t m2, bool *equivalent,
+ const NodeDefManager *ndef)
{
*equivalent = false;
@@ -700,6 +679,7 @@ static u8 face_contents(
u8 c1 = f1.solidness;
u8 c2 = f2.solidness;
+
if (c1 == c2)
return 0;
@@ -708,6 +688,7 @@ static u8 face_contents(
else if (c2 == 0)
c2 = f2.visual_solidness;
+
if (c1 == c2) {
*equivalent = true;
// If same solidness, liquid takes precense
@@ -726,8 +707,7 @@ static u8 face_contents(
/*
Gets nth node tile (0 <= n <= 5).
*/
-void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data,
- TileSpec &tile)
+void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile)
{
const NodeDefManager *ndef = data->m_client->ndef();
const ContentFeatures &f = ndef->get(mn);
@@ -747,8 +727,7 @@ void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data,
/*
Gets node tile given a face direction.
*/
-void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data,
- TileSpec &tile)
+void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile)
{
const NodeDefManager *ndef = data->m_client->ndef();
@@ -770,43 +749,38 @@ void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *dat
// Get rotation for things like chests
u8 facedir = mn.getFaceDir(ndef, true);
- static const u16 dir_to_tile[24 * 16] = {// 0 +X +Y +Z -Z -Y
- // -X -> value=tile,rotation
- 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 5, 0, 1, 0, 3,
- 0, // rotate around y+ 0 - 3
- 0, 0, 4, 0, 0, 3, 3, 0, 0, 0, 2, 0, 1, 1, 5, 0, 0, 0, 3, 0, 0, 2,
- 5, 0, 0, 0, 4, 0, 1, 2, 2, 0, 0, 0, 5, 0, 0, 1, 2, 0, 0, 0, 3, 0,
- 1, 3, 4, 0,
-
- 0, 0, 2, 3, 5, 0, 0, 2, 0, 0, 1, 0, 4, 2, 3,
- 1, // rotate around z+ 4 - 7
- 0, 0, 4, 3, 2, 0, 0, 1, 0, 0, 1, 1, 3, 2, 5, 1, 0, 0, 3, 3, 4, 0,
- 0, 0, 0, 0, 1, 2, 5, 2, 2, 1, 0, 0, 5, 3, 3, 0, 0, 3, 0, 0, 1, 3,
- 2, 2, 4, 1,
-
- 0, 0, 2, 1, 4, 2, 1, 2, 0, 0, 0, 0, 5, 0, 3,
- 3, // rotate around z- 8 - 11
- 0, 0, 4, 1, 3, 2, 1, 3, 0, 0, 0, 3, 2, 0, 5, 3, 0, 0, 3, 1, 5, 2,
- 1, 0, 0, 0, 0, 2, 4, 0, 2, 3, 0, 0, 5, 1, 2, 2, 1, 1, 0, 0, 0, 1,
- 3, 0, 4, 3,
-
- 0, 0, 0, 3, 3, 3, 4, 1, 0, 0, 5, 3, 2, 3, 1,
- 3, // rotate around x+ 12 - 15
- 0, 0, 0, 2, 5, 3, 3, 1, 0, 0, 2, 3, 4, 3, 1, 0, 0, 0, 0, 1, 2, 3,
- 5, 1, 0, 0, 4, 3, 3, 3, 1, 1, 0, 0, 0, 0, 4, 3, 2, 1, 0, 0, 3, 3,
- 5, 3, 1, 2,
-
- 0, 0, 1, 1, 2, 1, 4, 3, 0, 0, 5, 1, 3, 1, 0,
- 1, // rotate around x- 16 - 19
- 0, 0, 1, 2, 4, 1, 3, 3, 0, 0, 2, 1, 5, 1, 0, 0, 0, 0, 1, 3, 3, 1,
- 5, 3, 0, 0, 4, 1, 2, 1, 0, 3, 0, 0, 1, 0, 5, 1, 2, 3, 0, 0, 3, 1,
- 4, 1, 0, 2,
-
- 0, 0, 3, 2, 1, 2, 4, 2, 0, 0, 5, 2, 0, 2, 2,
- 2, // rotate around y- 20 - 23
- 0, 0, 5, 2, 1, 3, 3, 2, 0, 0, 2, 2, 0, 1, 4, 2, 0, 0, 2, 2, 1, 0,
- 5, 2, 0, 0, 4, 2, 0, 0, 3, 2, 0, 0, 4, 2, 1, 1, 2, 2, 0, 0, 3, 2,
- 0, 3, 5, 2
+ static const u16 dir_to_tile[24 * 16] =
+ {
+ // 0 +X +Y +Z -Z -Y -X -> value=tile,rotation
+ 0,0, 2,0 , 0,0 , 4,0 , 0,0, 5,0 , 1,0 , 3,0 , // rotate around y+ 0 - 3
+ 0,0, 4,0 , 0,3 , 3,0 , 0,0, 2,0 , 1,1 , 5,0 ,
+ 0,0, 3,0 , 0,2 , 5,0 , 0,0, 4,0 , 1,2 , 2,0 ,
+ 0,0, 5,0 , 0,1 , 2,0 , 0,0, 3,0 , 1,3 , 4,0 ,
+
+ 0,0, 2,3 , 5,0 , 0,2 , 0,0, 1,0 , 4,2 , 3,1 , // rotate around z+ 4 - 7
+ 0,0, 4,3 , 2,0 , 0,1 , 0,0, 1,1 , 3,2 , 5,1 ,
+ 0,0, 3,3 , 4,0 , 0,0 , 0,0, 1,2 , 5,2 , 2,1 ,
+ 0,0, 5,3 , 3,0 , 0,3 , 0,0, 1,3 , 2,2 , 4,1 ,
+
+ 0,0, 2,1 , 4,2 , 1,2 , 0,0, 0,0 , 5,0 , 3,3 , // rotate around z- 8 - 11
+ 0,0, 4,1 , 3,2 , 1,3 , 0,0, 0,3 , 2,0 , 5,3 ,
+ 0,0, 3,1 , 5,2 , 1,0 , 0,0, 0,2 , 4,0 , 2,3 ,
+ 0,0, 5,1 , 2,2 , 1,1 , 0,0, 0,1 , 3,0 , 4,3 ,
+
+ 0,0, 0,3 , 3,3 , 4,1 , 0,0, 5,3 , 2,3 , 1,3 , // rotate around x+ 12 - 15
+ 0,0, 0,2 , 5,3 , 3,1 , 0,0, 2,3 , 4,3 , 1,0 ,
+ 0,0, 0,1 , 2,3 , 5,1 , 0,0, 4,3 , 3,3 , 1,1 ,
+ 0,0, 0,0 , 4,3 , 2,1 , 0,0, 3,3 , 5,3 , 1,2 ,
+
+ 0,0, 1,1 , 2,1 , 4,3 , 0,0, 5,1 , 3,1 , 0,1 , // rotate around x- 16 - 19
+ 0,0, 1,2 , 4,1 , 3,3 , 0,0, 2,1 , 5,1 , 0,0 ,
+ 0,0, 1,3 , 3,1 , 5,3 , 0,0, 4,1 , 2,1 , 0,3 ,
+ 0,0, 1,0 , 5,1 , 2,3 , 0,0, 3,1 , 4,1 , 0,2 ,
+
+ 0,0, 3,2 , 1,2 , 4,2 , 0,0, 5,2 , 0,2 , 2,2 , // rotate around y- 20 - 23
+ 0,0, 5,2 , 1,3 , 3,2 , 0,0, 2,2 , 0,1 , 4,2 ,
+ 0,0, 2,2 , 1,0 , 5,2 , 0,0, 4,2 , 0,0 , 3,2 ,
+ 0,0, 4,2 , 1,1 , 2,2 , 0,0, 3,2 , 0,3 , 5,2
};
u16 tile_index = facedir * 16 + dir_i;
@@ -821,7 +795,7 @@ std::set<content_t> splitToContentT(std::string str, const NodeDefManager *ndef)
std::string buf;
for (char c : str) {
if (c == ',' || c == '\n') {
- if (!buf.empty()) {
+ if (! buf.empty()) {
dat.insert(ndef->getId(buf));
}
buf.clear();
@@ -834,16 +808,24 @@ std::set<content_t> splitToContentT(std::string str, const NodeDefManager *ndef)
static void getTileInfo(
// Input:
- MeshMakeData *data, const v3s16 &p, const v3s16 &face_dir,
+ MeshMakeData *data,
+ const v3s16 &p,
+ const v3s16 &face_dir,
// Output:
- bool &makes_face, v3s16 &p_corrected, v3s16 &face_dir_corrected,
- u16 *lights, u8 &waving, TileSpec &tile, bool xray,
- std::set<content_t> xraySet)
+ bool &makes_face,
+ v3s16 &p_corrected,
+ v3s16 &face_dir_corrected,
+ u16 *lights,
+ u8 &waving,
+ TileSpec &tile,
+ bool xray,
+ std::set<content_t> xraySet
+ )
{
VoxelManipulator &vmanip = data->m_vmanip;
const NodeDefManager *ndef = data->m_client->ndef();
v3s16 blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE;
-
+
const MapNode &n0 = vmanip.getNodeRefUnsafe(blockpos_nodes + p);
content_t c0 = n0.getContent();
@@ -856,8 +838,7 @@ static void getTileInfo(
return;
}
- const MapNode &n1 =
- vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir);
+ const MapNode &n1 = vmanip.getNodeRefUnsafeCheckFlags(blockpos_nodes + p + face_dir);
content_t c1 = n1.getContent();
if (xray && xraySet.find(c1) != xraySet.end())
@@ -870,7 +851,8 @@ static void getTileInfo(
// This is hackish
bool equivalent = false;
- u8 mf = face_contents(c0, c1, &equivalent, ndef);
+ u8 mf = face_contents(c0, c1,
+ &equivalent, ndef);
if (mf == 0) {
makes_face = false;
@@ -910,8 +892,7 @@ static void getTileInfo(
v3s16 light_p = blockpos_nodes + p_corrected;
for (u16 i = 0; i < 4; i++)
- lights[i] = getSmoothLightSolid(light_p, face_dir_corrected,
- vertex_dirs[i], data);
+ lights[i] = getSmoothLightSolid(light_p, face_dir_corrected, vertex_dirs[i], data);
}
}
@@ -920,13 +901,19 @@ static void getTileInfo(
translate_dir: unit vector with only one of x, y or z
face_dir: unit vector with only one of x, y or z
*/
-static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
- v3s16 translate_dir, const v3f &&translate_dir_f, const v3s16 &&face_dir,
- std::vector<FastFace> &dest, bool xray, std::set<content_t> xraySet)
+static void updateFastFaceRow(
+ MeshMakeData *data,
+ const v3s16 &&startpos,
+ v3s16 translate_dir,
+ const v3f &&translate_dir_f,
+ const v3s16 &&face_dir,
+ std::vector<FastFace> &dest,
+ bool xray,
+ std::set<content_t> xraySet)
{
static thread_local const bool waving_liquids =
- g_settings->getBool("enable_shaders") &&
- g_settings->getBool("enable_waving_water");
+ g_settings->getBool("enable_shaders") &&
+ g_settings->getBool("enable_waving_water");
v3s16 p = startpos;
@@ -940,7 +927,8 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
TileSpec tile;
// Get info of first tile
- getTileInfo(data, p, face_dir, makes_face, p_corrected, face_dir_corrected,
+ getTileInfo(data, p, face_dir,
+ makes_face, p_corrected, face_dir_corrected,
lights, waving, tile, xray, xraySet);
// Unroll this variable which has a significant build cost
@@ -959,17 +947,21 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
if (j != MAP_BLOCKSIZE - 1) {
p += translate_dir;
- getTileInfo(data, p, face_dir, next_makes_face, next_p_corrected,
- next_face_dir_corrected, next_lights, waving,
- next_tile, xray, xraySet);
-
- if (next_makes_face == makes_face &&
- next_p_corrected == p_corrected + translate_dir &&
- next_face_dir_corrected == face_dir_corrected &&
- memcmp(next_lights, lights, sizeof(lights)) == 0
+ getTileInfo(data, p, face_dir,
+ next_makes_face, next_p_corrected,
+ next_face_dir_corrected, next_lights,
+ waving,
+ next_tile,
+ xray,
+ xraySet);
+
+ if (next_makes_face == makes_face
+ && next_p_corrected == p_corrected + translate_dir
+ && next_face_dir_corrected == face_dir_corrected
+ && memcmp(next_lights, lights, sizeof(lights)) == 0
// Don't apply fast faces to waving water.
- && (waving != 3 || !waving_liquids) &&
- next_tile.isTileable(tile)) {
+ && (waving != 3 || !waving_liquids)
+ && next_tile.isTileable(tile)) {
next_is_different = false;
continuous_tiles_count++;
}
@@ -982,9 +974,8 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
// Floating point conversion of the position vector
v3f pf(p_corrected.X, p_corrected.Y, p_corrected.Z);
// Center point of face (kind of)
- v3f sp = pf -
- ((f32)continuous_tiles_count * 0.5f - 0.5f) *
- translate_dir_f;
+ v3f sp = pf - ((f32)continuous_tiles_count * 0.5f - 0.5f)
+ * translate_dir_f;
v3f scale(1, 1, 1);
if (translate_dir.X != 0)
@@ -994,11 +985,9 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
if (translate_dir.Z != 0)
scale.Z = continuous_tiles_count;
- makeFastFace(tile, lights[0], lights[1], lights[2],
- lights[3], pf, sp, face_dir_corrected,
- scale, dest);
- g_profiler->avg("Meshgen: Tiles per face [#]",
- continuous_tiles_count);
+ makeFastFace(tile, lights[0], lights[1], lights[2], lights[3],
+ pf, sp, face_dir_corrected, scale, dest);
+ g_profiler->avg("Meshgen: Tiles per face [#]", continuous_tiles_count);
}
continuous_tiles_count = 1;
@@ -1013,35 +1002,50 @@ static void updateFastFaceRow(MeshMakeData *data, const v3s16 &&startpos,
}
}
-static void updateAllFastFaceRows(MeshMakeData *data, std::vector<FastFace> &dest,
- bool xray, std::set<content_t> xraySet)
+static void updateAllFastFaceRows(MeshMakeData *data,
+ std::vector<FastFace> &dest, bool xray, std::set<content_t> xraySet)
{
/*
Go through every y,z and get top(y+) faces in rows of x+
*/
for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
- for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
- updateFastFaceRow(data, v3s16(0, y, z), v3s16(1, 0, 0), // dir
- v3f(1, 0, 0), v3s16(0, 1, 0), // face dir
- dest, xray, xraySet);
+ for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
+ updateFastFaceRow(data,
+ v3s16(0, y, z),
+ v3s16(1, 0, 0), //dir
+ v3f (1, 0, 0),
+ v3s16(0, 1, 0), //face dir
+ dest,
+ xray,
+ xraySet);
/*
Go through every x,y and get right(x+) faces in rows of z+
*/
for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
- for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
- updateFastFaceRow(data, v3s16(x, y, 0), v3s16(0, 0, 1), // dir
- v3f(0, 0, 1), v3s16(1, 0, 0), // face dir
- dest, xray, xraySet);
+ for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
+ updateFastFaceRow(data,
+ v3s16(x, y, 0),
+ v3s16(0, 0, 1), //dir
+ v3f (0, 0, 1),
+ v3s16(1, 0, 0), //face dir
+ dest,
+ xray,
+ xraySet);
/*
Go through every y,z and get back(z+) faces in rows of x+
*/
for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
- for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
- updateFastFaceRow(data, v3s16(0, y, z), v3s16(1, 0, 0), // dir
- v3f(1, 0, 0), v3s16(0, 0, 1), // face dir
- dest, xray, xraySet);
+ for (s16 y = 0; y < MAP_BLOCKSIZE; y++)
+ updateFastFaceRow(data,
+ v3s16(0, y, z),
+ v3s16(1, 0, 0), //dir
+ v3f (1, 0, 0),
+ v3s16(0, 0, 1), //face dir
+ dest,
+ xray,
+ xraySet);
}
static void applyTileColor(PreMeshBuffer &pmb)
@@ -1051,9 +1055,10 @@ static void applyTileColor(PreMeshBuffer &pmb)
return;
for (video::S3DVertex &vertex : pmb.vertices) {
video::SColor *c = &vertex.Color;
- c->set(c->getAlpha(), c->getRed() * tc.getRed() / 255,
- c->getGreen() * tc.getGreen() / 255,
- c->getBlue() * tc.getBlue() / 255);
+ c->set(c->getAlpha(),
+ c->getRed() * tc.getRed() / 255,
+ c->getGreen() * tc.getGreen() / 255,
+ c->getBlue() * tc.getBlue() / 255);
}
}
@@ -1061,11 +1066,13 @@ static void applyTileColor(PreMeshBuffer &pmb)
MapBlockMesh
*/
-MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
- m_minimap_mapblock(NULL), m_tsrc(data->m_client->getTextureSource()),
- m_shdrsrc(data->m_client->getShaderSource()),
- m_animation_force_timer(0), // force initial animation
- m_last_crack(-1), m_last_daynight_ratio((u32)-1)
+MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset):
+ m_minimap_mapblock(NULL),
+ m_tsrc(data->m_client->getTextureSource()),
+ m_shdrsrc(data->m_client->getShaderSource()),
+ m_animation_force_timer(0), // force initial animation
+ m_last_crack(-1),
+ m_last_daynight_ratio((u32) -1)
{
for (auto &m : m_mesh)
m = new scene::SMesh();
@@ -1076,12 +1083,12 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
if (g_settings->getBool("enable_minimap")) {
m_minimap_mapblock = new MinimapMapblock;
m_minimap_mapblock->getMinimapNodes(
- &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE);
+ &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE);
}
// 4-21ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
// 24-155ms for MAP_BLOCKSIZE=32 (NOTE: probably outdated)
- // TimeTaker timer1("MapBlockMesh()");
+ //TimeTaker timer1("MapBlockMesh()");
std::vector<FastFace> fastfaces_new;
fastfaces_new.reserve(512);
@@ -1091,19 +1098,18 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
bool xray = g_settings->getBool("xray");
std::set<content_t> xraySet;
if (xray)
- xraySet = splitToContentT(
- g_settings->get("xray_nodes"), data->m_client->ndef());
-
+ xraySet = splitToContentT(g_settings->get("xray_nodes"), data->m_client->ndef());
+
/*
We are including the faces of the trailing edges of the block.
This means that when something changes, the caller must
also update the meshes of the blocks at the leading edges.
NOTE: This is the slowest part of this method.
- */
+ */
{
// 4-23ms for MAP_BLOCKSIZE=16 (NOTE: probably outdated)
- // TimeTaker timer2("updateAllFastFaceRows()");
+ //TimeTaker timer2("updateAllFastFaceRows()");
updateAllFastFaceRows(data, fastfaces_new, xray, xraySet);
}
// End of slow part
@@ -1117,13 +1123,13 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
{
// avg 0ms (100ms spikes when loading textures the first time)
// (NOTE: probably outdated)
- // TimeTaker timer2("MeshCollector building");
+ //TimeTaker timer2("MeshCollector building");
for (const FastFace &f : fastfaces_new) {
static const u16 indices[] = {0, 1, 2, 2, 3, 0};
static const u16 indices_alternate[] = {0, 1, 3, 2, 3, 1};
- const u16 *indices_p = f.vertex_0_2_connected ? indices
- : indices_alternate;
+ const u16 *indices_p =
+ f.vertex_0_2_connected ? indices : indices_alternate;
collector.append(f.tile, f.vertices, 4, indices_p, 6);
}
}
@@ -1146,7 +1152,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
*/
for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
- for (u32 i = 0; i < collector.prebuffers[layer].size(); i++) {
+ for(u32 i = 0; i < collector.prebuffers[layer].size(); i++)
+ {
PreMeshBuffer &p = collector.prebuffers[layer][i];
applyTileColor(p);
@@ -1156,10 +1163,9 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
if (p.layer.material_flags & MATERIAL_FLAG_CRACK) {
// Find the texture name plus ^[crack:N:
std::ostringstream os(std::ios::binary);
- os << m_tsrc->getTextureName(p.layer.texture_id)
- << "^[crack";
+ os << m_tsrc->getTextureName(p.layer.texture_id) << "^[crack";
if (p.layer.material_flags & MATERIAL_FLAG_CRACK_OVERLAY)
- os << "o"; // use ^[cracko
+ os << "o"; // use ^[cracko
u8 tiles = p.layer.scale;
if (tiles > 1)
os << ":" << (u32)tiles;
@@ -1168,27 +1174,24 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
std::pair<u8, u32>(layer, i), os.str()));
// Replace tile texture with the cracked one
p.layer.texture = m_tsrc->getTextureForMesh(
- os.str() + "0", &p.layer.texture_id);
+ os.str() + "0",
+ &p.layer.texture_id);
}
// - Texture animation
if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) {
// Add to MapBlockMesh in order to animate these tiles
m_animation_tiles[std::pair<u8, u32>(layer, i)] = p.layer;
m_animation_frames[std::pair<u8, u32>(layer, i)] = 0;
- if (g_settings->getBool("desynchronize_mapblock_texture_"
- "animation")) {
+ if (g_settings->getBool(
+ "desynchronize_mapblock_texture_animation")) {
// Get starting position from noise
- m_animation_frame_offsets[std::pair<u8, u32>(
- layer, i)] =
- 100000 *
- (2.0 + noise3d(data->m_blockpos.X,
- data->m_blockpos.Y,
- data->m_blockpos.Z,
- 0));
+ m_animation_frame_offsets[std::pair<u8, u32>(layer, i)] =
+ 100000 * (2.0 + noise3d(
+ data->m_blockpos.X, data->m_blockpos.Y,
+ data->m_blockpos.Z, 0));
} else {
// Play all synchronized
- m_animation_frame_offsets[std::pair<u8, u32>(
- layer, i)] = 0;
+ m_animation_frame_offsets[std::pair<u8, u32>(layer, i)] = 0;
}
// Replace tile texture with the first animation frame
p.layer.texture = (*p.layer.frames)[0].texture;
@@ -1203,14 +1206,10 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
for (u32 j = 0; j < vertex_count; j++) {
video::SColor *vc = &p.vertices[j].Color;
video::SColor copy = *vc;
- if (vc->getAlpha() == 0) // No sunlight - no need
- // to animate
- final_color_blend(vc, copy,
- sunlight); // Finalize
- // color
+ if (vc->getAlpha() == 0) // No sunlight - no need to animate
+ final_color_blend(vc, copy, sunlight); // Finalize color
else // Record color to animate
- m_daynight_diffs[std::pair<u8, u32>(
- layer, i)][j] = copy;
+ m_daynight_diffs[std::pair<u8, u32>(layer, i)][j] = copy;
// The sunlight ratio has been stored,
// delete alpha (for the final rendering).
@@ -1227,9 +1226,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
material.setTexture(0, p.layer.texture);
if (m_enable_shaders) {
- material.MaterialType =
- m_shdrsrc->getShaderInfo(p.layer.shader_id)
- .material;
+ material.MaterialType = m_shdrsrc->getShaderInfo(
+ p.layer.shader_id).material;
p.layer.applyMaterialOptionsWithShaders(material);
if (p.layer.normal_texture)
material.setTexture(1, p.layer.normal_texture);
@@ -1247,10 +1245,9 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
buf->Material = material;
buf->Vertices.reallocate(p.vertices.size());
buf->Indices.reallocate(p.indices.size());
- for (const video::S3DVertex &v : p.vertices)
- buf->Vertices.push_back(video::S3DVertexTangents(
- v.Pos, v.Color, v.TCoords));
- for (u16 i : p.indices)
+ for (const video::S3DVertex &v: p.vertices)
+ buf->Vertices.push_back(video::S3DVertexTangents(v.Pos, v.Color, v.TCoords));
+ for (u16 i: p.indices)
buf->Indices.push_back(i);
buf->recalculateBoundingBox();
mesh->addMeshBuffer(buf);
@@ -1259,7 +1256,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
scene::SMeshBuffer *buf = new scene::SMeshBuffer();
buf->Material = material;
buf->append(&p.vertices[0], p.vertices.size(),
- &p.indices[0], p.indices.size());
+ &p.indices[0], p.indices.size());
mesh->addMeshBuffer(buf);
buf->drop();
}
@@ -1270,14 +1267,11 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
*/
m_camera_offset = camera_offset;
translateMesh(m_mesh[layer],
- intToFloat(data->m_blockpos * MAP_BLOCKSIZE -
- camera_offset,
- BS));
+ intToFloat(data->m_blockpos * MAP_BLOCKSIZE - camera_offset, BS));
if (m_use_tangent_vertices) {
- scene::IMeshManipulator *meshmanip =
- RenderingEngine::get_scene_manager()
- ->getMeshManipulator();
+ scene::IMeshManipulator* meshmanip =
+ RenderingEngine::get_scene_manager()->getMeshManipulator();
meshmanip->recalculateTangents(m_mesh[layer], true, false, false);
}
@@ -1295,11 +1289,13 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset) :
}
}
- // std::cout<<"added "<<fastfaces.getSize()<<" faces."<<std::endl;
+ //std::cout<<"added "<<fastfaces.getSize()<<" faces."<<std::endl;
// Check if animation is required for this mesh
- m_has_animation = !m_crack_materials.empty() || !m_daynight_diffs.empty() ||
- !m_animation_tiles.empty();
+ m_has_animation =
+ !m_crack_materials.empty() ||
+ !m_daynight_diffs.empty() ||
+ !m_animation_tiles.empty();
}
MapBlockMesh::~MapBlockMesh()
@@ -1308,8 +1304,7 @@ MapBlockMesh::~MapBlockMesh()
if (m_enable_vbo && m)
for (u32 i = 0; i < m->getMeshBufferCount(); i++) {
scene::IMeshBuffer *buf = m->getMeshBuffer(i);
- RenderingEngine::get_video_driver()->removeHardwareBuffer(
- buf);
+ RenderingEngine::get_video_driver()->removeHardwareBuffer(buf);
}
m->drop();
m = NULL;
@@ -1317,7 +1312,8 @@ MapBlockMesh::~MapBlockMesh()
delete m_minimap_mapblock;
}
-bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_ratio)
+bool MapBlockMesh::animate(bool faraway, float time, int crack,
+ u32 daynight_ratio)
{
if (!m_has_animation) {
m_animation_force_timer = 100000;
@@ -1329,17 +1325,16 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat
// Cracks
if (crack != m_last_crack) {
for (auto &crack_material : m_crack_materials) {
- scene::IMeshBuffer *buf =
- m_mesh[crack_material.first.first]->getMeshBuffer(
- crack_material.first.second);
+ scene::IMeshBuffer *buf = m_mesh[crack_material.first.first]->
+ getMeshBuffer(crack_material.first.second);
std::string basename = crack_material.second;
// Create new texture name from original
std::ostringstream os;
os << basename << crack;
u32 new_texture_id = 0;
- video::ITexture *new_texture = m_tsrc->getTextureForMesh(
- os.str(), &new_texture_id);
+ video::ITexture *new_texture =
+ m_tsrc->getTextureForMesh(os.str(), &new_texture_id);
buf->getMaterial().setTexture(0, new_texture);
// If the current material is also animated,
@@ -1362,25 +1357,23 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat
const TileLayer &tile = animation_tile.second;
// Figure out current frame
int frameoffset = m_animation_frame_offsets[animation_tile.first];
- int frame = (int)(time * 1000 / tile.animation_frame_length_ms +
- frameoffset) %
- tile.animation_frame_count;
+ int frame = (int)(time * 1000 / tile.animation_frame_length_ms
+ + frameoffset) % tile.animation_frame_count;
// If frame doesn't change, skip
if (frame == m_animation_frames[animation_tile.first])
continue;
m_animation_frames[animation_tile.first] = frame;
- scene::IMeshBuffer *buf =
- m_mesh[animation_tile.first.first]->getMeshBuffer(
- animation_tile.first.second);
+ scene::IMeshBuffer *buf = m_mesh[animation_tile.first.first]->
+ getMeshBuffer(animation_tile.first.second);
const FrameSpec &animation_frame = (*tile.frames)[frame];
buf->getMaterial().setTexture(0, animation_frame.texture);
if (m_enable_shaders) {
if (animation_frame.normal_texture)
- buf->getMaterial().setTexture(
- 1, animation_frame.normal_texture);
+ buf->getMaterial().setTexture(1,
+ animation_frame.normal_texture);
buf->getMaterial().setTexture(2, animation_frame.flags_texture);
}
}
@@ -1395,11 +1388,9 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, u32 daynight_rat
get_sunlight_color(&day_color, daynight_ratio);
for (auto &daynight_diff : m_daynight_diffs) {
- scene::IMeshBuffer *buf =
- m_mesh[daynight_diff.first.first]->getMeshBuffer(
- daynight_diff.first.second);
- video::S3DVertex *vertices =
- (video::S3DVertex *)buf->getVertices();
+ scene::IMeshBuffer *buf = m_mesh[daynight_diff.first.first]->
+ getMeshBuffer(daynight_diff.first.second);
+ video::S3DVertex *vertices = (video::S3DVertex *)buf->getVertices();
for (const auto &j : daynight_diff.second)
final_color_blend(&(vertices[j.first].Color), j.second,
day_color);
@@ -1415,7 +1406,7 @@ void MapBlockMesh::updateCameraOffset(v3s16 camera_offset)
if (camera_offset != m_camera_offset) {
for (scene::IMesh *layer : m_mesh) {
translateMesh(layer,
- intToFloat(m_camera_offset - camera_offset, BS));
+ intToFloat(m_camera_offset - camera_offset, BS));
if (m_enable_vbo)
layer->setDirty();
}
diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h
index dd08433a1..6af23a656 100644
--- a/src/client/mapblock_mesh.h
+++ b/src/client/mapblock_mesh.h
@@ -32,21 +32,23 @@ class IShaderSource;
Mesh making stuff
*/
+
class MapBlock;
struct MinimapMapblock;
struct MeshMakeData
{
VoxelManipulator m_vmanip;
- v3s16 m_blockpos = v3s16(-1337, -1337, -1337);
- v3s16 m_crack_pos_relative = v3s16(-1337, -1337, -1337);
+ v3s16 m_blockpos = v3s16(-1337,-1337,-1337);
+ v3s16 m_crack_pos_relative = v3s16(-1337,-1337,-1337);
bool m_smooth_lighting = false;
Client *m_client;
bool m_use_shaders;
bool m_use_tangent_vertices;
- MeshMakeData(Client *client, bool use_shaders, bool use_tangent_vertices = false);
+ MeshMakeData(Client *client, bool use_shaders,
+ bool use_tangent_vertices = false);
/*
Copy block data manually (to allow optimizations by the caller)
@@ -102,9 +104,15 @@ public:
// Returns true if anything has been changed.
bool animate(bool faraway, float time, int crack, u32 daynight_ratio);
- scene::IMesh *getMesh() { return m_mesh[0]; }
+ scene::IMesh *getMesh()
+ {
+ return m_mesh[0];
+ }
- scene::IMesh *getMesh(u8 layer) { return m_mesh[layer]; }
+ scene::IMesh *getMesh(u8 layer)
+ {
+ return m_mesh[layer];
+ }
MinimapMapblock *moveMinimapMapblock()
{
@@ -113,11 +121,14 @@ public:
return p;
}
- bool isAnimationForced() const { return m_animation_force_timer == 0; }
+ bool isAnimationForced() const
+ {
+ return m_animation_force_timer == 0;
+ }
void decreaseAnimationForceTimer()
{
- if (m_animation_force_timer > 0)
+ if(m_animation_force_timer > 0)
m_animation_force_timer--;
}
@@ -156,7 +167,7 @@ private:
// For each mesh and mesh buffer, stores pre-baked colors
// of sunlit vertices
// Keys are pairs of (mesh index, buffer index in the mesh)
- std::map<std::pair<u8, u32>, std::map<u32, video::SColor>> m_daynight_diffs;
+ std::map<std::pair<u8, u32>, std::map<u32, video::SColor > > m_daynight_diffs;
// Camera offset info -> do we have to translate the mesh?
v3s16 m_camera_offset;
@@ -178,10 +189,9 @@ video::SColor encode_light(u16 light, u8 emissive_light);
// Compute light at node
u16 getInteriorLight(MapNode n, s32 increment, const NodeDefManager *ndef);
-u16 getFaceLight(
- MapNode n, MapNode n2, const v3s16 &face_dir, const NodeDefManager *ndef);
-u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner,
- MeshMakeData *data);
+u16 getFaceLight(MapNode n, MapNode n2, const v3s16 &face_dir,
+ const NodeDefManager *ndef);
+u16 getSmoothLightSolid(const v3s16 &p, const v3s16 &face_dir, const v3s16 &corner, MeshMakeData *data);
u16 getSmoothLightTransparent(const v3s16 &p, const v3s16 &corner, MeshMakeData *data);
/*!
@@ -197,7 +207,8 @@ void get_sunlight_color(video::SColorf *sunlight, u32 daynight_ratio);
* \param light first 8 bits are day light, second 8 bits are
* night light
*/
-void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio);
+void final_color_blend(video::SColor *result,
+ u16 light, u32 daynight_ratio);
/*!
* Gives the final SColor shown on screen.
@@ -206,14 +217,12 @@ void final_color_blend(video::SColor *result, u16 light, u32 daynight_ratio);
* \param data the half-baked vertex color
* \param dayLight color of the sunlight
*/
-void final_color_blend(video::SColor *result, const video::SColor &data,
- const video::SColorf &dayLight);
+void final_color_blend(video::SColor *result,
+ const video::SColor &data, const video::SColorf &dayLight);
// Retrieves the TileSpec of a face of a node
// Adds MATERIAL_FLAG_CRACK if the node is cracked
// TileSpec should be passed as reference due to the underlying TileFrame and its vector
// TileFrame vector copy cost very much to client
-void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data,
- TileSpec &tile);
-void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data,
- TileSpec &tile);
+void getNodeTileN(MapNode mn, const v3s16 &p, u8 tileindex, MeshMakeData *data, TileSpec &tile);
+void getNodeTile(MapNode mn, const v3s16 &p, const v3s16 &dir, MeshMakeData *data, TileSpec &tile);
diff --git a/src/client/mesh.cpp b/src/client/mesh.cpp
index 312d4e7f6..e1ec22068 100644
--- a/src/client/mesh.cpp
+++ b/src/client/mesh.cpp
@@ -35,11 +35,11 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY
#endif
-inline static void applyShadeFactor(video::SColor &color, float factor)
+inline static void applyShadeFactor(video::SColor& color, float factor)
{
- color.setRed(core::clamp(core::round32(color.getRed() * factor), 0, 255));
- color.setGreen(core::clamp(core::round32(color.getGreen() * factor), 0, 255));
- color.setBlue(core::clamp(core::round32(color.getBlue() * factor), 0, 255));
+ color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255));
+ color.setGreen(core::clamp(core::round32(color.getGreen()*factor), 0, 255));
+ color.setBlue(core::clamp(core::round32(color.getBlue()*factor), 0, 255));
}
void applyFacesShading(video::SColor &color, const v3f &normal)
@@ -62,53 +62,54 @@ void applyFacesShading(video::SColor &color, const v3f &normal)
applyShadeFactor(color, 0.670820f * x2 + 1.000000f * y2 + 0.836660f * z2);
}
-scene::IAnimatedMesh *createCubeMesh(v3f scale)
+scene::IAnimatedMesh* createCubeMesh(v3f scale)
{
- video::SColor c(255, 255, 255, 255);
- video::S3DVertex vertices[24] = {
- // Up
- video::S3DVertex(-0.5, +0.5, -0.5, 0, 1, 0, c, 0, 1),
- video::S3DVertex(-0.5, +0.5, +0.5, 0, 1, 0, c, 0, 0),
- video::S3DVertex(+0.5, +0.5, +0.5, 0, 1, 0, c, 1, 0),
- video::S3DVertex(+0.5, +0.5, -0.5, 0, 1, 0, c, 1, 1),
- // Down
- video::S3DVertex(-0.5, -0.5, -0.5, 0, -1, 0, c, 0, 0),
- video::S3DVertex(+0.5, -0.5, -0.5, 0, -1, 0, c, 1, 0),
- video::S3DVertex(+0.5, -0.5, +0.5, 0, -1, 0, c, 1, 1),
- video::S3DVertex(-0.5, -0.5, +0.5, 0, -1, 0, c, 0, 1),
- // Right
- video::S3DVertex(+0.5, -0.5, -0.5, 1, 0, 0, c, 0, 1),
- video::S3DVertex(+0.5, +0.5, -0.5, 1, 0, 0, c, 0, 0),
- video::S3DVertex(+0.5, +0.5, +0.5, 1, 0, 0, c, 1, 0),
- video::S3DVertex(+0.5, -0.5, +0.5, 1, 0, 0, c, 1, 1),
- // Left
- video::S3DVertex(-0.5, -0.5, -0.5, -1, 0, 0, c, 1, 1),
- video::S3DVertex(-0.5, -0.5, +0.5, -1, 0, 0, c, 0, 1),
- video::S3DVertex(-0.5, +0.5, +0.5, -1, 0, 0, c, 0, 0),
- video::S3DVertex(-0.5, +0.5, -0.5, -1, 0, 0, c, 1, 0),
- // Back
- video::S3DVertex(-0.5, -0.5, +0.5, 0, 0, 1, c, 1, 1),
- video::S3DVertex(+0.5, -0.5, +0.5, 0, 0, 1, c, 0, 1),
- video::S3DVertex(+0.5, +0.5, +0.5, 0, 0, 1, c, 0, 0),
- video::S3DVertex(-0.5, +0.5, +0.5, 0, 0, 1, c, 1, 0),
- // Front
- video::S3DVertex(-0.5, -0.5, -0.5, 0, 0, -1, c, 0, 1),
- video::S3DVertex(-0.5, +0.5, -0.5, 0, 0, -1, c, 0, 0),
- video::S3DVertex(+0.5, +0.5, -0.5, 0, 0, -1, c, 1, 0),
- video::S3DVertex(+0.5, -0.5, -0.5, 0, 0, -1, c, 1, 1),
+ video::SColor c(255,255,255,255);
+ video::S3DVertex vertices[24] =
+ {
+ // Up
+ video::S3DVertex(-0.5,+0.5,-0.5, 0,1,0, c, 0,1),
+ video::S3DVertex(-0.5,+0.5,+0.5, 0,1,0, c, 0,0),
+ video::S3DVertex(+0.5,+0.5,+0.5, 0,1,0, c, 1,0),
+ video::S3DVertex(+0.5,+0.5,-0.5, 0,1,0, c, 1,1),
+ // Down
+ video::S3DVertex(-0.5,-0.5,-0.5, 0,-1,0, c, 0,0),
+ video::S3DVertex(+0.5,-0.5,-0.5, 0,-1,0, c, 1,0),
+ video::S3DVertex(+0.5,-0.5,+0.5, 0,-1,0, c, 1,1),
+ video::S3DVertex(-0.5,-0.5,+0.5, 0,-1,0, c, 0,1),
+ // Right
+ video::S3DVertex(+0.5,-0.5,-0.5, 1,0,0, c, 0,1),
+ video::S3DVertex(+0.5,+0.5,-0.5, 1,0,0, c, 0,0),
+ video::S3DVertex(+0.5,+0.5,+0.5, 1,0,0, c, 1,0),
+ video::S3DVertex(+0.5,-0.5,+0.5, 1,0,0, c, 1,1),
+ // Left
+ video::S3DVertex(-0.5,-0.5,-0.5, -1,0,0, c, 1,1),
+ video::S3DVertex(-0.5,-0.5,+0.5, -1,0,0, c, 0,1),
+ video::S3DVertex(-0.5,+0.5,+0.5, -1,0,0, c, 0,0),
+ video::S3DVertex(-0.5,+0.5,-0.5, -1,0,0, c, 1,0),
+ // Back
+ video::S3DVertex(-0.5,-0.5,+0.5, 0,0,1, c, 1,1),
+ video::S3DVertex(+0.5,-0.5,+0.5, 0,0,1, c, 0,1),
+ video::S3DVertex(+0.5,+0.5,+0.5, 0,0,1, c, 0,0),
+ video::S3DVertex(-0.5,+0.5,+0.5, 0,0,1, c, 1,0),
+ // Front
+ video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1),
+ video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0),
+ video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0),
+ video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1),
};
- u16 indices[6] = {0, 1, 2, 2, 3, 0};
+ u16 indices[6] = {0,1,2,2,3,0};
scene::SMesh *mesh = new scene::SMesh();
- for (u32 i = 0; i < 6; ++i) {
+ for (u32 i=0; i<6; ++i)
+ {
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
buf->append(vertices + 4 * i, 4, indices, 6);
// Set default material
buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
- buf->getMaterial().MaterialType =
- video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
+ buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
// Add mesh buffer to mesh
mesh->addMeshBuffer(buf);
buf->drop();
@@ -116,7 +117,7 @@ scene::IAnimatedMesh *createCubeMesh(v3f scale)
scene::SAnimatedMesh *anim_mesh = new scene::SAnimatedMesh(mesh);
mesh->drop();
- scaleMesh(anim_mesh, scale); // also recalculates bounding box
+ scaleMesh(anim_mesh, scale); // also recalculates bounding box
return anim_mesh;
}
@@ -180,9 +181,9 @@ void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color)
{
const u32 stride = getVertexPitchFromType(buf->getVertexType());
u32 vertex_count = buf->getVertexCount();
- u8 *vertices = (u8 *)buf->getVertices();
+ u8 *vertices = (u8 *) buf->getVertices();
for (u32 i = 0; i < vertex_count; i++)
- ((video::S3DVertex *)(vertices + i * stride))->Color = color;
+ ((video::S3DVertex *) (vertices + i * stride))->Color = color;
}
void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color)
@@ -202,7 +203,8 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color)
setMeshBufferColor(mesh->getMeshBuffer(j), color);
}
-template <typename F> static void applyToMesh(scene::IMesh *mesh, const F &fn)
+template <typename F>
+static void applyToMesh(scene::IMesh *mesh, const F &fn)
{
u16 mc = mesh->getMeshBufferCount();
for (u16 j = 0; j < mc; j++) {
@@ -219,9 +221,9 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo
{
const u32 stride = getVertexPitchFromType(buf->getVertexType());
u32 vertex_count = buf->getVertexCount();
- u8 *vertices = (u8 *)buf->getVertices();
+ u8 *vertices = (u8 *) buf->getVertices();
for (u32 i = 0; i < vertex_count; i++) {
- video::S3DVertex *vertex = (video::S3DVertex *)(vertices + i * stride);
+ video::S3DVertex *vertex = (video::S3DVertex *) (vertices + i * stride);
video::SColor *vc = &(vertex->Color);
// Reset color
*vc = *buffercolor;
@@ -230,12 +232,14 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo
}
}
-void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX,
- const video::SColor &colorY, const video::SColor &colorZ)
+void setMeshColorByNormalXYZ(scene::IMesh *mesh,
+ const video::SColor &colorX,
+ const video::SColor &colorY,
+ const video::SColor &colorZ)
{
if (!mesh)
return;
- auto colorizator = [=](video::S3DVertex *vertex) {
+ auto colorizator = [=] (video::S3DVertex *vertex) {
f32 x = fabs(vertex->Normal.X);
f32 y = fabs(vertex->Normal.Y);
f32 z = fabs(vertex->Normal.Z);
@@ -249,12 +253,12 @@ void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX,
applyToMesh(mesh, colorizator);
}
-void setMeshColorByNormal(
- scene::IMesh *mesh, const v3f &normal, const video::SColor &color)
+void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal,
+ const video::SColor &color)
{
if (!mesh)
return;
- auto colorizator = [normal, color](video::S3DVertex *vertex) {
+ auto colorizator = [normal, color] (video::S3DVertex *vertex) {
if (vertex->Normal == normal)
vertex->Color = color;
};
@@ -267,7 +271,7 @@ static void rotateMesh(scene::IMesh *mesh, float degrees)
degrees *= M_PI / 180.0f;
float c = std::cos(degrees);
float s = std::sin(degrees);
- auto rotator = [c, s](video::S3DVertex *vertex) {
+ auto rotator = [c, s] (video::S3DVertex *vertex) {
float u = vertex->Pos.*U;
float v = vertex->Pos.*V;
vertex->Pos.*U = c * u - s * v;
@@ -296,39 +300,23 @@ void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir)
int axisdir = facedir >> 2;
facedir &= 0x03;
switch (facedir) {
- case 1:
- rotateMeshXZby(mesh, -90);
- break;
- case 2:
- rotateMeshXZby(mesh, 180);
- break;
- case 3:
- rotateMeshXZby(mesh, 90);
- break;
+ case 1: rotateMeshXZby(mesh, -90); break;
+ case 2: rotateMeshXZby(mesh, 180); break;
+ case 3: rotateMeshXZby(mesh, 90); break;
}
switch (axisdir) {
- case 1:
- rotateMeshYZby(mesh, 90);
- break; // z+
- case 2:
- rotateMeshYZby(mesh, -90);
- break; // z-
- case 3:
- rotateMeshXYby(mesh, -90);
- break; // x+
- case 4:
- rotateMeshXYby(mesh, 90);
- break; // x-
- case 5:
- rotateMeshXYby(mesh, -180);
- break;
+ case 1: rotateMeshYZby(mesh, 90); break; // z+
+ case 2: rotateMeshYZby(mesh, -90); break; // z-
+ case 3: rotateMeshXYby(mesh, -90); break; // x+
+ case 4: rotateMeshXYby(mesh, 90); break; // x-
+ case 5: rotateMeshXYby(mesh, -180); break;
}
}
void recalculateBoundingBox(scene::IMesh *src_mesh)
{
aabb3f bbox;
- bbox.reset(0, 0, 0);
+ bbox.reset(0,0,0);
for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
scene::IMeshBuffer *buf = src_mesh->getMeshBuffer(j);
buf->recalculateBoundingBox();
@@ -360,35 +348,35 @@ bool checkMeshNormals(scene::IMesh *mesh)
return true;
}
-scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer)
+scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer)
{
switch (mesh_buffer->getVertexType()) {
case video::EVT_STANDARD: {
- video::S3DVertex *v = (video::S3DVertex *)mesh_buffer->getVertices();
+ video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices();
u16 *indices = mesh_buffer->getIndices();
scene::SMeshBuffer *cloned_buffer = new scene::SMeshBuffer();
cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
- mesh_buffer->getIndexCount());
+ mesh_buffer->getIndexCount());
return cloned_buffer;
}
case video::EVT_2TCOORDS: {
video::S3DVertex2TCoords *v =
- (video::S3DVertex2TCoords *)mesh_buffer->getVertices();
+ (video::S3DVertex2TCoords *) mesh_buffer->getVertices();
u16 *indices = mesh_buffer->getIndices();
scene::SMeshBufferLightMap *cloned_buffer =
- new scene::SMeshBufferLightMap();
+ new scene::SMeshBufferLightMap();
cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
- mesh_buffer->getIndexCount());
+ mesh_buffer->getIndexCount());
return cloned_buffer;
}
case video::EVT_TANGENTS: {
video::S3DVertexTangents *v =
- (video::S3DVertexTangents *)mesh_buffer->getVertices();
+ (video::S3DVertexTangents *) mesh_buffer->getVertices();
u16 *indices = mesh_buffer->getIndices();
scene::SMeshBufferTangents *cloned_buffer =
- new scene::SMeshBufferTangents();
+ new scene::SMeshBufferTangents();
cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
- mesh_buffer->getIndexCount());
+ mesh_buffer->getIndexCount());
return cloned_buffer;
}
}
@@ -397,24 +385,26 @@ scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer)
return NULL;
}
-scene::SMesh *cloneMesh(scene::IMesh *src_mesh)
+scene::SMesh* cloneMesh(scene::IMesh *src_mesh)
{
- scene::SMesh *dst_mesh = new scene::SMesh();
+ scene::SMesh* dst_mesh = new scene::SMesh();
for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
- scene::IMeshBuffer *temp_buf =
- cloneMeshBuffer(src_mesh->getMeshBuffer(j));
+ scene::IMeshBuffer *temp_buf = cloneMeshBuffer(
+ src_mesh->getMeshBuffer(j));
dst_mesh->addMeshBuffer(temp_buf);
temp_buf->drop();
+
}
return dst_mesh;
}
-scene::IMesh *convertNodeboxesToMesh(
- const std::vector<aabb3f> &boxes, const f32 *uv_coords, float expand)
+scene::IMesh* convertNodeboxesToMesh(const std::vector<aabb3f> &boxes,
+ const f32 *uv_coords, float expand)
{
- scene::SMesh *dst_mesh = new scene::SMesh();
+ scene::SMesh* dst_mesh = new scene::SMesh();
- for (u16 j = 0; j < 6; j++) {
+ for (u16 j = 0; j < 6; j++)
+ {
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
@@ -422,7 +412,7 @@ scene::IMesh *convertNodeboxesToMesh(
buf->drop();
}
- video::SColor c(255, 255, 255, 255);
+ video::SColor c(255,255,255,255);
for (aabb3f box : boxes) {
box.repair();
@@ -443,36 +433,18 @@ scene::IMesh *convertNodeboxesToMesh(
f32 tz2 = (box.MaxEdge.Z / BS) + 0.5;
f32 txc_default[24] = {
- // up
- tx1,
- 1 - tz2,
- tx2,
- 1 - tz1,
- // down
- tx1,
- tz1,
- tx2,
- tz2,
- // right
- tz1,
- 1 - ty2,
- tz2,
- 1 - ty1,
- // left
- 1 - tz2,
- 1 - ty2,
- 1 - tz1,
- 1 - ty1,
- // back
- 1 - tx2,
- 1 - ty2,
- 1 - tx1,
- 1 - ty1,
- // front
- tx1,
- 1 - ty2,
- tx2,
- 1 - ty1,
+ // up
+ tx1, 1 - tz2, tx2, 1 - tz1,
+ // down
+ tx1, tz1, tx2, tz2,
+ // right
+ tz1, 1 - ty2, tz2, 1 - ty1,
+ // left
+ 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1,
+ // back
+ 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1,
+ // front
+ tx1, 1 - ty2, tx2, 1 - ty1,
};
// use default texture UV mapping if not provided
@@ -481,66 +453,44 @@ scene::IMesh *convertNodeboxesToMesh(
v3f min = box.MinEdge;
v3f max = box.MaxEdge;
- video::S3DVertex vertices[24] = {
- // up
- video::S3DVertex(min.X, max.Y, max.Z, 0, 1, 0, c, txc[0],
- txc[1]),
- video::S3DVertex(max.X, max.Y, max.Z, 0, 1, 0, c, txc[2],
- txc[1]),
- video::S3DVertex(max.X, max.Y, min.Z, 0, 1, 0, c, txc[2],
- txc[3]),
- video::S3DVertex(min.X, max.Y, min.Z, 0, 1, 0, c, txc[0],
- txc[3]),
- // down
- video::S3DVertex(min.X, min.Y, min.Z, 0, -1, 0, c, txc[4],
- txc[5]),
- video::S3DVertex(max.X, min.Y, min.Z, 0, -1, 0, c, txc[6],
- txc[5]),
- video::S3DVertex(max.X, min.Y, max.Z, 0, -1, 0, c, txc[6],
- txc[7]),
- video::S3DVertex(min.X, min.Y, max.Z, 0, -1, 0, c, txc[4],
- txc[7]),
- // right
- video::S3DVertex(max.X, max.Y, min.Z, 1, 0, 0, c, txc[8],
- txc[9]),
- video::S3DVertex(max.X, max.Y, max.Z, 1, 0, 0, c, txc[10],
- txc[9]),
- video::S3DVertex(max.X, min.Y, max.Z, 1, 0, 0, c, txc[10],
- txc[11]),
- video::S3DVertex(max.X, min.Y, min.Z, 1, 0, 0, c, txc[8],
- txc[11]),
- // left
- video::S3DVertex(min.X, max.Y, max.Z, -1, 0, 0, c,
- txc[12], txc[13]),
- video::S3DVertex(min.X, max.Y, min.Z, -1, 0, 0, c,
- txc[14], txc[13]),
- video::S3DVertex(min.X, min.Y, min.Z, -1, 0, 0, c,
- txc[14], txc[15]),
- video::S3DVertex(min.X, min.Y, max.Z, -1, 0, 0, c,
- txc[12], txc[15]),
- // back
- video::S3DVertex(max.X, max.Y, max.Z, 0, 0, 1, c, txc[16],
- txc[17]),
- video::S3DVertex(min.X, max.Y, max.Z, 0, 0, 1, c, txc[18],
- txc[17]),
- video::S3DVertex(min.X, min.Y, max.Z, 0, 0, 1, c, txc[18],
- txc[19]),
- video::S3DVertex(max.X, min.Y, max.Z, 0, 0, 1, c, txc[16],
- txc[19]),
- // front
- video::S3DVertex(min.X, max.Y, min.Z, 0, 0, -1, c,
- txc[20], txc[21]),
- video::S3DVertex(max.X, max.Y, min.Z, 0, 0, -1, c,
- txc[22], txc[21]),
- video::S3DVertex(max.X, min.Y, min.Z, 0, 0, -1, c,
- txc[22], txc[23]),
- video::S3DVertex(min.X, min.Y, min.Z, 0, 0, -1, c,
- txc[20], txc[23]),
+ video::S3DVertex vertices[24] =
+ {
+ // up
+ video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c, txc[0],txc[1]),
+ video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c, txc[2],txc[1]),
+ video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c, txc[2],txc[3]),
+ video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c, txc[0],txc[3]),
+ // down
+ video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c, txc[4],txc[5]),
+ video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c, txc[6],txc[5]),
+ video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c, txc[6],txc[7]),
+ video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c, txc[4],txc[7]),
+ // right
+ video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c, txc[ 8],txc[9]),
+ video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c, txc[10],txc[9]),
+ video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c, txc[10],txc[11]),
+ video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c, txc[ 8],txc[11]),
+ // left
+ video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c, txc[12],txc[13]),
+ video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c, txc[14],txc[13]),
+ video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c, txc[14],txc[15]),
+ video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c, txc[12],txc[15]),
+ // back
+ video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c, txc[16],txc[17]),
+ video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c, txc[18],txc[17]),
+ video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c, txc[18],txc[19]),
+ video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c, txc[16],txc[19]),
+ // front
+ video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c, txc[20],txc[21]),
+ video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c, txc[22],txc[21]),
+ video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c, txc[22],txc[23]),
+ video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c, txc[20],txc[23]),
};
- u16 indices[] = {0, 1, 2, 2, 3, 0};
+ u16 indices[] = {0,1,2,2,3,0};
- for (u16 j = 0; j < 24; j += 4) {
+ for(u16 j = 0; j < 24; j += 4)
+ {
scene::IMeshBuffer *buf = dst_mesh->getMeshBuffer(j / 4);
buf->append(vertices + j, 4, indices, 6);
}
@@ -573,21 +523,28 @@ float FindVertexScore(vcache *v)
const float ValenceBoostPower = 0.5f;
const float MaxSizeVertexCache = 32.0f;
- if (v->NumActiveTris == 0) {
+ if (v->NumActiveTris == 0)
+ {
// No tri needs this vertex!
return -1.0f;
}
float Score = 0.0f;
int CachePosition = v->cachepos;
- if (CachePosition < 0) {
+ if (CachePosition < 0)
+ {
// Vertex is not in FIFO cache - no score.
- } else {
- if (CachePosition < 3) {
+ }
+ else
+ {
+ if (CachePosition < 3)
+ {
// This vertex was used in the last triangle,
// so it has a fixed score.
Score = LastTriScore;
- } else {
+ }
+ else
+ {
// Points for being high in the cache.
const float Scaler = 1.0f / (MaxSizeVertexCache - 3);
Score = 1.0f - (CachePosition - 3) * Scaler;
@@ -597,7 +554,8 @@ float FindVertexScore(vcache *v)
// Bonus points for having a low number of tris still to
// use the vert, so we get rid of lone verts quickly.
- float ValenceBoost = powf(v->NumActiveTris, -ValenceBoostPower);
+ float ValenceBoost = powf(v->NumActiveTris,
+ -ValenceBoostPower);
Score += ValenceBoostScale * ValenceBoost;
return Score;
@@ -611,7 +569,7 @@ class f_lru
{
public:
- f_lru(vcache *v, tcache *t) : vc(v), tc(t)
+ f_lru(vcache *v, tcache *t): vc(v), tc(t)
{
for (int &i : cache) {
i = -1;
@@ -624,10 +582,13 @@ public:
bool found = false;
// Mark existing pos as empty
- for (u16 i = 0; i < cachesize; i++) {
- if (cache[i] == vert) {
+ for (u16 i = 0; i < cachesize; i++)
+ {
+ if (cache[i] == vert)
+ {
// Move everything down
- for (u16 j = i; j; j--) {
+ for (u16 j = i; j; j--)
+ {
cache[j] = cache[j - 1];
}
@@ -636,12 +597,14 @@ public:
}
}
- if (!found) {
- if (cache[cachesize - 1] != -1)
- vc[cache[cachesize - 1]].cachepos = -1;
+ if (!found)
+ {
+ if (cache[cachesize-1] != -1)
+ vc[cache[cachesize-1]].cachepos = -1;
// Move everything down
- for (u16 i = cachesize - 1; i; i--) {
+ for (u16 i = cachesize - 1; i; i--)
+ {
cache[i] = cache[i - 1];
}
}
@@ -651,9 +614,11 @@ public:
u32 highest = 0;
float hiscore = 0;
- if (updatetris) {
+ if (updatetris)
+ {
// Update cache positions
- for (u16 i = 0; i < cachesize; i++) {
+ for (u16 i = 0; i < cachesize; i++)
+ {
if (cache[i] == -1)
break;
@@ -667,14 +632,17 @@ public:
break;
const u16 trisize = vc[i].tris.size();
- for (u16 t = 0; t < trisize; t++) {
+ for (u16 t = 0; t < trisize; t++)
+ {
tcache *tri = &tc[vc[i].tris[t]];
- tri->score = vc[tri->ind[0]].score +
- vc[tri->ind[1]].score +
- vc[tri->ind[2]].score;
+ tri->score =
+ vc[tri->ind[0]].score +
+ vc[tri->ind[1]].score +
+ vc[tri->ind[2]].score;
- if (tri->score > hiscore) {
+ if (tri->score > hiscore)
+ {
hiscore = tri->score;
highest = vc[i].tris[t];
}
@@ -698,7 +666,7 @@ http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
The function is thread-safe (read: you can optimize several meshes in different threads)
\param mesh Source mesh for the operation. */
-scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh)
+scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh)
{
if (!mesh)
return 0;
@@ -708,12 +676,13 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh)
const u32 mbcount = mesh->getMeshBufferCount();
- for (u32 b = 0; b < mbcount; ++b) {
+ for (u32 b = 0; b < mbcount; ++b)
+ {
const scene::IMeshBuffer *mb = mesh->getMeshBuffer(b);
- if (mb->getIndexType() != video::EIT_16BIT) {
- // os::Printer::log("Cannot optimize a mesh with 32bit indices",
- // ELL_ERROR);
+ if (mb->getIndexType() != video::EIT_16BIT)
+ {
+ //os::Printer::log("Cannot optimize a mesh with 32bit indices", ELL_ERROR);
newmesh->drop();
return 0;
}
@@ -729,26 +698,29 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh)
f_lru lru(vc, tc);
// init
- for (u16 i = 0; i < vcount; i++) {
+ for (u16 i = 0; i < vcount; i++)
+ {
vc[i].score = 0;
vc[i].cachepos = -1;
vc[i].NumActiveTris = 0;
}
// First pass: count how many times a vert is used
- for (u32 i = 0; i < icount; i += 3) {
+ for (u32 i = 0; i < icount; i += 3)
+ {
vc[ind[i]].NumActiveTris++;
vc[ind[i + 1]].NumActiveTris++;
vc[ind[i + 2]].NumActiveTris++;
- const u32 tri_ind = i / 3;
+ const u32 tri_ind = i/3;
tc[tri_ind].ind[0] = ind[i];
tc[tri_ind].ind[1] = ind[i + 1];
tc[tri_ind].ind[2] = ind[i + 2];
}
// Second pass: list of each triangle
- for (u32 i = 0; i < tcount; i++) {
+ for (u32 i = 0; i < tcount; i++)
+ {
vc[tc[i].ind[0]].tris.push_back(i);
vc[tc[i].ind[1]].tris.push_back(i);
vc[tc[i].ind[2]].tris.push_back(i);
@@ -757,308 +729,358 @@ scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh)
}
// Give initial scores
- for (u16 i = 0; i < vcount; i++) {
+ for (u16 i = 0; i < vcount; i++)
+ {
vc[i].score = FindVertexScore(&vc[i]);
}
- for (u32 i = 0; i < tcount; i++) {
- tc[i].score = vc[tc[i].ind[0]].score + vc[tc[i].ind[1]].score +
- vc[tc[i].ind[2]].score;
+ for (u32 i = 0; i < tcount; i++)
+ {
+ tc[i].score =
+ vc[tc[i].ind[0]].score +
+ vc[tc[i].ind[1]].score +
+ vc[tc[i].ind[2]].score;
}
- switch (mb->getVertexType()) {
- case video::EVT_STANDARD: {
- video::S3DVertex *v = (video::S3DVertex *)mb->getVertices();
-
- scene::SMeshBuffer *buf = new scene::SMeshBuffer();
- buf->Material = mb->getMaterial();
-
- buf->Vertices.reallocate(vcount);
- buf->Indices.reallocate(icount);
-
- core::map<const video::S3DVertex, const u16>
- sind; // search index for fast operation
- typedef core::map<const video::S3DVertex, const u16>::Node snode;
-
- // Main algorithm
- u32 highest = 0;
- u32 drawcalls = 0;
- for (;;) {
- if (tc[highest].drawn) {
- bool found = false;
- float hiscore = 0;
- for (u32 t = 0; t < tcount; t++) {
- if (!tc[t].drawn) {
- if (tc[t].score > hiscore) {
- highest = t;
- hiscore = tc[t].score;
- found = true;
+ switch(mb->getVertexType())
+ {
+ case video::EVT_STANDARD:
+ {
+ video::S3DVertex *v = (video::S3DVertex *) mb->getVertices();
+
+ scene::SMeshBuffer *buf = new scene::SMeshBuffer();
+ buf->Material = mb->getMaterial();
+
+ buf->Vertices.reallocate(vcount);
+ buf->Indices.reallocate(icount);
+
+ core::map<const video::S3DVertex, const u16> sind; // search index for fast operation
+ typedef core::map<const video::S3DVertex, const u16>::Node snode;
+
+ // Main algorithm
+ u32 highest = 0;
+ u32 drawcalls = 0;
+ for (;;)
+ {
+ if (tc[highest].drawn)
+ {
+ bool found = false;
+ float hiscore = 0;
+ for (u32 t = 0; t < tcount; t++)
+ {
+ if (!tc[t].drawn)
+ {
+ if (tc[t].score > hiscore)
+ {
+ highest = t;
+ hiscore = tc[t].score;
+ found = true;
+ }
}
}
+ if (!found)
+ break;
}
- if (!found)
- break;
- }
- // Output the best triangle
- u16 newind = buf->Vertices.size();
+ // Output the best triangle
+ u16 newind = buf->Vertices.size();
- snode *s = sind.find(v[tc[highest].ind[0]]);
+ snode *s = sind.find(v[tc[highest].ind[0]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[0]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[0]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[0]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[0]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[1]]);
+ s = sind.find(v[tc[highest].ind[1]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[1]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[1]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[1]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[1]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[2]]);
+ s = sind.find(v[tc[highest].ind[2]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[2]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[2]], newind);
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[2]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[2]], newind);
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- vc[tc[highest].ind[0]].NumActiveTris--;
- vc[tc[highest].ind[1]].NumActiveTris--;
- vc[tc[highest].ind[2]].NumActiveTris--;
+ vc[tc[highest].ind[0]].NumActiveTris--;
+ vc[tc[highest].ind[1]].NumActiveTris--;
+ vc[tc[highest].ind[2]].NumActiveTris--;
- tc[highest].drawn = true;
+ tc[highest].drawn = true;
- for (u16 j : tc[highest].ind) {
- vcache *vert = &vc[j];
- for (u16 t = 0; t < vert->tris.size(); t++) {
- if (highest == vert->tris[t]) {
- vert->tris.erase(t);
- break;
+ for (u16 j : tc[highest].ind) {
+ vcache *vert = &vc[j];
+ for (u16 t = 0; t < vert->tris.size(); t++)
+ {
+ if (highest == vert->tris[t])
+ {
+ vert->tris.erase(t);
+ break;
+ }
}
}
+
+ lru.add(tc[highest].ind[0]);
+ lru.add(tc[highest].ind[1]);
+ highest = lru.add(tc[highest].ind[2], true);
+ drawcalls++;
}
- lru.add(tc[highest].ind[0]);
- lru.add(tc[highest].ind[1]);
- highest = lru.add(tc[highest].ind[2], true);
- drawcalls++;
+ buf->setBoundingBox(mb->getBoundingBox());
+ newmesh->addMeshBuffer(buf);
+ buf->drop();
}
-
- buf->setBoundingBox(mb->getBoundingBox());
- newmesh->addMeshBuffer(buf);
- buf->drop();
- } break;
- case video::EVT_2TCOORDS: {
- video::S3DVertex2TCoords *v =
- (video::S3DVertex2TCoords *)mb->getVertices();
-
- scene::SMeshBufferLightMap *buf =
- new scene::SMeshBufferLightMap();
- buf->Material = mb->getMaterial();
-
- buf->Vertices.reallocate(vcount);
- buf->Indices.reallocate(icount);
-
- core::map<const video::S3DVertex2TCoords, const u16>
- sind; // search index for fast operation
- typedef core::map<const video::S3DVertex2TCoords, const u16>::Node
- snode;
-
- // Main algorithm
- u32 highest = 0;
- u32 drawcalls = 0;
- for (;;) {
- if (tc[highest].drawn) {
- bool found = false;
- float hiscore = 0;
- for (u32 t = 0; t < tcount; t++) {
- if (!tc[t].drawn) {
- if (tc[t].score > hiscore) {
- highest = t;
- hiscore = tc[t].score;
- found = true;
+ break;
+ case video::EVT_2TCOORDS:
+ {
+ video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mb->getVertices();
+
+ scene::SMeshBufferLightMap *buf = new scene::SMeshBufferLightMap();
+ buf->Material = mb->getMaterial();
+
+ buf->Vertices.reallocate(vcount);
+ buf->Indices.reallocate(icount);
+
+ core::map<const video::S3DVertex2TCoords, const u16> sind; // search index for fast operation
+ typedef core::map<const video::S3DVertex2TCoords, const u16>::Node snode;
+
+ // Main algorithm
+ u32 highest = 0;
+ u32 drawcalls = 0;
+ for (;;)
+ {
+ if (tc[highest].drawn)
+ {
+ bool found = false;
+ float hiscore = 0;
+ for (u32 t = 0; t < tcount; t++)
+ {
+ if (!tc[t].drawn)
+ {
+ if (tc[t].score > hiscore)
+ {
+ highest = t;
+ hiscore = tc[t].score;
+ found = true;
+ }
}
}
+ if (!found)
+ break;
}
- if (!found)
- break;
- }
- // Output the best triangle
- u16 newind = buf->Vertices.size();
+ // Output the best triangle
+ u16 newind = buf->Vertices.size();
- snode *s = sind.find(v[tc[highest].ind[0]]);
+ snode *s = sind.find(v[tc[highest].ind[0]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[0]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[0]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[0]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[0]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[1]]);
+ s = sind.find(v[tc[highest].ind[1]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[1]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[1]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[1]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[1]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[2]]);
+ s = sind.find(v[tc[highest].ind[2]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[2]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[2]], newind);
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[2]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[2]], newind);
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- vc[tc[highest].ind[0]].NumActiveTris--;
- vc[tc[highest].ind[1]].NumActiveTris--;
- vc[tc[highest].ind[2]].NumActiveTris--;
+ vc[tc[highest].ind[0]].NumActiveTris--;
+ vc[tc[highest].ind[1]].NumActiveTris--;
+ vc[tc[highest].ind[2]].NumActiveTris--;
- tc[highest].drawn = true;
+ tc[highest].drawn = true;
- for (u16 j : tc[highest].ind) {
- vcache *vert = &vc[j];
- for (u16 t = 0; t < vert->tris.size(); t++) {
- if (highest == vert->tris[t]) {
- vert->tris.erase(t);
- break;
+ for (u16 j : tc[highest].ind) {
+ vcache *vert = &vc[j];
+ for (u16 t = 0; t < vert->tris.size(); t++)
+ {
+ if (highest == vert->tris[t])
+ {
+ vert->tris.erase(t);
+ break;
+ }
}
}
+
+ lru.add(tc[highest].ind[0]);
+ lru.add(tc[highest].ind[1]);
+ highest = lru.add(tc[highest].ind[2]);
+ drawcalls++;
}
- lru.add(tc[highest].ind[0]);
- lru.add(tc[highest].ind[1]);
- highest = lru.add(tc[highest].ind[2]);
- drawcalls++;
- }
+ buf->setBoundingBox(mb->getBoundingBox());
+ newmesh->addMeshBuffer(buf);
+ buf->drop();
- buf->setBoundingBox(mb->getBoundingBox());
- newmesh->addMeshBuffer(buf);
- buf->drop();
-
- } break;
- case video::EVT_TANGENTS: {
- video::S3DVertexTangents *v =
- (video::S3DVertexTangents *)mb->getVertices();
-
- scene::SMeshBufferTangents *buf =
- new scene::SMeshBufferTangents();
- buf->Material = mb->getMaterial();
-
- buf->Vertices.reallocate(vcount);
- buf->Indices.reallocate(icount);
-
- core::map<const video::S3DVertexTangents, const u16>
- sind; // search index for fast operation
- typedef core::map<const video::S3DVertexTangents, const u16>::Node
- snode;
-
- // Main algorithm
- u32 highest = 0;
- u32 drawcalls = 0;
- for (;;) {
- if (tc[highest].drawn) {
- bool found = false;
- float hiscore = 0;
- for (u32 t = 0; t < tcount; t++) {
- if (!tc[t].drawn) {
- if (tc[t].score > hiscore) {
- highest = t;
- hiscore = tc[t].score;
- found = true;
+ }
+ break;
+ case video::EVT_TANGENTS:
+ {
+ video::S3DVertexTangents *v = (video::S3DVertexTangents *) mb->getVertices();
+
+ scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents();
+ buf->Material = mb->getMaterial();
+
+ buf->Vertices.reallocate(vcount);
+ buf->Indices.reallocate(icount);
+
+ core::map<const video::S3DVertexTangents, const u16> sind; // search index for fast operation
+ typedef core::map<const video::S3DVertexTangents, const u16>::Node snode;
+
+ // Main algorithm
+ u32 highest = 0;
+ u32 drawcalls = 0;
+ for (;;)
+ {
+ if (tc[highest].drawn)
+ {
+ bool found = false;
+ float hiscore = 0;
+ for (u32 t = 0; t < tcount; t++)
+ {
+ if (!tc[t].drawn)
+ {
+ if (tc[t].score > hiscore)
+ {
+ highest = t;
+ hiscore = tc[t].score;
+ found = true;
+ }
}
}
+ if (!found)
+ break;
}
- if (!found)
- break;
- }
- // Output the best triangle
- u16 newind = buf->Vertices.size();
+ // Output the best triangle
+ u16 newind = buf->Vertices.size();
- snode *s = sind.find(v[tc[highest].ind[0]]);
+ snode *s = sind.find(v[tc[highest].ind[0]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[0]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[0]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[0]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[0]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[1]]);
+ s = sind.find(v[tc[highest].ind[1]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[1]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[1]], newind);
- newind++;
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[1]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[1]], newind);
+ newind++;
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- s = sind.find(v[tc[highest].ind[2]]);
+ s = sind.find(v[tc[highest].ind[2]]);
- if (!s) {
- buf->Vertices.push_back(v[tc[highest].ind[2]]);
- buf->Indices.push_back(newind);
- sind.insert(v[tc[highest].ind[2]], newind);
- } else {
- buf->Indices.push_back(s->getValue());
- }
+ if (!s)
+ {
+ buf->Vertices.push_back(v[tc[highest].ind[2]]);
+ buf->Indices.push_back(newind);
+ sind.insert(v[tc[highest].ind[2]], newind);
+ }
+ else
+ {
+ buf->Indices.push_back(s->getValue());
+ }
- vc[tc[highest].ind[0]].NumActiveTris--;
- vc[tc[highest].ind[1]].NumActiveTris--;
- vc[tc[highest].ind[2]].NumActiveTris--;
+ vc[tc[highest].ind[0]].NumActiveTris--;
+ vc[tc[highest].ind[1]].NumActiveTris--;
+ vc[tc[highest].ind[2]].NumActiveTris--;
- tc[highest].drawn = true;
+ tc[highest].drawn = true;
- for (u16 j : tc[highest].ind) {
- vcache *vert = &vc[j];
- for (u16 t = 0; t < vert->tris.size(); t++) {
- if (highest == vert->tris[t]) {
- vert->tris.erase(t);
- break;
+ for (u16 j : tc[highest].ind) {
+ vcache *vert = &vc[j];
+ for (u16 t = 0; t < vert->tris.size(); t++)
+ {
+ if (highest == vert->tris[t])
+ {
+ vert->tris.erase(t);
+ break;
+ }
}
}
+
+ lru.add(tc[highest].ind[0]);
+ lru.add(tc[highest].ind[1]);
+ highest = lru.add(tc[highest].ind[2]);
+ drawcalls++;
}
- lru.add(tc[highest].ind[0]);
- lru.add(tc[highest].ind[1]);
- highest = lru.add(tc[highest].ind[2]);
- drawcalls++;
+ buf->setBoundingBox(mb->getBoundingBox());
+ newmesh->addMeshBuffer(buf);
+ buf->drop();
}
-
- buf->setBoundingBox(mb->getBoundingBox());
- newmesh->addMeshBuffer(buf);
- buf->drop();
- } break;
+ break;
}
- delete[] vc;
- delete[] tc;
+ delete [] vc;
+ delete [] tc;
} // for each meshbuffer
diff --git a/src/client/mesh.h b/src/client/mesh.h
index 1698026e8..103c61e45 100644
--- a/src/client/mesh.h
+++ b/src/client/mesh.h
@@ -35,7 +35,7 @@ void applyFacesShading(video::SColor &color, const v3f &normal);
The resulting mesh has 6 materials (up, down, right, left, back, front)
which must be defined by the caller.
*/
-scene::IAnimatedMesh *createCubeMesh(v3f scale);
+scene::IAnimatedMesh* createCubeMesh(v3f scale);
/*
Multiplies each vertex coordinate by the specified scaling factors
@@ -61,8 +61,7 @@ void setMeshColor(scene::IMesh *mesh, const video::SColor &color);
/*
Set a constant color for an animated mesh
*/
-void setAnimatedMeshColor(
- scene::IAnimatedMeshSceneNode *node, const video::SColor &color);
+void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color);
/*!
* Overwrites the color of a mesh buffer.
@@ -76,11 +75,13 @@ void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolo
the normal vector, and choose one of colorX, colorY or
colorZ accordingly.
*/
-void setMeshColorByNormalXYZ(scene::IMesh *mesh, const video::SColor &colorX,
- const video::SColor &colorY, const video::SColor &colorZ);
+void setMeshColorByNormalXYZ(scene::IMesh *mesh,
+ const video::SColor &colorX,
+ const video::SColor &colorY,
+ const video::SColor &colorZ);
-void setMeshColorByNormal(
- scene::IMesh *mesh, const v3f &normal, const video::SColor &color);
+void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal,
+ const video::SColor &color);
/*
Rotate the mesh by 6d facedir value.
@@ -91,20 +92,20 @@ void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir);
/*
Rotate the mesh around the axis and given angle in degrees.
*/
-void rotateMeshXYby(scene::IMesh *mesh, f64 degrees);
-void rotateMeshXZby(scene::IMesh *mesh, f64 degrees);
-void rotateMeshYZby(scene::IMesh *mesh, f64 degrees);
+void rotateMeshXYby (scene::IMesh *mesh, f64 degrees);
+void rotateMeshXZby (scene::IMesh *mesh, f64 degrees);
+void rotateMeshYZby (scene::IMesh *mesh, f64 degrees);
/*
* Clone the mesh buffer.
* The returned pointer should be dropped.
*/
-scene::IMeshBuffer *cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer);
+scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer);
/*
Clone the mesh.
*/
-scene::SMesh *cloneMesh(scene::IMesh *src_mesh);
+scene::SMesh* cloneMesh(scene::IMesh *src_mesh);
/*
Convert nodeboxes to mesh. Each tile goes into a different buffer.
@@ -112,7 +113,7 @@ scene::SMesh *cloneMesh(scene::IMesh *src_mesh);
uv_coords[24] - table of texture uv coords for each cuboid face
expand - factor by which cuboids will be resized
*/
-scene::IMesh *convertNodeboxesToMesh(const std::vector<aabb3f> &boxes,
+scene::IMesh* convertNodeboxesToMesh(const std::vector<aabb3f> &boxes,
const f32 *uv_coords = NULL, float expand = 0);
/*
@@ -131,4 +132,4 @@ bool checkMeshNormals(scene::IMesh *mesh);
http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
Ported from irrlicht 1.8
*/
-scene::IMesh *createForsythOptimizedMesh(const scene::IMesh *mesh);
+scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh);
diff --git a/src/client/mesh_generator_thread.cpp b/src/client/mesh_generator_thread.cpp
index 69d61d5e6..53b980eeb 100644
--- a/src/client/mesh_generator_thread.cpp
+++ b/src/client/mesh_generator_thread.cpp
@@ -48,13 +48,13 @@ QueuedMeshUpdate::~QueuedMeshUpdate()
MeshUpdateQueue
*/
-MeshUpdateQueue::MeshUpdateQueue(Client *client) : m_client(client)
+MeshUpdateQueue::MeshUpdateQueue(Client *client):
+ m_client(client)
{
m_cache_enable_shaders = g_settings->getBool("enable_shaders");
- m_cache_use_tangent_vertices =
- m_cache_enable_shaders &&
- (g_settings->getBool("enable_bumpmapping") ||
- g_settings->getBool("enable_parallax_occlusion"));
+ m_cache_use_tangent_vertices = m_cache_enable_shaders && (
+ g_settings->getBool("enable_bumpmapping") ||
+ g_settings->getBool("enable_parallax_occlusion"));
m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
m_meshgen_block_cache_size = g_settings->getS32("meshgen_block_cache_size");
}
@@ -82,23 +82,22 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool
Cache the block data (force-update the center block, don't update the
neighbors but get them if they aren't already cached)
*/
- std::vector<CachedMapBlockData *> cached_blocks;
+ std::vector<CachedMapBlockData*> cached_blocks;
size_t cache_hit_counter = 0;
- cached_blocks.reserve(3 * 3 * 3);
+ cached_blocks.reserve(3*3*3);
v3s16 dp;
for (dp.X = -1; dp.X <= 1; dp.X++)
- for (dp.Y = -1; dp.Y <= 1; dp.Y++)
- for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
- v3s16 p1 = p + dp;
- CachedMapBlockData *cached_block;
- if (dp == v3s16(0, 0, 0))
- cached_block = cacheBlock(map, p1, FORCE_UPDATE);
- else
- cached_block = cacheBlock(map, p1,
- SKIP_UPDATE_IF_ALREADY_CACHED,
- &cache_hit_counter);
- cached_blocks.push_back(cached_block);
- }
+ for (dp.Y = -1; dp.Y <= 1; dp.Y++)
+ for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
+ v3s16 p1 = p + dp;
+ CachedMapBlockData *cached_block;
+ if (dp == v3s16(0, 0, 0))
+ cached_block = cacheBlock(map, p1, FORCE_UPDATE);
+ else
+ cached_block = cacheBlock(map, p1, SKIP_UPDATE_IF_ALREADY_CACHED,
+ &cache_hit_counter);
+ cached_blocks.push_back(cached_block);
+ }
g_profiler->avg("MeshUpdateQueue: MapBlocks from cache [%]",
100.0f * cache_hit_counter / cached_blocks.size());
@@ -116,7 +115,7 @@ void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool
if (q->p == p) {
// NOTE: We are not adding a new position to the queue, thus
// refcount_from_queue stays the same.
- if (ack_block_to_server)
+ if(ack_block_to_server)
q->ack_block_to_server = true;
q->crack_level = m_client->getCrackLevel();
q->crack_pos = m_client->getCrackPos();
@@ -147,10 +146,10 @@ QueuedMeshUpdate *MeshUpdateQueue::pop()
MutexAutoLock lock(m_mutex);
bool must_be_urgent = !m_urgents.empty();
- for (std::vector<QueuedMeshUpdate *>::iterator i = m_queue.begin();
+ for (std::vector<QueuedMeshUpdate*>::iterator i = m_queue.begin();
i != m_queue.end(); ++i) {
QueuedMeshUpdate *q = *i;
- if (must_be_urgent && m_urgents.count(q->p) == 0)
+ if(must_be_urgent && m_urgents.count(q->p) == 0)
continue;
m_queue.erase(i);
m_urgents.erase(q->p);
@@ -160,11 +159,12 @@ QueuedMeshUpdate *MeshUpdateQueue::pop()
return NULL;
}
-CachedMapBlockData *MeshUpdateQueue::cacheBlock(
- Map *map, v3s16 p, UpdateMode mode, size_t *cache_hit_counter)
+CachedMapBlockData* MeshUpdateQueue::cacheBlock(Map *map, v3s16 p, UpdateMode mode,
+ size_t *cache_hit_counter)
{
CachedMapBlockData *cached_block = nullptr;
- std::map<v3s16, CachedMapBlockData *>::iterator it = m_cache.find(p);
+ std::map<v3s16, CachedMapBlockData*>::iterator it =
+ m_cache.find(p);
if (it != m_cache.end()) {
cached_block = it->second;
@@ -185,11 +185,10 @@ CachedMapBlockData *MeshUpdateQueue::cacheBlock(
MapBlock *b = map->getBlockNoCreateNoEx(p);
if (b) {
if (!cached_block->data)
- cached_block->data = new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE *
- MAP_BLOCKSIZE];
+ cached_block->data =
+ new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE];
memcpy(cached_block->data, b->getData(),
- MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE *
- sizeof(MapNode));
+ MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * sizeof(MapNode));
} else {
delete[] cached_block->data;
cached_block->data = nullptr;
@@ -197,9 +196,9 @@ CachedMapBlockData *MeshUpdateQueue::cacheBlock(
return cached_block;
}
-CachedMapBlockData *MeshUpdateQueue::getCachedBlock(const v3s16 &p)
+CachedMapBlockData* MeshUpdateQueue::getCachedBlock(const v3s16 &p)
{
- std::map<v3s16, CachedMapBlockData *>::iterator it = m_cache.find(p);
+ std::map<v3s16, CachedMapBlockData*>::iterator it = m_cache.find(p);
if (it != m_cache.end()) {
return it->second;
}
@@ -208,8 +207,8 @@ CachedMapBlockData *MeshUpdateQueue::getCachedBlock(const v3s16 &p)
void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q)
{
- MeshMakeData *data = new MeshMakeData(
- m_client, m_cache_enable_shaders, m_cache_use_tangent_vertices);
+ MeshMakeData *data = new MeshMakeData(m_client, m_cache_enable_shaders,
+ m_cache_use_tangent_vertices);
q->data = data;
data->fillBlockDataBegin(q->p);
@@ -219,18 +218,17 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q)
// Collect data for 3*3*3 blocks from cache
v3s16 dp;
for (dp.X = -1; dp.X <= 1; dp.X++)
- for (dp.Y = -1; dp.Y <= 1; dp.Y++)
- for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
- v3s16 p = q->p + dp;
- CachedMapBlockData *cached_block = getCachedBlock(p);
- if (cached_block) {
- cached_block->refcount_from_queue--;
- cached_block->last_used_timestamp = t_now;
- if (cached_block->data)
- data->fillBlockData(
- dp, cached_block->data);
- }
- }
+ for (dp.Y = -1; dp.Y <= 1; dp.Y++)
+ for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
+ v3s16 p = q->p + dp;
+ CachedMapBlockData *cached_block = getCachedBlock(p);
+ if (cached_block) {
+ cached_block->refcount_from_queue--;
+ cached_block->last_used_timestamp = t_now;
+ if (cached_block->data)
+ data->fillBlockData(dp, cached_block->data);
+ }
+ }
data->setCrack(q->crack_level, q->crack_pos);
data->setSmoothLighting(m_cache_smooth_lighting);
@@ -239,7 +237,7 @@ void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q)
void MeshUpdateQueue::cleanupCache()
{
const int mapblock_kB = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE *
- sizeof(MapNode) / 1000;
+ sizeof(MapNode) / 1000;
g_profiler->avg("MeshUpdateQueue MapBlock cache size kB",
mapblock_kB * m_cache.size());
@@ -247,20 +245,16 @@ void MeshUpdateQueue::cleanupCache()
// anything get older than cache_seconds_max or deleted before 2 seconds.
const int cache_seconds_max = 10;
const int cache_soft_max_size = m_meshgen_block_cache_size * 1000 / mapblock_kB;
- int cache_seconds = MYMAX(2,
- cache_seconds_max -
- m_cache.size() /
- (cache_soft_max_size /
- cache_seconds_max));
+ int cache_seconds = MYMAX(2, cache_seconds_max -
+ m_cache.size() / (cache_soft_max_size / cache_seconds_max));
int t_now = time(0);
- for (std::map<v3s16, CachedMapBlockData *>::iterator it = m_cache.begin();
- it != m_cache.end();) {
+ for (std::map<v3s16, CachedMapBlockData*>::iterator it = m_cache.begin();
+ it != m_cache.end(); ) {
CachedMapBlockData *cached_block = it->second;
if (cached_block->refcount_from_queue == 0 &&
- cached_block->last_used_timestamp <
- t_now - cache_seconds) {
+ cached_block->last_used_timestamp < t_now - cache_seconds) {
m_cache.erase(it++);
delete cached_block;
} else {
@@ -273,15 +267,16 @@ void MeshUpdateQueue::cleanupCache()
MeshUpdateThread
*/
-MeshUpdateThread::MeshUpdateThread(Client *client) :
- UpdateThread("Mesh"), m_queue_in(client)
+MeshUpdateThread::MeshUpdateThread(Client *client):
+ UpdateThread("Mesh"),
+ m_queue_in(client)
{
m_generation_interval = g_settings->getU16("mesh_generation_interval");
m_generation_interval = rangelim(m_generation_interval, 0, 50);
}
-void MeshUpdateThread::updateBlock(
- Map *map, v3s16 p, bool ack_block_to_server, bool urgent)
+void MeshUpdateThread::updateBlock(Map *map, v3s16 p, bool ack_block_to_server,
+ bool urgent)
{
// Allow the MeshUpdateQueue to do whatever it wants
m_queue_in.addBlock(map, p, ack_block_to_server, urgent);
diff --git a/src/client/minimap.cpp b/src/client/minimap.cpp
index e321aaae5..68770ec19 100644
--- a/src/client/minimap.cpp
+++ b/src/client/minimap.cpp
@@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "mapblock.h"
#include "client/renderingengine.h"
+
////
//// MinimapUpdateThread
////
@@ -57,7 +58,7 @@ bool MinimapUpdateThread::pushBlockUpdate(v3s16 pos, MinimapMapblock *data)
// Add the block
QueuedMinimapUpdate q;
- q.pos = pos;
+ q.pos = pos;
q.data = data;
m_update_queue.push_back(q);
@@ -83,6 +84,7 @@ void MinimapUpdateThread::enqueueBlock(v3s16 pos, MinimapMapblock *data)
deferUpdate();
}
+
void MinimapUpdateThread::doUpdate()
{
QueuedMinimapUpdate update;
@@ -90,9 +92,8 @@ void MinimapUpdateThread::doUpdate()
while (popBlockUpdate(&update)) {
if (update.data) {
// Swap two values in the map using single lookup
- std::pair<std::map<v3s16, MinimapMapblock *>::iterator, bool>
- result = m_blocks_cache.insert(std::make_pair(
- update.pos, update.data));
+ std::pair<std::map<v3s16, MinimapMapblock*>::iterator, bool>
+ result = m_blocks_cache.insert(std::make_pair(update.pos, update.data));
if (!result.second) {
delete result.first->second;
result.first->second = update.data;
@@ -120,60 +121,51 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height)
v3s16 blockpos_min = getNodeBlockPos(pos_min);
v3s16 blockpos_max = getNodeBlockPos(pos_max);
- // clear the map
+// clear the map
for (int z = 0; z < size; z++)
- for (int x = 0; x < size; x++) {
- MinimapPixel &mmpixel = data->minimap_scan[x + z * size];
- mmpixel.air_count = 0;
- mmpixel.height = 0;
- mmpixel.n = MapNode(CONTENT_AIR);
- }
+ for (int x = 0; x < size; x++) {
+ MinimapPixel &mmpixel = data->minimap_scan[x + z * size];
+ mmpixel.air_count = 0;
+ mmpixel.height = 0;
+ mmpixel.n = MapNode(CONTENT_AIR);
+ }
- // draw the map
+// draw the map
v3s16 blockpos;
for (blockpos.Z = blockpos_min.Z; blockpos.Z <= blockpos_max.Z; ++blockpos.Z)
- for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y;
- ++blockpos.Y)
- for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X;
- ++blockpos.X) {
- std::map<v3s16, MinimapMapblock *>::const_iterator
- pblock = m_blocks_cache.find(blockpos);
- if (pblock == m_blocks_cache.end())
- continue;
- const MinimapMapblock &block = *pblock->second;
-
- v3s16 block_node_min(blockpos * MAP_BLOCKSIZE);
- v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1);
- // clip
- v3s16 range_min = componentwise_max(
- block_node_min, pos_min);
- v3s16 range_max = componentwise_min(
- block_node_max, pos_max);
-
- v3s16 pos;
- pos.Y = range_min.Y;
- for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z)
- for (pos.X = range_min.X; pos.X <= range_max.X;
- ++pos.X) {
- v3s16 inblock_pos = pos - block_node_min;
- const MinimapPixel &in_pixel =
- block.data[inblock_pos.Z * MAP_BLOCKSIZE +
- inblock_pos.X];
-
- v3s16 inmap_pos = pos - pos_min;
- MinimapPixel &out_pixel =
- data->minimap_scan[inmap_pos.X +
- inmap_pos.Z * size];
-
- out_pixel.air_count += in_pixel.air_count;
- if (in_pixel.n.param0 != CONTENT_AIR) {
- out_pixel.n = in_pixel.n;
- out_pixel.height =
- inmap_pos.Y +
- in_pixel.height;
- }
- }
+ for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y; ++blockpos.Y)
+ for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X; ++blockpos.X) {
+ std::map<v3s16, MinimapMapblock *>::const_iterator pblock =
+ m_blocks_cache.find(blockpos);
+ if (pblock == m_blocks_cache.end())
+ continue;
+ const MinimapMapblock &block = *pblock->second;
+
+ v3s16 block_node_min(blockpos * MAP_BLOCKSIZE);
+ v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1);
+ // clip
+ v3s16 range_min = componentwise_max(block_node_min, pos_min);
+ v3s16 range_max = componentwise_min(block_node_max, pos_max);
+
+ v3s16 pos;
+ pos.Y = range_min.Y;
+ for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z)
+ for (pos.X = range_min.X; pos.X <= range_max.X; ++pos.X) {
+ v3s16 inblock_pos = pos - block_node_min;
+ const MinimapPixel &in_pixel =
+ block.data[inblock_pos.Z * MAP_BLOCKSIZE + inblock_pos.X];
+
+ v3s16 inmap_pos = pos - pos_min;
+ MinimapPixel &out_pixel =
+ data->minimap_scan[inmap_pos.X + inmap_pos.Z * size];
+
+ out_pixel.air_count += in_pixel.air_count;
+ if (in_pixel.n.param0 != CONTENT_AIR) {
+ out_pixel.n = in_pixel.n;
+ out_pixel.height = inmap_pos.Y + in_pixel.height;
}
+ }
+ }
}
////
@@ -182,40 +174,40 @@ void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height)
Minimap::Minimap(Client *client)
{
- this->client = client;
- this->driver = RenderingEngine::get_video_driver();
- this->m_tsrc = client->getTextureSource();
+ this->client = client;
+ this->driver = RenderingEngine::get_video_driver();
+ this->m_tsrc = client->getTextureSource();
this->m_shdrsrc = client->getShaderSource();
- this->m_ndef = client->getNodeDefManager();
+ this->m_ndef = client->getNodeDefManager();
m_angle = 0.f;
// Initialize static settings
m_enable_shaders = g_settings->getBool("enable_shaders");
m_surface_mode_scan_height =
- g_settings->getBool("minimap_double_scan_height") ? 256 : 128;
+ g_settings->getBool("minimap_double_scan_height") ? 256 : 128;
// Initialize minimap data
data = new MinimapData;
- data->mode = MINIMAP_MODE_OFF;
- data->is_radar = false;
- data->map_invalidated = true;
- data->texture = NULL;
+ data->mode = MINIMAP_MODE_OFF;
+ data->is_radar = false;
+ data->map_invalidated = true;
+ data->texture = NULL;
data->heightmap_texture = NULL;
data->minimap_shape_round = g_settings->getBool("minimap_shape_round");
// Get round minimap textures
data->minimap_mask_round = driver->createImage(
- m_tsrc->getTexture("minimap_mask_round.png"),
- core::position2d<s32>(0, 0),
- core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
+ m_tsrc->getTexture("minimap_mask_round.png"),
+ core::position2d<s32>(0, 0),
+ core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
data->minimap_overlay_round = m_tsrc->getTexture("minimap_overlay_round.png");
// Get square minimap textures
data->minimap_mask_square = driver->createImage(
- m_tsrc->getTexture("minimap_mask_square.png"),
- core::position2d<s32>(0, 0),
- core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
+ m_tsrc->getTexture("minimap_mask_square.png"),
+ core::position2d<s32>(0, 0),
+ core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
data->minimap_overlay_square = m_tsrc->getTexture("minimap_overlay_square.png");
// Create player marker texture
@@ -290,21 +282,25 @@ MinimapShape Minimap::getMinimapShape()
void Minimap::setMinimapMode(MinimapMode mode)
{
- static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = {{false, 0, 0},
- {false, m_surface_mode_scan_height, 256},
- {false, m_surface_mode_scan_height, 128},
- {false, m_surface_mode_scan_height, 64}, {true, 32, 128},
- {true, 32, 64}, {true, 32, 32}};
+ static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = {
+ {false, 0, 0},
+ {false, m_surface_mode_scan_height, 256},
+ {false, m_surface_mode_scan_height, 128},
+ {false, m_surface_mode_scan_height, 64},
+ {true, 32, 128},
+ {true, 32, 64},
+ {true, 32, 32}
+ };
if (mode >= MINIMAP_MODE_COUNT)
return;
MutexAutoLock lock(m_mutex);
- data->is_radar = modedefs[mode].is_radar;
+ data->is_radar = modedefs[mode].is_radar;
data->scan_height = modedefs[mode].scan_height;
- data->map_size = modedefs[mode].map_size;
- data->mode = mode;
+ data->map_size = modedefs[mode].map_size;
+ data->mode = mode;
m_minimap_update_thread->deferUpdate();
}
@@ -336,55 +332,47 @@ void Minimap::blitMinimapPixelsToImageRadar(video::IImage *map_image)
{
video::SColor c(240, 0, 0, 0);
for (s16 x = 0; x < data->map_size; x++)
- for (s16 z = 0; z < data->map_size; z++) {
- MinimapPixel *mmpixel =
- &data->minimap_scan[x + z * data->map_size];
-
- if (mmpixel->air_count > 0)
- c.setGreen(core::clamp(
- core::round32(32 +
- mmpixel->air_count * 8),
- 0, 255));
- else
- c.setGreen(0);
-
- map_image->setPixel(x, data->map_size - z - 1, c);
- }
+ for (s16 z = 0; z < data->map_size; z++) {
+ MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
+
+ if (mmpixel->air_count > 0)
+ c.setGreen(core::clamp(core::round32(32 + mmpixel->air_count * 8), 0, 255));
+ else
+ c.setGreen(0);
+
+ map_image->setPixel(x, data->map_size - z - 1, c);
+ }
}
void Minimap::blitMinimapPixelsToImageSurface(
- video::IImage *map_image, video::IImage *heightmap_image)
+ video::IImage *map_image, video::IImage *heightmap_image)
{
// This variable creation/destruction has a 1% cost on rendering minimap
video::SColor tilecolor;
for (s16 x = 0; x < data->map_size; x++)
- for (s16 z = 0; z < data->map_size; z++) {
- MinimapPixel *mmpixel =
- &data->minimap_scan[x + z * data->map_size];
-
- const ContentFeatures &f = m_ndef->get(mmpixel->n);
- const TileDef *tile = &f.tiledef[0];
-
- // Color of the 0th tile (mostly this is the topmost)
- if (tile->has_color)
- tilecolor = tile->color;
- else
- mmpixel->n.getColor(f, &tilecolor);
-
- tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() /
- 255);
- tilecolor.setGreen(tilecolor.getGreen() *
- f.minimap_color.getGreen() / 255);
- tilecolor.setBlue(tilecolor.getBlue() *
- f.minimap_color.getBlue() / 255);
- tilecolor.setAlpha(240);
-
- map_image->setPixel(x, data->map_size - z - 1, tilecolor);
-
- u32 h = mmpixel->height;
- heightmap_image->setPixel(x, data->map_size - z - 1,
- video::SColor(255, h, h, h));
- }
+ for (s16 z = 0; z < data->map_size; z++) {
+ MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
+
+ const ContentFeatures &f = m_ndef->get(mmpixel->n);
+ const TileDef *tile = &f.tiledef[0];
+
+ // Color of the 0th tile (mostly this is the topmost)
+ if(tile->has_color)
+ tilecolor = tile->color;
+ else
+ mmpixel->n.getColor(f, &tilecolor);
+
+ tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / 255);
+ tilecolor.setGreen(tilecolor.getGreen() * f.minimap_color.getGreen() / 255);
+ tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255);
+ tilecolor.setAlpha(240);
+
+ map_image->setPixel(x, data->map_size - z - 1, tilecolor);
+
+ u32 h = mmpixel->height;
+ heightmap_image->setPixel(x,data->map_size - z - 1,
+ video::SColor(255, h, h, h));
+ }
}
video::ITexture *Minimap::getMinimapTexture()
@@ -395,10 +383,10 @@ video::ITexture *Minimap::getMinimapTexture()
// create minimap and heightmap images in memory
core::dimension2d<u32> dim(data->map_size, data->map_size);
- video::IImage *map_image = driver->createImage(video::ECF_A8R8G8B8, dim);
+ video::IImage *map_image = driver->createImage(video::ECF_A8R8G8B8, dim);
video::IImage *heightmap_image = driver->createImage(video::ECF_A8R8G8B8, dim);
- video::IImage *minimap_image = driver->createImage(video::ECF_A8R8G8B8,
- core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
+ video::IImage *minimap_image = driver->createImage(video::ECF_A8R8G8B8,
+ core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
// Blit MinimapPixels to images
if (data->is_radar)
@@ -409,19 +397,16 @@ video::ITexture *Minimap::getMinimapTexture()
map_image->copyToScaling(minimap_image);
map_image->drop();
- video::IImage *minimap_mask = data->minimap_shape_round
- ? data->minimap_mask_round
- : data->minimap_mask_square;
+ video::IImage *minimap_mask = data->minimap_shape_round ?
+ data->minimap_mask_round : data->minimap_mask_square;
if (minimap_mask) {
for (s16 y = 0; y < MINIMAP_MAX_SY; y++)
- for (s16 x = 0; x < MINIMAP_MAX_SX; x++) {
- const video::SColor &mask_col =
- minimap_mask->getPixel(x, y);
- if (!mask_col.getAlpha())
- minimap_image->setPixel(
- x, y, video::SColor(0, 0, 0, 0));
- }
+ for (s16 x = 0; x < MINIMAP_MAX_SX; x++) {
+ const video::SColor &mask_col = minimap_mask->getPixel(x, y);
+ if (!mask_col.getAlpha())
+ minimap_image->setPixel(x, y, video::SColor(0,0,0,0));
+ }
}
if (data->texture)
@@ -431,7 +416,7 @@ video::ITexture *Minimap::getMinimapTexture()
data->texture = driver->addTexture("minimap__", minimap_image);
data->heightmap_texture =
- driver->addTexture("minimap_heightmap__", heightmap_image);
+ driver->addTexture("minimap_heightmap__", heightmap_image);
minimap_image->drop();
heightmap_image->drop();
@@ -443,8 +428,10 @@ video::ITexture *Minimap::getMinimapTexture()
v3f Minimap::getYawVec()
{
if (data->minimap_shape_round) {
- return v3f(std::cos(m_angle * core::DEGTORAD),
- std::sin(m_angle * core::DEGTORAD), 1.0);
+ return v3f(
+ std::cos(m_angle * core::DEGTORAD),
+ std::sin(m_angle * core::DEGTORAD),
+ 1.0);
}
return v3f(1.0, 0.0, 1.0);
@@ -458,9 +445,9 @@ scene::SMeshBuffer *Minimap::getMinimapMeshBuffer()
static const video::SColor c(255, 255, 255, 255);
buf->Vertices[0] = video::S3DVertex(-1, -1, 0, 0, 0, 1, c, 0, 1);
- buf->Vertices[1] = video::S3DVertex(-1, 1, 0, 0, 0, 1, c, 0, 0);
- buf->Vertices[2] = video::S3DVertex(1, 1, 0, 0, 0, 1, c, 1, 0);
- buf->Vertices[3] = video::S3DVertex(1, -1, 0, 0, 0, 1, c, 1, 1);
+ buf->Vertices[1] = video::S3DVertex(-1, 1, 0, 0, 0, 1, c, 0, 0);
+ buf->Vertices[2] = video::S3DVertex( 1, 1, 0, 0, 0, 1, c, 1, 0);
+ buf->Vertices[3] = video::S3DVertex( 1, -1, 0, 0, 0, 1, c, 1, 1);
buf->Indices[0] = 0;
buf->Indices[1] = 1;
@@ -487,7 +474,8 @@ void Minimap::drawMinimap()
core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW);
driver->setViewPort(core::rect<s32>(
- screensize.X - size - 10, 10, screensize.X - 10, size + 10));
+ screensize.X - size - 10, 10,
+ screensize.X - 10, size + 10));
driver->setTransform(video::ETS_PROJECTION, core::matrix4());
driver->setTransform(video::ETS_VIEW, core::matrix4());
@@ -516,9 +504,8 @@ void Minimap::drawMinimap()
driver->drawMeshBuffer(m_meshbuffer);
// Draw overlay
- video::ITexture *minimap_overlay = data->minimap_shape_round
- ? data->minimap_overlay_round
- : data->minimap_overlay_square;
+ video::ITexture *minimap_overlay = data->minimap_shape_round ?
+ data->minimap_overlay_round : data->minimap_overlay_square;
material.TextureLayer[0].Texture = minimap_overlay;
material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
driver->setMaterial(material);
@@ -549,8 +536,9 @@ void Minimap::drawMinimap()
static const video::SColor c[4] = {col, col, col, col};
f32 sin_angle = std::sin(m_angle * core::DEGTORAD);
f32 cos_angle = std::cos(m_angle * core::DEGTORAD);
- s32 marker_size2 = 0.025 * (float)size;
- for (std::list<v2f>::const_iterator i = m_active_markers.begin();
+ s32 marker_size2 = 0.025 * (float)size;
+ for (std::list<v2f>::const_iterator
+ i = m_active_markers.begin();
i != m_active_markers.end(); ++i) {
v2f posf = *i;
if (data->minimap_shape_round) {
@@ -561,36 +549,34 @@ void Minimap::drawMinimap()
}
posf.X = (posf.X + 0.5) * (float)size;
posf.Y = (posf.Y + 0.5) * (float)size;
- core::rect<s32> dest_rect(s_pos.X + posf.X - marker_size2,
- s_pos.Y + posf.Y - marker_size2,
- s_pos.X + posf.X + marker_size2,
- s_pos.Y + posf.Y + marker_size2);
- driver->draw2DImage(data->object_marker_red, dest_rect, img_rect,
- &dest_rect, &c[0], true);
+ core::rect<s32> dest_rect(
+ s_pos.X + posf.X - marker_size2,
+ s_pos.Y + posf.Y - marker_size2,
+ s_pos.X + posf.X + marker_size2,
+ s_pos.Y + posf.Y + marker_size2);
+ driver->draw2DImage(data->object_marker_red, dest_rect,
+ img_rect, &dest_rect, &c[0], true);
}
}
void Minimap::updateActiveMarkers()
{
- video::IImage *minimap_mask = data->minimap_shape_round
- ? data->minimap_mask_round
- : data->minimap_mask_square;
+ video::IImage *minimap_mask = data->minimap_shape_round ?
+ data->minimap_mask_round : data->minimap_mask_square;
const std::list<Nametag *> &nametags = client->getCamera()->getNametags();
m_active_markers.clear();
for (Nametag *nametag : nametags) {
- v3s16 pos = floatToInt(
- nametag->parent_node->getAbsolutePosition() +
- intToFloat(client->getCamera()->getOffset(),
- BS),
- BS);
- pos -= data->pos - v3s16(data->map_size / 2, data->scan_height / 2,
- data->map_size / 2);
- if (pos.X < 0 || pos.X > data->map_size || pos.Y < 0 ||
- pos.Y > data->scan_height || pos.Z < 0 ||
- pos.Z > data->map_size) {
+ v3s16 pos = floatToInt(nametag->parent_node->getAbsolutePosition() +
+ intToFloat(client->getCamera()->getOffset(), BS), BS);
+ pos -= data->pos - v3s16(data->map_size / 2,
+ data->scan_height / 2,
+ data->map_size / 2);
+ if (pos.X < 0 || pos.X > data->map_size ||
+ pos.Y < 0 || pos.Y > data->scan_height ||
+ pos.Z < 0 || pos.Z > data->map_size) {
continue;
}
pos.X = ((float)pos.X / data->map_size) * MINIMAP_MAX_SX;
@@ -600,9 +586,8 @@ void Minimap::updateActiveMarkers()
continue;
}
- m_active_markers.emplace_back(
- ((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5,
- (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5);
+ m_active_markers.emplace_back(((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5,
+ (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5);
}
}
@@ -614,26 +599,26 @@ void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos
{
for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
- for (s16 z = 0; z < MAP_BLOCKSIZE; z++) {
- s16 air_count = 0;
- bool surface_found = false;
- MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x];
-
- for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) {
- v3s16 p(x, y, z);
- MapNode n = vmanip->getNodeNoEx(pos + p);
- if (!surface_found && n.getContent() != CONTENT_AIR) {
- mmpixel->height = y;
- mmpixel->n = n;
- surface_found = true;
- } else if (n.getContent() == CONTENT_AIR) {
- air_count++;
- }
+ for (s16 z = 0; z < MAP_BLOCKSIZE; z++) {
+ s16 air_count = 0;
+ bool surface_found = false;
+ MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x];
+
+ for (s16 y = MAP_BLOCKSIZE -1; y >= 0; y--) {
+ v3s16 p(x, y, z);
+ MapNode n = vmanip->getNodeNoEx(pos + p);
+ if (!surface_found && n.getContent() != CONTENT_AIR) {
+ mmpixel->height = y;
+ mmpixel->n = n;
+ surface_found = true;
+ } else if (n.getContent() == CONTENT_AIR) {
+ air_count++;
}
+ }
- if (!surface_found)
- mmpixel->n = MapNode(CONTENT_AIR);
+ if (!surface_found)
+ mmpixel->n = MapNode(CONTENT_AIR);
- mmpixel->air_count = air_count;
- }
+ mmpixel->air_count = air_count;
+ }
}
diff --git a/src/client/minimap.h b/src/client/minimap.h
index dc4db514a..258d5330d 100644
--- a/src/client/minimap.h
+++ b/src/client/minimap.h
@@ -33,8 +33,7 @@ class IShaderSource;
#define MINIMAP_MAX_SX 512
#define MINIMAP_MAX_SY 512
-enum MinimapMode
-{
+enum MinimapMode {
MINIMAP_MODE_OFF,
MINIMAP_MODE_SURFACEx1,
MINIMAP_MODE_SURFACEx2,
@@ -45,36 +44,31 @@ enum MinimapMode
MINIMAP_MODE_COUNT,
};
-enum MinimapShape
-{
+enum MinimapShape {
MINIMAP_SHAPE_SQUARE,
MINIMAP_SHAPE_ROUND,
};
-struct MinimapModeDef
-{
+struct MinimapModeDef {
bool is_radar;
u16 scan_height;
u16 map_size;
};
-struct MinimapPixel
-{
+struct MinimapPixel {
//! The topmost node that the minimap displays.
MapNode n;
u16 height;
u16 air_count;
};
-struct MinimapMapblock
-{
+struct MinimapMapblock {
void getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos);
MinimapPixel data[MAP_BLOCKSIZE * MAP_BLOCKSIZE];
};
-struct MinimapData
-{
+struct MinimapData {
bool is_radar;
MinimapMode mode;
v3s16 pos;
@@ -94,14 +88,12 @@ struct MinimapData
video::ITexture *object_marker_red = nullptr;
};
-struct QueuedMinimapUpdate
-{
+struct QueuedMinimapUpdate {
v3s16 pos;
MinimapMapblock *data = nullptr;
};
-class MinimapUpdateThread : public UpdateThread
-{
+class MinimapUpdateThread : public UpdateThread {
public:
MinimapUpdateThread() : UpdateThread("Minimap") {}
virtual ~MinimapUpdateThread();
@@ -122,8 +114,7 @@ private:
std::map<v3s16, MinimapMapblock *> m_blocks_cache;
};
-class Minimap
-{
+class Minimap {
public:
Minimap(Client *client);
~Minimap();
@@ -142,11 +133,12 @@ public:
void setMinimapShape(MinimapShape shape);
MinimapShape getMinimapShape();
+
video::ITexture *getMinimapTexture();
void blitMinimapPixelsToImageRadar(video::IImage *map_image);
- void blitMinimapPixelsToImageSurface(
- video::IImage *map_image, video::IImage *heightmap_image);
+ void blitMinimapPixelsToImageSurface(video::IImage *map_image,
+ video::IImage *heightmap_image);
scene::SMeshBuffer *getMinimapMeshBuffer();
@@ -154,7 +146,7 @@ public:
void drawMinimap();
video::IVideoDriver *driver;
- Client *client;
+ Client* client;
MinimapData *data;
private:
diff --git a/src/client/particles.cpp b/src/client/particles.cpp
index 5885987fc..7acd996dc 100644
--- a/src/client/particles.cpp
+++ b/src/client/particles.cpp
@@ -44,20 +44,28 @@ static f32 random_f32(f32 min, f32 max)
static v3f random_v3f(v3f min, v3f max)
{
- return v3f(random_f32(min.X, max.X), random_f32(min.Y, max.Y),
- random_f32(min.Z, max.Z));
+ return v3f(
+ random_f32(min.X, max.X),
+ random_f32(min.Y, max.Y),
+ random_f32(min.Z, max.Z));
}
/*
Particle
*/
-Particle::Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *env,
- const ParticleParameters &p, video::ITexture *texture, v2f texpos,
- v2f texsize, video::SColor color) :
- scene::ISceneNode(
- RenderingEngine::get_scene_manager()->getRootSceneNode(),
- RenderingEngine::get_scene_manager())
+Particle::Particle(
+ IGameDef *gamedef,
+ LocalPlayer *player,
+ ClientEnvironment *env,
+ const ParticleParameters &p,
+ video::ITexture *texture,
+ v2f texpos,
+ v2f texsize,
+ video::SColor color
+):
+ scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
+ RenderingEngine::get_scene_manager())
{
// Misc
m_gamedef = gamedef;
@@ -106,8 +114,7 @@ Particle::Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *en
void Particle::OnRegisterSceneNode()
{
if (IsVisible)
- SceneManager->registerNodeForRendering(
- this, scene::ESNRP_TRANSPARENT_EFFECT);
+ SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT_EFFECT);
ISceneNode::OnRegisterSceneNode();
}
@@ -118,8 +125,9 @@ void Particle::render()
driver->setMaterial(m_material);
driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
- u16 indices[] = {0, 1, 2, 2, 3, 0};
- driver->drawVertexPrimitiveList(m_vertices, 4, indices, 2, video::EVT_STANDARD,
+ u16 indices[] = {0,1,2, 2,3,0};
+ driver->drawVertexPrimitiveList(m_vertices, 4,
+ indices, 2, video::EVT_STANDARD,
scene::EPT_TRIANGLES, video::EIT_16BIT);
}
@@ -131,8 +139,8 @@ void Particle::step(float dtime)
v3f p_pos = m_pos * BS;
v3f p_velocity = m_velocity * BS;
collisionMoveResult r = collisionMoveSimple(m_env, m_gamedef, BS * 0.5f,
- box, 0.0f, dtime, &p_pos, &p_velocity,
- m_acceleration * BS, nullptr, m_object_collision);
+ box, 0.0f, dtime, &p_pos, &p_velocity, m_acceleration * BS, nullptr,
+ m_object_collision);
if (m_collision_removal && r.collides) {
// force expiration of the particle
m_expiration = -1.0;
@@ -147,7 +155,8 @@ void Particle::step(float dtime)
if (m_animation.type != TAT_NONE) {
m_animation_time += dtime;
int frame_length_i, frame_count;
- m_animation.determineParams(m_material.getTexture(0)->getSize(),
+ m_animation.determineParams(
+ m_material.getTexture(0)->getSize(),
&frame_count, &frame_length_i, NULL);
float frame_length = frame_length_i / 1000.0;
while (m_animation_time > frame_length) {
@@ -168,7 +177,11 @@ void Particle::updateLight()
u8 light = 0;
bool pos_ok;
- v3s16 p = v3s16(floor(m_pos.X + 0.5), floor(m_pos.Y + 0.5), floor(m_pos.Z + 0.5));
+ v3s16 p = v3s16(
+ floor(m_pos.X+0.5),
+ floor(m_pos.Y+0.5),
+ floor(m_pos.Z+0.5)
+ );
MapNode n = m_env->getClientMap().getNode(p, &pos_ok);
if (pos_ok)
light = n.getLightBlend(m_env->getDayNightRatio(), m_gamedef->ndef());
@@ -176,9 +189,10 @@ void Particle::updateLight()
light = blend_light(m_env->getDayNightRatio(), LIGHT_SUN, 0);
u8 m_light = decode_light(light + m_glow);
- m_color.set(255, m_light * m_base_color.getRed() / 255,
- m_light * m_base_color.getGreen() / 255,
- m_light * m_base_color.getBlue() / 255);
+ m_color.set(255,
+ m_light * m_base_color.getRed() / 255,
+ m_light * m_base_color.getGreen() / 255,
+ m_light * m_base_color.getBlue() / 255);
}
void Particle::updateVertices()
@@ -191,8 +205,7 @@ void Particle::updateVertices()
v2u32 framesize;
texcoord = m_animation.getTextureCoords(texsize, m_animation_frame);
m_animation.determineParams(texsize, NULL, NULL, &framesize);
- framesize_f = v2f(framesize.X / (float)texsize.X,
- framesize.Y / (float)texsize.Y);
+ framesize_f = v2f(framesize.X / (float) texsize.X, framesize.Y / (float) texsize.Y);
tx0 = m_texpos.X + texcoord.X;
tx1 = m_texpos.X + texcoord.X + framesize_f.X * m_texsize.X;
@@ -205,29 +218,27 @@ void Particle::updateVertices()
ty1 = m_texpos.Y + m_texsize.Y;
}
- m_vertices[0] = video::S3DVertex(
- -m_size / 2, -m_size / 2, 0, 0, 0, 0, m_color, tx0, ty1);
- m_vertices[1] = video::S3DVertex(
- m_size / 2, -m_size / 2, 0, 0, 0, 0, m_color, tx1, ty1);
- m_vertices[2] = video::S3DVertex(
- m_size / 2, m_size / 2, 0, 0, 0, 0, m_color, tx1, ty0);
- m_vertices[3] = video::S3DVertex(
- -m_size / 2, m_size / 2, 0, 0, 0, 0, m_color, tx0, ty0);
+ m_vertices[0] = video::S3DVertex(-m_size / 2, -m_size / 2,
+ 0, 0, 0, 0, m_color, tx0, ty1);
+ m_vertices[1] = video::S3DVertex(m_size / 2, -m_size / 2,
+ 0, 0, 0, 0, m_color, tx1, ty1);
+ m_vertices[2] = video::S3DVertex(m_size / 2, m_size / 2,
+ 0, 0, 0, 0, m_color, tx1, ty0);
+ m_vertices[3] = video::S3DVertex(-m_size / 2, m_size / 2,
+ 0, 0, 0, 0, m_color, tx0, ty0);
v3s16 camera_offset = m_env->getCameraOffset();
for (video::S3DVertex &vertex : m_vertices) {
if (m_vertical) {
- v3f ppos = m_player->getPosition() / BS;
- vertex.Pos.rotateXZBy(
- std::atan2(ppos.Z - m_pos.Z, ppos.X - m_pos.X) /
- core::DEGTORAD +
- 90);
+ v3f ppos = m_player->getPosition()/BS;
+ vertex.Pos.rotateXZBy(std::atan2(ppos.Z - m_pos.Z, ppos.X - m_pos.X) /
+ core::DEGTORAD + 90);
} else {
vertex.Pos.rotateYZBy(m_player->getPitch());
vertex.Pos.rotateXZBy(m_player->getYaw());
}
m_box.addInternalPoint(vertex.Pos);
- vertex.Pos += m_pos * BS - intToFloat(camera_offset, BS);
+ vertex.Pos += m_pos*BS - intToFloat(camera_offset, BS);
}
}
@@ -235,11 +246,15 @@ void Particle::updateVertices()
ParticleSpawner
*/
-ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player,
- const ParticleSpawnerParameters &p, u16 attached_id,
- video::ITexture *texture, ParticleManager *p_manager) :
- m_particlemanager(p_manager),
- p(p)
+ParticleSpawner::ParticleSpawner(
+ IGameDef *gamedef,
+ LocalPlayer *player,
+ const ParticleSpawnerParameters &p,
+ u16 attached_id,
+ video::ITexture *texture,
+ ParticleManager *p_manager
+):
+ m_particlemanager(p_manager), p(p)
{
m_gamedef = gamedef;
m_player = player;
@@ -255,7 +270,7 @@ ParticleSpawner::ParticleSpawner(IGameDef *gamedef, LocalPlayer *player,
}
void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius,
- const core::matrix4 *attached_absolute_pos_rot_matrix)
+ const core::matrix4 *attached_absolute_pos_rot_matrix)
{
v3f ppos = m_player->getPosition() / BS;
v3f pos = random_v3f(p.minpos, p.maxpos);
@@ -297,10 +312,9 @@ void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius,
if (p.node.getContent() != CONTENT_IGNORE) {
const ContentFeatures &f =
- m_particlemanager->m_env->getGameDef()->ndef()->get(
- p.node);
+ m_particlemanager->m_env->getGameDef()->ndef()->get(p.node);
if (!ParticleManager::getNodeParticleParams(p.node, f, pp, &texture,
- texpos, texsize, &color, p.node_tile))
+ texpos, texsize, &color, p.node_tile))
return;
} else {
texture = m_texture;
@@ -313,7 +327,15 @@ void ParticleSpawner::spawnParticle(ClientEnvironment *env, float radius,
pp.size = random_f32(p.minsize, p.maxsize);
m_particlemanager->addParticle(new Particle(
- m_gamedef, m_player, env, pp, texture, texpos, texsize, color));
+ m_gamedef,
+ m_player,
+ env,
+ pp,
+ texture,
+ texpos,
+ texsize,
+ color
+ ));
}
void ParticleSpawner::step(float dtime, ClientEnvironment *env)
@@ -326,10 +348,8 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env)
bool unloaded = false;
const core::matrix4 *attached_absolute_pos_rot_matrix = nullptr;
if (m_attached_id) {
- if (GenericCAO *attached = dynamic_cast<GenericCAO *>(
- env->getActiveObject(m_attached_id))) {
- attached_absolute_pos_rot_matrix =
- attached->getAbsolutePosRotMatrix();
+ if (GenericCAO *attached = dynamic_cast<GenericCAO *>(env->getActiveObject(m_attached_id))) {
+ attached_absolute_pos_rot_matrix = attached->getAbsolutePosRotMatrix();
} else {
unloaded = true;
}
@@ -337,16 +357,14 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env)
if (p.time != 0) {
// Spawner exists for a predefined timespan
- for (auto i = m_spawntimes.begin(); i != m_spawntimes.end();) {
+ for (auto i = m_spawntimes.begin(); i != m_spawntimes.end(); ) {
if ((*i) <= m_time && p.amount > 0) {
--p.amount;
- // Pretend to, but don't actually spawn a particle if it
- // is attached to an unloaded object or distant from
- // player.
+ // Pretend to, but don't actually spawn a particle if it is
+ // attached to an unloaded object or distant from player.
if (!unloaded)
- spawnParticle(env, radius,
- attached_absolute_pos_rot_matrix);
+ spawnParticle(env, radius, attached_absolute_pos_rot_matrix);
i = m_spawntimes.erase(i);
} else {
@@ -362,8 +380,7 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env)
for (int i = 0; i <= p.amount; i++) {
if (rand() / (float)RAND_MAX < dtime)
- spawnParticle(env, radius,
- attached_absolute_pos_rot_matrix);
+ spawnParticle(env, radius, attached_absolute_pos_rot_matrix);
}
}
}
@@ -372,9 +389,9 @@ void ParticleSpawner::step(float dtime, ClientEnvironment *env)
ParticleManager
*/
-ParticleManager::ParticleManager(ClientEnvironment *env) : m_env(env)
-{
-}
+ParticleManager::ParticleManager(ClientEnvironment *env) :
+ m_env(env)
+{}
ParticleManager::~ParticleManager()
{
@@ -383,8 +400,8 @@ ParticleManager::~ParticleManager()
void ParticleManager::step(float dtime)
{
- stepParticles(dtime);
- stepSpawners(dtime);
+ stepParticles (dtime);
+ stepSpawners (dtime);
}
void ParticleManager::stepSpawners(float dtime)
@@ -425,80 +442,83 @@ void ParticleManager::clearAll()
m_particle_spawners.erase(i++);
}
- for (auto i = m_particles.begin(); i != m_particles.end();) {
+ for(auto i = m_particles.begin(); i != m_particles.end();)
+ {
(*i)->remove();
delete *i;
i = m_particles.erase(i);
}
}
-void ParticleManager::handleParticleEvent(
- ClientEvent *event, Client *client, LocalPlayer *player)
+void ParticleManager::handleParticleEvent(ClientEvent *event, Client *client,
+ LocalPlayer *player)
{
switch (event->type) {
- case CE_DELETE_PARTICLESPAWNER: {
- deleteParticleSpawner(event->delete_particlespawner.id);
- // no allocated memory in delete event
- break;
- }
- case CE_ADD_PARTICLESPAWNER: {
- deleteParticleSpawner(event->add_particlespawner.id);
+ case CE_DELETE_PARTICLESPAWNER: {
+ deleteParticleSpawner(event->delete_particlespawner.id);
+ // no allocated memory in delete event
+ break;
+ }
+ case CE_ADD_PARTICLESPAWNER: {
+ deleteParticleSpawner(event->add_particlespawner.id);
- const ParticleSpawnerParameters &p = *event->add_particlespawner.p;
+ const ParticleSpawnerParameters &p = *event->add_particlespawner.p;
- video::ITexture *texture = client->tsrc()->getTextureForMesh(p.texture);
+ video::ITexture *texture =
+ client->tsrc()->getTextureForMesh(p.texture);
- auto toadd = new ParticleSpawner(client, player, p,
- event->add_particlespawner.attached_id, texture, this);
+ auto toadd = new ParticleSpawner(client, player,
+ p,
+ event->add_particlespawner.attached_id,
+ texture,
+ this);
- addParticleSpawner(event->add_particlespawner.id, toadd);
+ addParticleSpawner(event->add_particlespawner.id, toadd);
- delete event->add_particlespawner.p;
- break;
- }
- case CE_SPAWN_PARTICLE: {
- ParticleParameters &p = *event->spawn_particle;
+ delete event->add_particlespawner.p;
+ break;
+ }
+ case CE_SPAWN_PARTICLE: {
+ ParticleParameters &p = *event->spawn_particle;
- video::ITexture *texture;
- v2f texpos, texsize;
- video::SColor color(0xFFFFFFFF);
+ video::ITexture *texture;
+ v2f texpos, texsize;
+ video::SColor color(0xFFFFFFFF);
- f32 oldsize = p.size;
+ f32 oldsize = p.size;
- if (p.node.getContent() != CONTENT_IGNORE) {
- const ContentFeatures &f =
- m_env->getGameDef()->ndef()->get(p.node);
- if (!getNodeParticleParams(p.node, f, p, &texture, texpos,
- texsize, &color, p.node_tile))
- texture = nullptr;
- } else {
- texture = client->tsrc()->getTextureForMesh(p.texture);
- texpos = v2f(0.0f, 0.0f);
- texsize = v2f(1.0f, 1.0f);
- }
+ if (p.node.getContent() != CONTENT_IGNORE) {
+ const ContentFeatures &f = m_env->getGameDef()->ndef()->get(p.node);
+ if (!getNodeParticleParams(p.node, f, p, &texture, texpos,
+ texsize, &color, p.node_tile))
+ texture = nullptr;
+ } else {
+ texture = client->tsrc()->getTextureForMesh(p.texture);
+ texpos = v2f(0.0f, 0.0f);
+ texsize = v2f(1.0f, 1.0f);
+ }
- // Allow keeping default random size
- if (oldsize > 0.0f)
- p.size = oldsize;
+ // Allow keeping default random size
+ if (oldsize > 0.0f)
+ p.size = oldsize;
- if (texture) {
- Particle *toadd = new Particle(client, player, m_env, p, texture,
- texpos, texsize, color);
+ if (texture) {
+ Particle *toadd = new Particle(client, player, m_env,
+ p, texture, texpos, texsize, color);
- addParticle(toadd);
- }
+ addParticle(toadd);
+ }
- delete event->spawn_particle;
- break;
- }
- default:
- break;
+ delete event->spawn_particle;
+ break;
+ }
+ default: break;
}
}
-bool ParticleManager::getNodeParticleParams(const MapNode &n, const ContentFeatures &f,
- ParticleParameters &p, video::ITexture **texture, v2f &texpos,
- v2f &texsize, video::SColor *color, u8 tilenum)
+bool ParticleManager::getNodeParticleParams(const MapNode &n,
+ const ContentFeatures &f, ParticleParameters &p, video::ITexture **texture,
+ v2f &texpos, v2f &texsize, video::SColor *color, u8 tilenum)
{
// No particles for "airlike" nodes
if (f.drawtype == NDT_AIRLIKE)
@@ -538,8 +558,8 @@ bool ParticleManager::getNodeParticleParams(const MapNode &n, const ContentFeatu
// The final burst of particles when a node is finally dug, *not* particles
// spawned during the digging of a node.
-void ParticleManager::addDiggingParticles(IGameDef *gamedef, LocalPlayer *player,
- v3s16 pos, const MapNode &n, const ContentFeatures &f)
+void ParticleManager::addDiggingParticles(IGameDef *gamedef,
+ LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f)
{
// No particles for "airlike" nodes
if (f.drawtype == NDT_AIRLIKE)
@@ -553,8 +573,8 @@ void ParticleManager::addDiggingParticles(IGameDef *gamedef, LocalPlayer *player
// During the digging of a node particles are spawned individually by this
// function, called from Game::handleDigging() in game.cpp.
-void ParticleManager::addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3s16 pos,
- const MapNode &n, const ContentFeatures &f)
+void ParticleManager::addNodeParticle(IGameDef *gamedef,
+ LocalPlayer *player, v3s16 pos, const MapNode &n, const ContentFeatures &f)
{
ParticleParameters p;
video::ITexture *texture;
@@ -567,17 +587,31 @@ void ParticleManager::addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3
p.expirationtime = (rand() % 100) / 100.0f;
// Physics
- p.vel = v3f((rand() % 150) / 50.0f - 1.5f, (rand() % 150) / 50.0f,
- (rand() % 150) / 50.0f - 1.5f);
- p.acc = v3f(0.0f,
- -player->movement_gravity * player->physics_override_gravity / BS,
- 0.0f);
- p.pos = v3f((f32)pos.X + (rand() % 100) / 200.0f - 0.25f,
- (f32)pos.Y + (rand() % 100) / 200.0f - 0.25f,
- (f32)pos.Z + (rand() % 100) / 200.0f - 0.25f);
+ p.vel = v3f(
+ (rand() % 150) / 50.0f - 1.5f,
+ (rand() % 150) / 50.0f,
+ (rand() % 150) / 50.0f - 1.5f
+ );
+ p.acc = v3f(
+ 0.0f,
+ -player->movement_gravity * player->physics_override_gravity / BS,
+ 0.0f
+ );
+ p.pos = v3f(
+ (f32)pos.X + (rand() % 100) / 200.0f - 0.25f,
+ (f32)pos.Y + (rand() % 100) / 200.0f - 0.25f,
+ (f32)pos.Z + (rand() % 100) / 200.0f - 0.25f
+ );
Particle *toadd = new Particle(
- gamedef, player, m_env, p, texture, texpos, texsize, color);
+ gamedef,
+ player,
+ m_env,
+ p,
+ texture,
+ texpos,
+ texsize,
+ color);
addParticle(toadd);
}
@@ -588,6 +622,7 @@ void ParticleManager::addParticle(Particle *toadd)
m_particles.push_back(toadd);
}
+
void ParticleManager::addParticleSpawner(u64 id, ParticleSpawner *toadd)
{
MutexAutoLock lock(m_spawner_list_lock);
diff --git a/src/client/particles.h b/src/client/particles.h
index b3a1f1156..2011f0262 100644
--- a/src/client/particles.h
+++ b/src/client/particles.h
@@ -33,24 +33,41 @@ struct ContentFeatures;
class Particle : public scene::ISceneNode
{
-public:
- Particle(IGameDef *gamedef, LocalPlayer *player, ClientEnvironment *env,
- const ParticleParameters &p, video::ITexture *texture, v2f texpos,
- v2f texsize, video::SColor color);
+ public:
+ Particle(
+ IGameDef* gamedef,
+ LocalPlayer *player,
+ ClientEnvironment *env,
+ const ParticleParameters &p,
+ video::ITexture *texture,
+ v2f texpos,
+ v2f texsize,
+ video::SColor color
+ );
~Particle() = default;
- virtual const aabb3f &getBoundingBox() const { return m_box; }
+ virtual const aabb3f &getBoundingBox() const
+ {
+ return m_box;
+ }
- virtual u32 getMaterialCount() const { return 1; }
+ virtual u32 getMaterialCount() const
+ {
+ return 1;
+ }
- virtual video::SMaterial &getMaterial(u32 i) { return m_material; }
+ virtual video::SMaterial& getMaterial(u32 i)
+ {
+ return m_material;
+ }
virtual void OnRegisterSceneNode();
virtual void render();
void step(float dtime);
- bool get_expired() { return m_expiration < m_time; }
+ bool get_expired ()
+ { return m_expiration < m_time; }
private:
void updateLight();
@@ -90,19 +107,23 @@ private:
class ParticleSpawner
{
public:
- ParticleSpawner(IGameDef *gamedef, LocalPlayer *player,
- const ParticleSpawnerParameters &p, u16 attached_id,
- video::ITexture *texture, ParticleManager *p_manager);
+ ParticleSpawner(IGameDef* gamedef,
+ LocalPlayer *player,
+ const ParticleSpawnerParameters &p,
+ u16 attached_id,
+ video::ITexture *texture,
+ ParticleManager* p_manager);
~ParticleSpawner() = default;
void step(float dtime, ClientEnvironment *env);
- bool get_expired() { return p.amount <= 0 && p.time != 0; }
+ bool get_expired ()
+ { return p.amount <= 0 && p.time != 0; }
private:
void spawnParticle(ClientEnvironment *env, float radius,
- const core::matrix4 *attached_absolute_pos_rot_matrix);
+ const core::matrix4 *attached_absolute_pos_rot_matrix);
ParticleManager *m_particlemanager;
float m_time;
@@ -119,21 +140,21 @@ private:
*/
class ParticleManager
{
- friend class ParticleSpawner;
-
+friend class ParticleSpawner;
public:
- ParticleManager(ClientEnvironment *env);
+ ParticleManager(ClientEnvironment* env);
~ParticleManager();
- void step(float dtime);
+ void step (float dtime);
- void handleParticleEvent(ClientEvent *event, Client *client, LocalPlayer *player);
+ void handleParticleEvent(ClientEvent *event, Client *client,
+ LocalPlayer *player);
void addDiggingParticles(IGameDef *gamedef, LocalPlayer *player, v3s16 pos,
- const MapNode &n, const ContentFeatures &f);
+ const MapNode &n, const ContentFeatures &f);
void addNodeParticle(IGameDef *gamedef, LocalPlayer *player, v3s16 pos,
- const MapNode &n, const ContentFeatures &f);
+ const MapNode &n, const ContentFeatures &f);
/**
* This function is only used by client particle spawners
@@ -142,14 +163,17 @@ public:
* never overlap (u64)
* @return new id
*/
- u64 generateSpawnerId() { return m_next_particle_spawner_id++; }
+ u64 generateSpawnerId()
+ {
+ return m_next_particle_spawner_id++;
+ }
protected:
static bool getNodeParticleParams(const MapNode &n, const ContentFeatures &f,
- ParticleParameters &p, video::ITexture **texture, v2f &texpos,
- v2f &texsize, video::SColor *color, u8 tilenum = 0);
+ ParticleParameters &p, video::ITexture **texture, v2f &texpos,
+ v2f &texsize, video::SColor *color, u8 tilenum = 0);
- void addParticle(Particle *toadd);
+ void addParticle(Particle* toadd);
private:
void addParticleSpawner(u64 id, ParticleSpawner *toadd);
@@ -160,13 +184,13 @@ private:
void clearAll();
- std::vector<Particle *> m_particles;
- std::unordered_map<u64, ParticleSpawner *> m_particle_spawners;
- // Start the particle spawner ids generated from here after u32_max. lower values
- // are for server sent spawners.
+ std::vector<Particle*> m_particles;
+ std::unordered_map<u64, ParticleSpawner*> m_particle_spawners;
+ // Start the particle spawner ids generated from here after u32_max. lower values are
+ // for server sent spawners.
u64 m_next_particle_spawner_id = U32_MAX + 1;
- ClientEnvironment *m_env;
+ ClientEnvironment* m_env;
std::mutex m_particle_list_lock;
std::mutex m_spawner_list_lock;
};
diff --git a/src/client/render/core.cpp b/src/client/render/core.cpp
index a7644681e..223af5142 100644
--- a/src/client/render/core.cpp
+++ b/src/client/render/core.cpp
@@ -27,11 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client/minimap.h"
#include "client/content_cao.h"
-RenderingCore::RenderingCore(IrrlichtDevice *_device, Client *_client, Hud *_hud) :
- device(_device), driver(device->getVideoDriver()),
- smgr(device->getSceneManager()), guienv(device->getGUIEnvironment()),
- client(_client), camera(client->getCamera()),
- mapper(client->getMinimap()), hud(_hud)
+RenderingCore::RenderingCore(IrrlichtDevice *_device, Client *_client, Hud *_hud)
+ : device(_device), driver(device->getVideoDriver()), smgr(device->getSceneManager()),
+ guienv(device->getGUIEnvironment()), client(_client), camera(client->getCamera()),
+ mapper(client->getMinimap()), hud(_hud)
{
screensize = driver->getScreenSize();
virtual_size = screensize;
@@ -56,8 +55,7 @@ void RenderingCore::updateScreenSize()
}
void RenderingCore::draw(video::SColor _skycolor, bool _show_hud, bool _show_minimap,
- bool _draw_wield_tool, bool _draw_crosshair, bool _draw_tracers,
- bool _draw_esp)
+ bool _draw_wield_tool, bool _draw_crosshair, bool _draw_tracers, bool _draw_esp)
{
v2u32 ss = driver->getScreenSize();
if (screensize != ss) {
@@ -71,7 +69,7 @@ void RenderingCore::draw(video::SColor _skycolor, bool _show_hud, bool _show_min
draw_crosshair = _draw_crosshair;
draw_tracers = _draw_tracers;
draw_esp = _draw_esp;
-
+
beforeDraw();
drawAll();
}
@@ -80,29 +78,29 @@ void RenderingCore::drawTracersAndESP()
{
ClientEnvironment &env = client->getEnv();
Camera *camera = client->getCamera();
-
+
v3f camera_offset = intToFloat(camera->getOffset(), BS);
-
+
v3f eye_pos = (camera->getPosition() + camera->getDirection() - camera_offset);
-
- video::SMaterial material, oldmaterial;
- oldmaterial = driver->getMaterial2D();
+
+ video::SMaterial material, oldmaterial;
+ oldmaterial = driver->getMaterial2D();
material.setFlag(video::EMF_LIGHTING, false);
material.setFlag(video::EMF_BILINEAR_FILTER, false);
material.setFlag(video::EMF_ZBUFFER, false);
material.setFlag(video::EMF_ZWRITE_ENABLE, false);
driver->setMaterial(material);
-
+
auto allObjects = env.getAllActiveObjects();
for (auto &it : allObjects) {
ClientActiveObject *cao = it.second;
if (cao->isLocalPlayer() || cao->getParent())
continue;
GenericCAO *obj = dynamic_cast<GenericCAO *>(cao);
- if (!obj)
+ if (! obj)
continue;
aabb3f box;
- if (!obj->getSelectionBox(&box))
+ if (! obj->getSelectionBox(&box))
continue;
v3f pos = obj->getPosition();
pos -= camera_offset;
@@ -112,10 +110,9 @@ void RenderingCore::drawTracersAndESP()
if (draw_esp)
driver->draw3DBox(box, video::SColor(255, 255, 255, 255));
if (draw_tracers)
- driver->draw3DLine(
- eye_pos, pos, video::SColor(255, 255, 255, 255));
+ driver->draw3DLine(eye_pos, pos, video::SColor(255, 255, 255, 255));
}
-
+
driver->setMaterial(oldmaterial);
}
@@ -137,7 +134,7 @@ void RenderingCore::drawHUD()
if (show_hud) {
if (draw_crosshair)
hud->drawCrosshair();
-
+
hud->drawHotbar(client->getEnv().getLocalPlayer()->getWieldIndex());
hud->drawLuaElements(camera->getOffset());
camera->drawNametags();
diff --git a/src/client/render/interlaced.cpp b/src/client/render/interlaced.cpp
index c5d9c9c24..2aadadc17 100644
--- a/src/client/render/interlaced.cpp
+++ b/src/client/render/interlaced.cpp
@@ -24,8 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "client/tile.h"
RenderingCoreInterlaced::RenderingCoreInterlaced(
- IrrlichtDevice *_device, Client *_client, Hud *_hud) :
- RenderingCoreStereo(_device, _client, _hud)
+ IrrlichtDevice *_device, Client *_client, Hud *_hud)
+ : RenderingCoreStereo(_device, _client, _hud)
{
initMaterial();
}
diff --git a/src/client/render/plain.cpp b/src/client/render/plain.cpp
index 8ac5e106b..a130a14eb 100644
--- a/src/client/render/plain.cpp
+++ b/src/client/render/plain.cpp
@@ -27,8 +27,8 @@ inline u32 scaledown(u32 coef, u32 size)
}
RenderingCorePlain::RenderingCorePlain(
- IrrlichtDevice *_device, Client *_client, Hud *_hud) :
- RenderingCore(_device, _client, _hud)
+ IrrlichtDevice *_device, Client *_client, Hud *_hud)
+ : RenderingCore(_device, _client, _hud)
{
scale = g_settings->getU16("undersampling");
}
diff --git a/src/client/render/sidebyside.cpp b/src/client/render/sidebyside.cpp
index 89e4b5e80..ed08810db 100644
--- a/src/client/render/sidebyside.cpp
+++ b/src/client/render/sidebyside.cpp
@@ -22,10 +22,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <ICameraSceneNode.h>
#include "client/hud.h"
-RenderingCoreSideBySide::RenderingCoreSideBySide(IrrlichtDevice *_device, Client *_client,
- Hud *_hud, bool _horizontal, bool _flipped) :
- RenderingCoreStereo(_device, _client, _hud),
- horizontal(_horizontal), flipped(_flipped)
+RenderingCoreSideBySide::RenderingCoreSideBySide(
+ IrrlichtDevice *_device, Client *_client, Hud *_hud, bool _horizontal, bool _flipped)
+ : RenderingCoreStereo(_device, _client, _hud), horizontal(_horizontal), flipped(_flipped)
{
}
diff --git a/src/client/render/stereo.cpp b/src/client/render/stereo.cpp
index 99997c967..967b5a78f 100644
--- a/src/client/render/stereo.cpp
+++ b/src/client/render/stereo.cpp
@@ -24,8 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "settings.h"
RenderingCoreStereo::RenderingCoreStereo(
- IrrlichtDevice *_device, Client *_client, Hud *_hud) :
- RenderingCore(_device, _client, _hud)
+ IrrlichtDevice *_device, Client *_client, Hud *_hud)
+ : RenderingCore(_device, _client, _hud)
{
eye_offset = BS * g_settings->getFloat("3d_paralax_strength");
}
diff --git a/src/client/renderingengine.cpp b/src/client/renderingengine.cpp
index 0b7a242fa..1534289d4 100644
--- a/src/client/renderingengine.cpp
+++ b/src/client/renderingengine.cpp
@@ -37,7 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "gettext.h"
#include "../gui/guiSkin.h"
-#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
+#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
!defined(SERVER) && !defined(__HAIKU__)
#define XORG_USED
#endif
@@ -58,6 +58,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
RenderingEngine *RenderingEngine::s_singleton = nullptr;
+
static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
{
@@ -66,7 +67,7 @@ static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
gui::IGUIFont *builtinfont = environment->getBuiltInFont();
gui::IGUIFontBitmap *bitfont = nullptr;
if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
- bitfont = (gui::IGUIFontBitmap *)builtinfont;
+ bitfont = (gui::IGUIFontBitmap*)builtinfont;
gui::IGUISpriteBank *bank = 0;
skin->setFont(builtinfont);
@@ -79,6 +80,7 @@ static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
return skin;
}
+
RenderingEngine::RenderingEngine(IEventReceiver *receiver)
{
sanity_check(!s_singleton);
@@ -104,7 +106,7 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver)
u32 i;
for (i = 0; i != drivers.size(); i++) {
if (!strcasecmp(driverstring.c_str(),
- RenderingEngine::getVideoDriverName(drivers[i]))) {
+ RenderingEngine::getVideoDriverName(drivers[i]))) {
driverType = drivers[i];
break;
}
@@ -132,10 +134,9 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver)
#endif
#if ENABLE_GLES
// there is no standardized path for these on desktop
- std::string rel_path = std::string("client") + DIR_DELIM + "shaders" + DIR_DELIM +
- "Irrlicht";
- params.OGLES2ShaderPath =
- (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
+ std::string rel_path = std::string("client") + DIR_DELIM
+ + "shaders" + DIR_DELIM + "Irrlicht";
+ params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
#endif
m_device = createDeviceEx(params);
@@ -143,8 +144,8 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver)
s_singleton = this;
- auto skin = createSkin(m_device->getGUIEnvironment(), gui::EGST_WINDOWS_METALLIC,
- driver);
+ auto skin = createSkin(m_device->getGUIEnvironment(),
+ gui::EGST_WINDOWS_METALLIC, driver);
m_device->getGUIEnvironment()->setSkin(skin);
skin->drop();
}
@@ -233,7 +234,8 @@ bool RenderingEngine::setupTopLevelWindow(const std::string &name)
/* Setting general properties for the top level window */
verbosestream << "Client: Configuring general top level"
- << " window properties" << std::endl;
+ << " window properties"
+ << std::endl;
bool result = setWindowIcon();
return result;
@@ -244,16 +246,17 @@ void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
#ifdef XORG_USED
const video::SExposedVideoData exposedData = driver->getExposedVideoData();
- Display *x11_dpl =
- reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
+ Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
if (x11_dpl == NULL) {
warningstream << "Client: Could not find X11 Display in ExposedVideoData"
- << std::endl;
+ << std::endl;
return;
}
verbosestream << "Client: Configuring X11-specific top level"
- << " window properties" << std::endl;
+ << " window properties"
+ << std::endl;
+
Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
@@ -281,35 +284,38 @@ void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
// more, using gtk/gdk as the model it would seem that not using a FQDN is
// not an issue for modern Xorg window managers.
- verbosestream << "Client: Setting Xorg window manager Properties" << std::endl;
+ verbosestream << "Client: Setting Xorg window manager Properties"
+ << std::endl;
- XSetWMProperties(x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
+ XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
// Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
// (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
// force a shutdown of an application if it doesn't respond to the destroy
// window message.
- verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager "
- "property"
- << std::endl;
+ verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property"
+ << std::endl;
Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
pid_t pid = getpid();
- XChangeProperty(x11_dpl, x11_win, NET_WM_PID, XA_CARDINAL, 32, PropModeReplace,
- reinterpret_cast<unsigned char *>(&pid), 1);
+ XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
+ XA_CARDINAL, 32, PropModeReplace,
+ reinterpret_cast<unsigned char *>(&pid),1);
// Set the WM_CLIENT_LEADER window property here. Minetest has only one
// window and that window will always be the leader.
- verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property" << std::endl;
+ verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
+ << std::endl;
Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
- XChangeProperty(x11_dpl, x11_win, WM_CLIENT_LEADER, XA_WINDOW, 32,
- PropModeReplace, reinterpret_cast<unsigned char *>(&x11_win), 1);
+ XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
+ XA_WINDOW, 32, PropModeReplace,
+ reinterpret_cast<unsigned char *>(&x11_win), 1);
#endif
}
@@ -537,8 +543,8 @@ void RenderingEngine::_draw_load_screen(const std::wstring &text,
/*
Draws the menu scene including (optional) cloud background.
*/
-void RenderingEngine::_draw_menu_scene(
- gui::IGUIEnvironment *guienv, float dtime, bool clouds)
+void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
+ float dtime, bool clouds)
{
bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
if (cloud_menu_background) {
@@ -598,11 +604,9 @@ void RenderingEngine::_finalize()
}
void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
- bool show_minimap, bool draw_wield_tool, bool draw_crosshair,
- bool draw_tracers, bool draw_esp)
+ bool show_minimap, bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp)
{
- core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair,
- draw_tracers, draw_esp);
+ core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair, draw_tracers, draw_esp);
}
const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
@@ -675,6 +679,7 @@ float RenderingEngine::getDisplayDensity()
#elif defined(_WIN32)
+
static float calcDisplayDensity(irr::video::IVideoDriver *driver)
{
HWND hWnd;
@@ -720,7 +725,7 @@ v2u32 RenderingEngine::getDisplaySize()
return deskres;
}
-#else // __ANDROID__
+#else // __ANDROID__
float RenderingEngine::getDisplayDensity()
{
return porting::getDisplayDensity();
diff --git a/src/client/renderingengine.h b/src/client/renderingengine.h
index c9f7d9223..c5fa8918b 100644
--- a/src/client/renderingengine.h
+++ b/src/client/renderingengine.h
@@ -118,8 +118,7 @@ public:
}
inline static void draw_scene(video::SColor skycolor, bool show_hud,
- bool show_minimap, bool draw_wield_tool, bool draw_crosshair,
- bool draw_tracers, bool draw_esp)
+ bool show_minimap, bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp)
{
s_singleton->_draw_scene(skycolor, show_hud, show_minimap,
draw_wield_tool, draw_crosshair, draw_tracers, draw_esp);
@@ -150,8 +149,7 @@ private:
bool clouds = true);
void _draw_scene(video::SColor skycolor, bool show_hud, bool show_minimap,
- bool draw_wield_tool, bool draw_crosshair, bool draw_tracers,
- bool draw_esp);
+ bool draw_wield_tool, bool draw_crosshair, bool draw_tracers, bool draw_esp);
void _initialize(Client *client, Hud *hud);
diff --git a/src/client/shader.cpp b/src/client/shader.cpp
index 9e0b73696..ee6079f7a 100644
--- a/src/client/shader.cpp
+++ b/src/client/shader.cpp
@@ -52,7 +52,8 @@ MutexedMap<std::string, std::string> g_shadername_to_path_cache;
Utilizes a thread-safe cache.
*/
-std::string getShaderPath(const std::string &name_of_shader, const std::string &filename)
+std::string getShaderPath(const std::string &name_of_shader,
+ const std::string &filename)
{
std::string combined = name_of_shader + DIR_DELIM + filename;
std::string fullpath;
@@ -60,7 +61,7 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string &
Check from cache
*/
bool incache = g_shadername_to_path_cache.get(combined, &fullpath);
- if (incache)
+ if(incache)
return fullpath;
/*
@@ -69,7 +70,7 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string &
std::string shader_path = g_settings->get("shader_path");
if (!shader_path.empty()) {
std::string testpath = shader_path + DIR_DELIM + combined;
- if (fs::PathExists(testpath))
+ if(fs::PathExists(testpath))
fullpath = testpath;
}
@@ -77,10 +78,12 @@ std::string getShaderPath(const std::string &name_of_shader, const std::string &
Check from default data directory
*/
if (fullpath.empty()) {
- std::string rel_path = std::string("client") + DIR_DELIM + "shaders" +
- DIR_DELIM + name_of_shader + DIR_DELIM + filename;
+ std::string rel_path = std::string("client") + DIR_DELIM
+ + "shaders" + DIR_DELIM
+ + name_of_shader + DIR_DELIM
+ + filename;
std::string testpath = porting::path_share + DIR_DELIM + rel_path;
- if (fs::PathExists(testpath))
+ if(fs::PathExists(testpath))
fullpath = testpath;
}
@@ -99,13 +102,13 @@ class SourceShaderCache
{
public:
void insert(const std::string &name_of_shader, const std::string &filename,
- const std::string &program, bool prefer_local)
+ const std::string &program, bool prefer_local)
{
std::string combined = name_of_shader + DIR_DELIM + filename;
// Try to use local shader instead if asked to
- if (prefer_local) {
+ if(prefer_local){
std::string path = getShaderPath(name_of_shader, filename);
- if (!path.empty()) {
+ if(!path.empty()){
std::string p = readFile(path);
if (!p.empty()) {
m_programs[combined] = p;
@@ -116,7 +119,8 @@ public:
m_programs[combined] = program;
}
- std::string get(const std::string &name_of_shader, const std::string &filename)
+ std::string get(const std::string &name_of_shader,
+ const std::string &filename)
{
std::string combined = name_of_shader + DIR_DELIM + filename;
StringMap::iterator n = m_programs.find(combined);
@@ -126,8 +130,8 @@ public:
}
// Primarily fetches from cache, secondarily tries to read from filesystem
- std::string getOrLoad(
- const std::string &name_of_shader, const std::string &filename)
+ std::string getOrLoad(const std::string &name_of_shader,
+ const std::string &filename)
{
std::string combined = name_of_shader + DIR_DELIM + filename;
StringMap::iterator n = m_programs.find(combined);
@@ -135,13 +139,12 @@ public:
return n->second;
std::string path = getShaderPath(name_of_shader, filename);
if (path.empty()) {
- infostream << "SourceShaderCache::getOrLoad(): No path found for "
- "\""
- << combined << "\"" << std::endl;
+ infostream << "SourceShaderCache::getOrLoad(): No path found for \""
+ << combined << "\"" << std::endl;
return "";
}
- infostream << "SourceShaderCache::getOrLoad(): Loading path \"" << path
- << "\"" << std::endl;
+ infostream << "SourceShaderCache::getOrLoad(): Loading path \""
+ << path << "\"" << std::endl;
std::string p = readFile(path);
if (!p.empty()) {
m_programs[combined] = p;
@@ -149,14 +152,13 @@ public:
}
return "";
}
-
private:
StringMap m_programs;
std::string readFile(const std::string &path)
{
std::ifstream is(path.c_str(), std::ios::binary);
- if (!is.is_open())
+ if(!is.is_open())
return "";
std::ostringstream tmp_os;
tmp_os << is.rdbuf();
@@ -164,13 +166,14 @@ private:
}
};
+
/*
ShaderCallback: Sets constants that can be used in shaders
*/
class ShaderCallback : public video::IShaderConstantSetCallBack
{
- std::vector<IShaderConstantSetter *> m_setters;
+ std::vector<IShaderConstantSetter*> m_setters;
public:
ShaderCallback(const std::vector<IShaderConstantSetterFactory *> &factories)
@@ -185,8 +188,7 @@ public:
delete setter;
}
- virtual void OnSetConstants(
- video::IMaterialRendererServices *services, s32 userData) override
+ virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override
{
video::IVideoDriver *driver = services->getVideoDriver();
sanity_check(driver != NULL);
@@ -197,13 +199,14 @@ public:
setter->onSetConstants(services, is_highlevel);
}
- virtual void OnSetMaterial(const video::SMaterial &material) override
+ virtual void OnSetMaterial(const video::SMaterial& material) override
{
for (IShaderConstantSetter *setter : m_setters)
setter->onSetMaterial(material);
}
};
+
/*
MainShaderConstantSetter: Set basic constants required for almost everything
*/
@@ -215,13 +218,13 @@ class MainShaderConstantSetter : public IShaderConstantSetter
public:
MainShaderConstantSetter() :
- m_world_view_proj("mWorldViewProj"), m_world("mWorld")
- {
- }
+ m_world_view_proj("mWorldViewProj"),
+ m_world("mWorld")
+ {}
~MainShaderConstantSetter() = default;
- virtual void onSetConstants(
- video::IMaterialRendererServices *services, bool is_highlevel)
+ virtual void onSetConstants(video::IMaterialRendererServices *services,
+ bool is_highlevel)
{
video::IVideoDriver *driver = services->getVideoDriver();
sanity_check(driver);
@@ -232,28 +235,29 @@ public:
worldViewProj *= driver->getTransform(video::ETS_VIEW);
worldViewProj *= driver->getTransform(video::ETS_WORLD);
if (is_highlevel)
- m_world_view_proj.set(*reinterpret_cast<float(*)[16]>(
- worldViewProj.pointer()),
- services);
+ m_world_view_proj.set(*reinterpret_cast<float(*)[16]>(worldViewProj.pointer()), services);
else
services->setVertexShaderConstant(worldViewProj.pointer(), 0, 4);
// Set world matrix
core::matrix4 world = driver->getTransform(video::ETS_WORLD);
if (is_highlevel)
- m_world.set(*reinterpret_cast<float(*)[16]>(world.pointer()),
- services);
+ m_world.set(*reinterpret_cast<float(*)[16]>(world.pointer()), services);
else
services->setVertexShaderConstant(world.pointer(), 4, 4);
+
}
};
+
class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory
{
public:
- virtual IShaderConstantSetter *create() { return new MainShaderConstantSetter(); }
+ virtual IShaderConstantSetter* create()
+ { return new MainShaderConstantSetter(); }
};
+
/*
ShaderSource
*/
@@ -271,8 +275,8 @@ public:
The id 0 points to a null shader. Its material is EMT_SOLID.
*/
- u32 getShaderIdDirect(const std::string &name, const u8 material_type,
- const u8 drawtype);
+ u32 getShaderIdDirect(const std::string &name,
+ const u8 material_type, const u8 drawtype);
/*
If shader specified by the name pointed by the id doesn't
@@ -283,7 +287,8 @@ public:
for processing.
*/
- u32 getShader(const std::string &name, const u8 material_type, const u8 drawtype);
+ u32 getShader(const std::string &name,
+ const u8 material_type, const u8 drawtype);
ShaderInfo getShaderInfo(u32 id);
@@ -294,7 +299,7 @@ public:
// Insert a shader program into the cache without touching the
// filesystem. Shall be called from the main thread.
void insertSourceShader(const std::string &name_of_shader,
- const std::string &filename, const std::string &program);
+ const std::string &filename, const std::string &program);
// Rebuild shaders from the current set of source shaders
// Shall be called from the main thread.
@@ -306,6 +311,7 @@ public:
}
private:
+
// The id of the thread that is allowed to use irrlicht directly
std::thread::id m_main_thread;
@@ -337,8 +343,8 @@ IWritableShaderSource *createShaderSource()
/*
Generate shader given the shader name.
*/
-ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype,
- std::vector<ShaderCallback *> &callbacks,
+ShaderInfo generate_shader(const std::string &name,
+ u8 material_type, u8 drawtype, std::vector<ShaderCallback *> &callbacks,
const std::vector<IShaderConstantSetterFactory *> &setter_factories,
SourceShaderCache *sourcecache);
@@ -371,8 +377,8 @@ ShaderSource::~ShaderSource()
}
}
-u32 ShaderSource::getShader(
- const std::string &name, const u8 material_type, const u8 drawtype)
+u32 ShaderSource::getShader(const std::string &name,
+ const u8 material_type, const u8 drawtype)
{
/*
Get shader
@@ -394,15 +400,15 @@ u32 ShaderSource::getShader(
/* infostream<<"Waiting for shader from main thread, name=\""
<<name<<"\""<<std::endl;*/
- while (true) {
- GetResult<std::string, u32, u8, u8> result = result_queue.pop_frontNoEx();
+ while(true) {
+ GetResult<std::string, u32, u8, u8>
+ result = result_queue.pop_frontNoEx();
if (result.key == name) {
return result.item;
}
- errorstream << "Got shader with invalid name: " << result.key
- << std::endl;
+ errorstream << "Got shader with invalid name: " << result.key << std::endl;
}
infostream << "getShader(): Failed" << std::endl;
@@ -413,22 +419,22 @@ u32 ShaderSource::getShader(
/*
This method generates all the shaders
*/
-u32 ShaderSource::getShaderIdDirect(
- const std::string &name, const u8 material_type, const u8 drawtype)
+u32 ShaderSource::getShaderIdDirect(const std::string &name,
+ const u8 material_type, const u8 drawtype)
{
- // infostream<<"getShaderIdDirect(): name=\""<<name<<"\""<<std::endl;
+ //infostream<<"getShaderIdDirect(): name=\""<<name<<"\""<<std::endl;
// Empty name means shader 0
if (name.empty()) {
- infostream << "getShaderIdDirect(): name is empty" << std::endl;
+ infostream<<"getShaderIdDirect(): name is empty"<<std::endl;
return 0;
}
// Check if already have such instance
- for (u32 i = 0; i < m_shaderinfo_cache.size(); i++) {
+ for(u32 i=0; i<m_shaderinfo_cache.size(); i++){
ShaderInfo *info = &m_shaderinfo_cache[i];
- if (info->name == name && info->material_type == material_type &&
- info->drawtype == drawtype)
+ if(info->name == name && info->material_type == material_type &&
+ info->drawtype == drawtype)
return i;
}
@@ -436,14 +442,13 @@ u32 ShaderSource::getShaderIdDirect(
Calling only allowed from main thread
*/
if (std::this_thread::get_id() != m_main_thread) {
- errorstream << "ShaderSource::getShaderIdDirect() "
- "called not from main thread"
- << std::endl;
+ errorstream<<"ShaderSource::getShaderIdDirect() "
+ "called not from main thread"<<std::endl;
return 0;
}
- ShaderInfo info = generate_shader(name, material_type, drawtype, m_callbacks,
- m_setter_factories, &m_sourcecache);
+ ShaderInfo info = generate_shader(name, material_type, drawtype,
+ m_callbacks, m_setter_factories, &m_sourcecache);
/*
Add shader to caches (add dummy shaders too)
@@ -454,18 +459,18 @@ u32 ShaderSource::getShaderIdDirect(
u32 id = m_shaderinfo_cache.size();
m_shaderinfo_cache.push_back(info);
- infostream << "getShaderIdDirect(): "
- << "Returning id=" << id << " for name \"" << name << "\""
- << std::endl;
+ infostream<<"getShaderIdDirect(): "
+ <<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl;
return id;
}
+
ShaderInfo ShaderSource::getShaderInfo(u32 id)
{
MutexAutoLock lock(m_shaderinfo_cache_mutex);
- if (id >= m_shaderinfo_cache.size())
+ if(id >= m_shaderinfo_cache.size())
return ShaderInfo();
return m_shaderinfo_cache[id];
@@ -473,6 +478,8 @@ ShaderInfo ShaderSource::getShaderInfo(u32 id)
void ShaderSource::processQueue()
{
+
+
}
void ShaderSource::insertSourceShader(const std::string &name_of_shader,
@@ -506,12 +513,13 @@ void ShaderSource::rebuildShaders()
ShaderInfo *info = &i;
if (!info->name.empty()) {
*info = generate_shader(info->name, info->material_type,
- info->drawtype, m_callbacks, m_setter_factories,
- &m_sourcecache);
+ info->drawtype, m_callbacks,
+ m_setter_factories, &m_sourcecache);
}
}
}
+
ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype,
std::vector<ShaderCallback *> &callbacks,
const std::vector<IShaderConstantSetterFactory *> &setter_factories,
@@ -550,13 +558,11 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
- if (!gpu) {
- errorstream << "generate_shader(): "
- "failed to generate \""
- << name
- << "\", "
- "GPU programming not supported."
- << std::endl;
+ if(!gpu){
+ errorstream<<"generate_shader(): "
+ "failed to generate \""<<name<<"\", "
+ "GPU programming not supported."
+ <<std::endl;
return shaderinfo;
}
@@ -566,30 +572,31 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
std::string pixel_program;
std::string geometry_program;
bool is_highlevel;
- load_shaders(name, sourcecache, driver->getDriverType(), enable_shaders,
- vertex_program, pixel_program, geometry_program, is_highlevel);
+ load_shaders(name, sourcecache, driver->getDriverType(),
+ enable_shaders, vertex_program, pixel_program,
+ geometry_program, is_highlevel);
// Check hardware/driver support
if (!vertex_program.empty() &&
!driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) &&
- !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1)) {
- infostream << "generate_shader(): vertex shaders disabled "
- "because of missing driver/hardware support."
- << std::endl;
+ !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1)){
+ infostream<<"generate_shader(): vertex shaders disabled "
+ "because of missing driver/hardware support."
+ <<std::endl;
vertex_program = "";
}
if (!pixel_program.empty() &&
!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) &&
- !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1)) {
- infostream << "generate_shader(): pixel shaders disabled "
- "because of missing driver/hardware support."
- << std::endl;
+ !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1)){
+ infostream<<"generate_shader(): pixel shaders disabled "
+ "because of missing driver/hardware support."
+ <<std::endl;
pixel_program = "";
}
if (!geometry_program.empty() &&
- !driver->queryFeature(video::EVDF_GEOMETRY_SHADER)) {
- infostream << "generate_shader(): geometry shaders disabled "
- "because of missing driver/hardware support."
- << std::endl;
+ !driver->queryFeature(video::EVDF_GEOMETRY_SHADER)){
+ infostream<<"generate_shader(): geometry shaders disabled "
+ "because of missing driver/hardware support."
+ <<std::endl;
geometry_program = "";
}
@@ -600,27 +607,27 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
// Create shaders header
std::string shaders_header = "#version 120\n";
- static const char *drawTypes[] = {
- "NDT_NORMAL",
- "NDT_AIRLIKE",
- "NDT_LIQUID",
- "NDT_FLOWINGLIQUID",
- "NDT_GLASSLIKE",
- "NDT_ALLFACES",
- "NDT_ALLFACES_OPTIONAL",
- "NDT_TORCHLIKE",
- "NDT_SIGNLIKE",
- "NDT_PLANTLIKE",
- "NDT_FENCELIKE",
- "NDT_RAILLIKE",
- "NDT_NODEBOX",
- "NDT_GLASSLIKE_FRAMED",
- "NDT_FIRELIKE",
- "NDT_GLASSLIKE_FRAMED_OPTIONAL",
- "NDT_PLANTLIKE_ROOTED",
+ static const char* drawTypes[] = {
+ "NDT_NORMAL",
+ "NDT_AIRLIKE",
+ "NDT_LIQUID",
+ "NDT_FLOWINGLIQUID",
+ "NDT_GLASSLIKE",
+ "NDT_ALLFACES",
+ "NDT_ALLFACES_OPTIONAL",
+ "NDT_TORCHLIKE",
+ "NDT_SIGNLIKE",
+ "NDT_PLANTLIKE",
+ "NDT_FENCELIKE",
+ "NDT_RAILLIKE",
+ "NDT_NODEBOX",
+ "NDT_GLASSLIKE_FRAMED",
+ "NDT_FIRELIKE",
+ "NDT_GLASSLIKE_FRAMED_OPTIONAL",
+ "NDT_PLANTLIKE_ROOTED",
};
- for (int i = 0; i < 14; i++) {
+ for (int i = 0; i < 14; i++){
shaders_header += "#define ";
shaders_header += drawTypes[i];
shaders_header += " ";
@@ -628,22 +635,22 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
shaders_header += "\n";
}
- static const char *materialTypes[] = {
- "TILE_MATERIAL_BASIC",
- "TILE_MATERIAL_ALPHA",
- "TILE_MATERIAL_LIQUID_TRANSPARENT",
- "TILE_MATERIAL_LIQUID_OPAQUE",
- "TILE_MATERIAL_WAVING_LEAVES",
- "TILE_MATERIAL_WAVING_PLANTS",
- "TILE_MATERIAL_OPAQUE",
- "TILE_MATERIAL_WAVING_LIQUID_BASIC",
- "TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT",
- "TILE_MATERIAL_WAVING_LIQUID_OPAQUE",
- "TILE_MATERIAL_PLAIN",
- "TILE_MATERIAL_PLAIN_ALPHA",
+ static const char* materialTypes[] = {
+ "TILE_MATERIAL_BASIC",
+ "TILE_MATERIAL_ALPHA",
+ "TILE_MATERIAL_LIQUID_TRANSPARENT",
+ "TILE_MATERIAL_LIQUID_OPAQUE",
+ "TILE_MATERIAL_WAVING_LEAVES",
+ "TILE_MATERIAL_WAVING_PLANTS",
+ "TILE_MATERIAL_OPAQUE",
+ "TILE_MATERIAL_WAVING_LIQUID_BASIC",
+ "TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT",
+ "TILE_MATERIAL_WAVING_LIQUID_OPAQUE",
+ "TILE_MATERIAL_PLAIN",
+ "TILE_MATERIAL_PLAIN_ALPHA",
};
- for (int i = 0; i < 12; i++) {
+ for (int i = 0; i < 12; i++){
shaders_header += "#define ";
shaders_header += materialTypes[i];
shaders_header += " ";
@@ -668,7 +675,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
shaders_header += "\n";
float sample_step;
int smooth = (int)g_settings->getFloat("normalmaps_smooth");
- switch (smooth) {
+ switch (smooth){
case 0:
sample_step = 0.0078125; // 1.0 / 128.0
break;
@@ -689,7 +696,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
if (g_settings->getBool("enable_bumpmapping"))
shaders_header += "#define ENABLE_BUMPMAPPING\n";
- if (g_settings->getBool("enable_parallax_occlusion")) {
+ if (g_settings->getBool("enable_parallax_occlusion")){
int mode = g_settings->getFloat("parallax_occlusion_mode");
float scale = g_settings->getFloat("parallax_occlusion_scale");
float bias = g_settings->getFloat("parallax_occlusion_bias");
@@ -710,13 +717,12 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
}
shaders_header += "#define USE_NORMALMAPS ";
- if (g_settings->getBool("enable_bumpmapping") ||
- g_settings->getBool("enable_parallax_occlusion"))
+ if (g_settings->getBool("enable_bumpmapping") || g_settings->getBool("enable_parallax_occlusion"))
shaders_header += "1\n";
else
shaders_header += "0\n";
- if (g_settings->getBool("enable_waving_water")) {
+ if (g_settings->getBool("enable_waving_water")){
shaders_header += "#define ENABLE_WAVING_WATER 1\n";
shaders_header += "#define WATER_WAVE_HEIGHT ";
shaders_header += ftos(g_settings->getFloat("water_wave_height"));
@@ -727,7 +733,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
shaders_header += "#define WATER_WAVE_SPEED ";
shaders_header += ftos(g_settings->getFloat("water_wave_speed"));
shaders_header += "\n";
- } else {
+ } else{
shaders_header += "#define ENABLE_WAVING_WATER 0\n";
}
@@ -751,9 +757,9 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
shaders_header += "\n";
// Call addHighLevelShaderMaterial() or addShaderMaterial()
- const c8 *vertex_program_ptr = 0;
- const c8 *pixel_program_ptr = 0;
- const c8 *geometry_program_ptr = 0;
+ const c8* vertex_program_ptr = 0;
+ const c8* pixel_program_ptr = 0;
+ const c8* geometry_program_ptr = 0;
if (!vertex_program.empty()) {
vertex_program = shaders_header + vertex_program;
vertex_program_ptr = vertex_program.c_str();
@@ -768,57 +774,54 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
}
ShaderCallback *cb = new ShaderCallback(setter_factories);
s32 shadermat = -1;
- if (is_highlevel) {
- infostream << "Compiling high level shaders for " << name << std::endl;
+ if(is_highlevel){
+ infostream<<"Compiling high level shaders for "<<name<<std::endl;
shadermat = gpu->addHighLevelShaderMaterial(
- vertex_program_ptr, // Vertex shader program
- "vertexMain", // Vertex shader entry point
- video::EVST_VS_1_1, // Vertex shader version
- pixel_program_ptr, // Pixel shader program
- "pixelMain", // Pixel shader entry point
- video::EPST_PS_1_2, // Pixel shader version
- geometry_program_ptr, // Geometry shader program
- "geometryMain", // Geometry shader entry point
- video::EGST_GS_4_0, // Geometry shader version
- scene::EPT_TRIANGLES, // Geometry shader input
- scene::EPT_TRIANGLE_STRIP, // Geometry shader output
- 0, // Support maximum number of vertices
- cb, // Set-constant callback
- shaderinfo.base_material, // Base material
- 1 // Userdata passed to callback
- );
- if (shadermat == -1) {
- errorstream << "generate_shader(): "
- "failed to generate \""
- << name
- << "\", "
- "addHighLevelShaderMaterial failed."
- << std::endl;
+ vertex_program_ptr, // Vertex shader program
+ "vertexMain", // Vertex shader entry point
+ video::EVST_VS_1_1, // Vertex shader version
+ pixel_program_ptr, // Pixel shader program
+ "pixelMain", // Pixel shader entry point
+ video::EPST_PS_1_2, // Pixel shader version
+ geometry_program_ptr, // Geometry shader program
+ "geometryMain", // Geometry shader entry point
+ video::EGST_GS_4_0, // Geometry shader version
+ scene::EPT_TRIANGLES, // Geometry shader input
+ scene::EPT_TRIANGLE_STRIP, // Geometry shader output
+ 0, // Support maximum number of vertices
+ cb, // Set-constant callback
+ shaderinfo.base_material, // Base material
+ 1 // Userdata passed to callback
+ );
+ if(shadermat == -1){
+ errorstream<<"generate_shader(): "
+ "failed to generate \""<<name<<"\", "
+ "addHighLevelShaderMaterial failed."
+ <<std::endl;
dumpShaderProgram(warningstream, "Vertex", vertex_program);
dumpShaderProgram(warningstream, "Pixel", pixel_program);
dumpShaderProgram(warningstream, "Geometry", geometry_program);
delete cb;
return shaderinfo;
}
- } else {
- infostream << "Compiling assembly shaders for " << name << std::endl;
+ }
+ else{
+ infostream<<"Compiling assembly shaders for "<<name<<std::endl;
shadermat = gpu->addShaderMaterial(
- vertex_program_ptr, // Vertex shader program
- pixel_program_ptr, // Pixel shader program
- cb, // Set-constant callback
- shaderinfo.base_material, // Base material
- 0 // Userdata passed to callback
- );
-
- if (shadermat == -1) {
- errorstream << "generate_shader(): "
- "failed to generate \""
- << name
- << "\", "
- "addShaderMaterial failed."
- << std::endl;
+ vertex_program_ptr, // Vertex shader program
+ pixel_program_ptr, // Pixel shader program
+ cb, // Set-constant callback
+ shaderinfo.base_material, // Base material
+ 0 // Userdata passed to callback
+ );
+
+ if(shadermat == -1){
+ errorstream<<"generate_shader(): "
+ "failed to generate \""<<name<<"\", "
+ "addShaderMaterial failed."
+ <<std::endl;
dumpShaderProgram(warningstream, "Vertex", vertex_program);
- dumpShaderProgram(warningstream, "Pixel", pixel_program);
+ dumpShaderProgram(warningstream,"Pixel", pixel_program);
delete cb;
return shaderinfo;
}
@@ -830,7 +833,7 @@ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtyp
driver->getMaterialRenderer(shadermat)->grab();
// Apply the newly created material type
- shaderinfo.material = (video::E_MATERIAL_TYPE)shadermat;
+ shaderinfo.material = (video::E_MATERIAL_TYPE) shadermat;
return shaderinfo;
}
@@ -844,45 +847,43 @@ void load_shaders(const std::string &name, SourceShaderCache *sourcecache,
geometry_program = "";
is_highlevel = false;
- if (enable_shaders) {
+ if(enable_shaders){
// Look for high level shaders
- if (drivertype == video::EDT_DIRECT3D9) {
+ if(drivertype == video::EDT_DIRECT3D9){
// Direct3D 9: HLSL
// (All shaders in one file)
vertex_program = sourcecache->getOrLoad(name, "d3d9.hlsl");
pixel_program = vertex_program;
geometry_program = vertex_program;
- } else if (drivertype == video::EDT_OPENGL) {
+ }
+ else if(drivertype == video::EDT_OPENGL){
// OpenGL: GLSL
- vertex_program = sourcecache->getOrLoad(
- name, "opengl_vertex.glsl");
- pixel_program = sourcecache->getOrLoad(
- name, "opengl_fragment.glsl");
- geometry_program = sourcecache->getOrLoad(
- name, "opengl_geometry.glsl");
+ vertex_program = sourcecache->getOrLoad(name, "opengl_vertex.glsl");
+ pixel_program = sourcecache->getOrLoad(name, "opengl_fragment.glsl");
+ geometry_program = sourcecache->getOrLoad(name, "opengl_geometry.glsl");
}
- if (!vertex_program.empty() || !pixel_program.empty() ||
- !geometry_program.empty()) {
+ if (!vertex_program.empty() || !pixel_program.empty() || !geometry_program.empty()){
is_highlevel = true;
return;
}
}
+
}
-void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type,
- const std::string &program)
+void dumpShaderProgram(std::ostream &output_stream,
+ const std::string &program_type, const std::string &program)
{
- output_stream << program_type << " shader program:" << std::endl
- << "----------------------------------" << std::endl;
+ output_stream << program_type << " shader program:" << std::endl <<
+ "----------------------------------" << std::endl;
size_t pos = 0;
size_t prev = 0;
s16 line = 1;
while ((pos = program.find('\n', prev)) != std::string::npos) {
- output_stream << line++ << ": " << program.substr(prev, pos - prev)
- << std::endl;
+ output_stream << line++ << ": "<< program.substr(prev, pos - prev) <<
+ std::endl;
prev = pos + 1;
}
- output_stream << line << ": " << program.substr(prev) << std::endl
- << "End of " << program_type << " shader program." << std::endl
- << " " << std::endl;
+ output_stream << line << ": " << program.substr(prev) << std::endl <<
+ "End of " << program_type << " shader program." << std::endl <<
+ " " << std::endl;
}
diff --git a/src/client/shader.h b/src/client/shader.h
index 4d1578df0..109d39336 100644
--- a/src/client/shader.h
+++ b/src/client/shader.h
@@ -39,10 +39,10 @@ class IGameDef;
Utilizes a thread-safe cache.
*/
-std::string getShaderPath(const std::string &name_of_shader, const std::string &filename);
+std::string getShaderPath(const std::string &name_of_shader,
+ const std::string &filename);
-struct ShaderInfo
-{
+struct ShaderInfo {
std::string name = "";
video::E_MATERIAL_TYPE base_material = video::EMT_SOLID;
video::E_MATERIAL_TYPE material = video::EMT_SOLID;
@@ -57,43 +57,38 @@ struct ShaderInfo
Setter of constants for shaders
*/
-namespace irr
-{
-namespace video
-{
-class IMaterialRendererServices;
-}
-}
+namespace irr { namespace video {
+ class IMaterialRendererServices;
+} }
-class IShaderConstantSetter
-{
+
+class IShaderConstantSetter {
public:
virtual ~IShaderConstantSetter() = default;
virtual void onSetConstants(video::IMaterialRendererServices *services,
bool is_highlevel) = 0;
- virtual void onSetMaterial(const video::SMaterial &material) {}
+ virtual void onSetMaterial(const video::SMaterial& material)
+ { }
};
-class IShaderConstantSetterFactory
-{
+
+class IShaderConstantSetterFactory {
public:
virtual ~IShaderConstantSetterFactory() = default;
- virtual IShaderConstantSetter *create() = 0;
+ virtual IShaderConstantSetter* create() = 0;
};
-template <typename T, std::size_t count = 1> class CachedShaderSetting
-{
+
+template <typename T, std::size_t count=1>
+class CachedShaderSetting {
const char *m_name;
T m_sent[count];
bool has_been_set = false;
bool is_pixel;
-
protected:
CachedShaderSetting(const char *name, bool is_pixel) :
- m_name(name), is_pixel(is_pixel)
- {
- }
-
+ m_name(name), is_pixel(is_pixel)
+ {}
public:
void set(const T value[count], video::IMaterialRendererServices *services)
{
@@ -109,75 +104,55 @@ public:
};
template <typename T, std::size_t count = 1>
-class CachedPixelShaderSetting : public CachedShaderSetting<T, count>
-{
+class CachedPixelShaderSetting : public CachedShaderSetting<T, count> {
public:
CachedPixelShaderSetting(const char *name) :
- CachedShaderSetting<T, count>(name, true)
- {
- }
+ CachedShaderSetting<T, count>(name, true){}
};
template <typename T, std::size_t count = 1>
-class CachedVertexShaderSetting : public CachedShaderSetting<T, count>
-{
+class CachedVertexShaderSetting : public CachedShaderSetting<T, count> {
public:
CachedVertexShaderSetting(const char *name) :
- CachedShaderSetting<T, count>(name, false)
- {
- }
+ CachedShaderSetting<T, count>(name, false){}
};
+
/*
ShaderSource creates and caches shaders.
*/
-class IShaderSource
-{
+class IShaderSource {
public:
IShaderSource() = default;
virtual ~IShaderSource() = default;
- virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type,
- const u8 drawtype)
- {
- return 0;
- }
- virtual ShaderInfo getShaderInfo(u32 id) { return ShaderInfo(); }
- virtual u32 getShader(const std::string &name, const u8 material_type,
- const u8 drawtype)
- {
- return 0;
- }
+ virtual u32 getShaderIdDirect(const std::string &name,
+ const u8 material_type, const u8 drawtype){return 0;}
+ virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();}
+ virtual u32 getShader(const std::string &name,
+ const u8 material_type, const u8 drawtype){return 0;}
};
-class IWritableShaderSource : public IShaderSource
-{
+class IWritableShaderSource : public IShaderSource {
public:
IWritableShaderSource() = default;
virtual ~IWritableShaderSource() = default;
- virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type,
- const u8 drawtype)
- {
- return 0;
- }
- virtual ShaderInfo getShaderInfo(u32 id) { return ShaderInfo(); }
- virtual u32 getShader(const std::string &name, const u8 material_type,
- const u8 drawtype)
- {
- return 0;
- }
+ virtual u32 getShaderIdDirect(const std::string &name,
+ const u8 material_type, const u8 drawtype){return 0;}
+ virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();}
+ virtual u32 getShader(const std::string &name,
+ const u8 material_type, const u8 drawtype){return 0;}
- virtual void processQueue() = 0;
+ virtual void processQueue()=0;
virtual void insertSourceShader(const std::string &name_of_shader,
- const std::string &filename, const std::string &program) = 0;
- virtual void rebuildShaders() = 0;
- virtual void addShaderConstantSetterFactory(
- IShaderConstantSetterFactory *setter) = 0;
+ const std::string &filename, const std::string &program)=0;
+ virtual void rebuildShaders()=0;
+ virtual void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) = 0;
};
IWritableShaderSource *createShaderSource();
-void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type,
- const std::string &program);
+void dumpShaderProgram(std::ostream &output_stream,
+ const std::string &program_type, const std::string &program);
diff --git a/src/client/sky.cpp b/src/client/sky.cpp
index fa36f623e..2e0cbca86 100644
--- a/src/client/sky.cpp
+++ b/src/client/sky.cpp
@@ -35,9 +35,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
using namespace irr::core;
Sky::Sky(s32 id, ITextureSource *tsrc) :
- scene::ISceneNode(
- RenderingEngine::get_scene_manager()->getRootSceneNode(),
- RenderingEngine::get_scene_manager(), id)
+ scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
+ RenderingEngine::get_scene_manager(), id)
{
setAutomaticCulling(scene::EAC_OFF);
m_box.MaxEdge.set(0, 0, 0);
@@ -61,40 +60,33 @@ Sky::Sky(s32 id, ITextureSource *tsrc) :
m_materials[0] = mat;
m_materials[1] = mat;
- // m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
+ //m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
m_materials[2] = mat;
m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png"));
m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
- // m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
+ //m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
// Ensures that sun and moon textures and tonemaps are correct.
setSkyDefaults();
- m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture)
- ? tsrc->getTextureForMesh(m_sun_params.texture)
- : NULL;
- m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture)
- ? tsrc->getTextureForMesh(m_moon_params.texture)
- : NULL;
- m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap)
- ? tsrc->getTexture(m_sun_params.tonemap)
- : NULL;
- m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap)
- ? tsrc->getTexture(m_moon_params.tonemap)
- : NULL;
+ m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) ?
+ tsrc->getTextureForMesh(m_sun_params.texture) : NULL;
+ m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) ?
+ tsrc->getTextureForMesh(m_moon_params.texture) : NULL;
+ m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
+ tsrc->getTexture(m_sun_params.tonemap) : NULL;
+ m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
+ tsrc->getTexture(m_moon_params.tonemap) : NULL;
if (m_sun_texture) {
m_materials[3] = mat;
m_materials[3].setTexture(0, m_sun_texture);
m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
// Disables texture filtering
- m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
- m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
- m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
+ m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
+ m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
+ m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
// Use tonemaps if available
if (m_sun_tonemap)
m_materials[3].Lighting = true;
@@ -104,12 +96,9 @@ Sky::Sky(s32 id, ITextureSource *tsrc) :
m_materials[4].setTexture(0, m_moon_texture);
m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
// Disables texture filtering
- m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
- m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
- m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
+ m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
+ m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
+ m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
// Use tonemaps if available
if (m_moon_tonemap)
m_materials[4].Lighting = true;
@@ -157,9 +146,9 @@ void Sky::render()
if (m_sunlight_seen) {
float sunsize = 0.07;
video::SColorf suncolor_f(1, 1, 0, 1);
- // suncolor_f.r = 1;
- // suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5));
- // suncolor_f.b = MYMAX(0.0, m_brightness * 0.95);
+ //suncolor_f.r = 1;
+ //suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5));
+ //suncolor_f.b = MYMAX(0.0, m_brightness * 0.95);
video::SColorf suncolor2_f(1, 1, 1, 1);
// The values below were probably meant to be suncolor2_f instead of a
// reassignment of suncolor_f. However, the resulting colour was chosen
@@ -177,8 +166,7 @@ void Sky::render()
float wn = nightlength / 2;
float wicked_time_of_day = 0;
if (m_time_of_day > wn && m_time_of_day < 1.0 - wn)
- wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 +
- 0.25;
+ wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25;
else if (m_time_of_day < 0.5)
wicked_time_of_day = m_time_of_day / wn * 0.25;
else
@@ -192,25 +180,22 @@ void Sky::render()
video::SColor mooncolor2 = mooncolor2_f.toSColor();
// Calculate offset normalized to the X dimension of a 512x1 px tonemap
- float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) *
- 511;
+ float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511;
if (m_sun_tonemap) {
- u8 *texels = (u8 *)m_sun_tonemap->lock();
- video::SColor *texel =
- (video::SColor *)(texels + (u32)offset * 4);
- video::SColor texel_color(255, texel->getRed(), texel->getGreen(),
- texel->getBlue());
+ u8 * texels = (u8 *)m_sun_tonemap->lock();
+ video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
+ video::SColor texel_color (255, texel->getRed(),
+ texel->getGreen(), texel->getBlue());
m_sun_tonemap->unlock();
m_materials[3].EmissiveColor = texel_color;
}
if (m_moon_tonemap) {
- u8 *texels = (u8 *)m_moon_tonemap->lock();
- video::SColor *texel =
- (video::SColor *)(texels + (u32)offset * 4);
- video::SColor texel_color(255, texel->getRed(), texel->getGreen(),
- texel->getBlue());
+ u8 * texels = (u8 *)m_moon_tonemap->lock();
+ video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
+ video::SColor texel_color (255, texel->getRed(),
+ texel->getGreen(), texel->getBlue());
m_moon_tonemap->unlock();
m_materials[4].EmissiveColor = texel_color;
}
@@ -236,14 +221,10 @@ void Sky::render()
driver->setMaterial(m_materials[j]);
// Use 1.05 rather than 1.0 to avoid colliding with the
// sun, moon and stars, as this is a background skybox.
- vertices[0] = video::S3DVertex(
- -1.05, -1.05, -1.05, 0, 0, 1, c, t, t);
- vertices[1] = video::S3DVertex(
- 1.05, -1.05, -1.05, 0, 0, 1, c, o, t);
- vertices[2] = video::S3DVertex(
- 1.05, 1.05, -1.05, 0, 0, 1, c, o, o);
- vertices[3] = video::S3DVertex(
- -1.05, 1.05, -1.05, 0, 0, 1, c, t, o);
+ vertices[0] = video::S3DVertex(-1.05, -1.05, -1.05, 0, 0, 1, c, t, t);
+ vertices[1] = video::S3DVertex( 1.05, -1.05, -1.05, 0, 0, 1, c, o, t);
+ vertices[2] = video::S3DVertex( 1.05, 1.05, -1.05, 0, 0, 1, c, o, o);
+ vertices[3] = video::S3DVertex(-1.05, 1.05, -1.05, 0, 0, 1, c, t, o);
for (video::S3DVertex &vertex : vertices) {
if (j == 5) { // Top texture
vertex.Pos.rotateYZBy(90);
@@ -256,16 +237,14 @@ void Sky::render()
} else if (j == 8) { // Right texture
vertex.Pos.rotateXZBy(-90);
} else if (j == 9) { // Front texture, do nothing
- // Irrlicht doesn't like it when vertexes
- // are left alone and not rotated for some
- // reason.
+ // Irrlicht doesn't like it when vertexes are left
+ // alone and not rotated for some reason.
vertex.Pos.rotateXZBy(0);
- } else { // Back texture
+ } else {// Back texture
vertex.Pos.rotateXZBy(180);
}
}
- driver->drawIndexedTriangleFan(
- &vertices[0], 4, indices, 2);
+ driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
}
}
@@ -273,19 +252,15 @@ void Sky::render()
if (m_visible) {
driver->setMaterial(m_materials[1]);
for (u32 j = 0; j < 4; j++) {
- vertices[0] = video::S3DVertex(
- -1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t);
- vertices[1] = video::S3DVertex(
- 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t);
- vertices[2] = video::S3DVertex(
- 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o);
- vertices[3] = video::S3DVertex(
- -1, 0.45, -1, 0, 0, 1, m_skycolor, t, o);
+ vertices[0] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t);
+ vertices[1] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t);
+ vertices[2] = video::S3DVertex( 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o);
+ vertices[3] = video::S3DVertex(-1, 0.45, -1, 0, 0, 1, m_skycolor, t, o);
for (video::S3DVertex &vertex : vertices) {
if (j == 0)
- // Don't switch
- {
- } else if (j == 1)
+ // Don't switch
+ {}
+ else if (j == 1)
// Switch from -Z (south) to +X (east)
vertex.Pos.rotateXZBy(90);
else if (j == 2)
@@ -295,8 +270,7 @@ void Sky::render()
// Switch from -Z (south) to +Z (north)
vertex.Pos.rotateXZBy(-180);
}
- driver->drawIndexedTriangleFan(
- &vertices[0], 4, indices, 2);
+ driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
}
}
@@ -312,15 +286,13 @@ void Sky::render()
float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1);
float a_ = 1.0f - std::fabs(wicked_time_of_day - mid) * 35.0f;
float a = easeCurve(MYMAX(0, MYMIN(1, a_)));
- // std::cerr<<"a_="<<a_<<" a="<<a<<std::endl;
+ //std::cerr<<"a_="<<a_<<" a="<<a<<std::endl;
video::SColor c(255, 255, 255, 255);
float y = -(1.0 - a) * 0.22;
- vertices[0] = video::S3DVertex(
- -1, -0.05 + y, -1, 0, 0, 1, c, t, t);
- vertices[1] = video::S3DVertex(
- 1, -0.05 + y, -1, 0, 0, 1, c, o, t);
- vertices[2] = video::S3DVertex(1, 0.2 + y, -1, 0, 0, 1, c, o, o);
- vertices[3] = video::S3DVertex(-1, 0.2 + y, -1, 0, 0, 1, c, t, o);
+ vertices[0] = video::S3DVertex(-1, -0.05 + y, -1, 0, 0, 1, c, t, t);
+ vertices[1] = video::S3DVertex( 1, -0.05 + y, -1, 0, 0, 1, c, o, t);
+ vertices[2] = video::S3DVertex( 1, 0.2 + y, -1, 0, 0, 1, c, o, o);
+ vertices[3] = video::S3DVertex(-1, 0.2 + y, -1, 0, 0, 1, c, t, o);
for (video::S3DVertex &vertex : vertices) {
if (wicked_time_of_day < 0.5)
// Switch from -Z (south) to +X (east)
@@ -334,13 +306,11 @@ void Sky::render()
// Draw sun
if (m_sun_params.visible)
- draw_sun(driver, sunsize, suncolor, suncolor2,
- wicked_time_of_day);
+ draw_sun(driver, sunsize, suncolor, suncolor2, wicked_time_of_day);
// Draw moon
if (m_moon_params.visible)
- draw_moon(driver, moonsize, mooncolor, mooncolor2,
- wicked_time_of_day);
+ draw_moon(driver, moonsize, mooncolor, mooncolor2, wicked_time_of_day);
// Draw far cloudy fog thing below all horizons in front of sun, moon
// and stars.
@@ -349,19 +319,15 @@ void Sky::render()
for (u32 j = 0; j < 4; j++) {
video::SColor c = cloudyfogcolor;
- vertices[0] = video::S3DVertex(
- -1, -1.0, -1, 0, 0, 1, c, t, t);
- vertices[1] = video::S3DVertex(
- 1, -1.0, -1, 0, 0, 1, c, o, t);
- vertices[2] = video::S3DVertex(
- 1, -0.02, -1, 0, 0, 1, c, o, o);
- vertices[3] = video::S3DVertex(
- -1, -0.02, -1, 0, 0, 1, c, t, o);
+ vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 0, 1, c, t, t);
+ vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 0, 1, c, o, t);
+ vertices[2] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, c, o, o);
+ vertices[3] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, c, t, o);
for (video::S3DVertex &vertex : vertices) {
if (j == 0)
- // Don't switch
- {
- } else if (j == 1)
+ // Don't switch
+ {}
+ else if (j == 1)
// Switch from -Z (south) to +X (east)
vertex.Pos.rotateXZBy(90);
else if (j == 2)
@@ -371,24 +337,23 @@ void Sky::render()
// Switch from -Z (south) to +Z (north)
vertex.Pos.rotateXZBy(-180);
}
- driver->drawIndexedTriangleFan(
- &vertices[0], 4, indices, 2);
+ driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
}
- // Draw bottom far cloudy fog thing in front of sun, moon and
- // stars
+ // Draw bottom far cloudy fog thing in front of sun, moon and stars
video::SColor c = cloudyfogcolor;
vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 1, 0, c, t, t);
- vertices[1] = video::S3DVertex(1, -1.0, -1, 0, 1, 0, c, o, t);
- vertices[2] = video::S3DVertex(1, -1.0, 1, 0, 1, 0, c, o, o);
+ vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 1, 0, c, o, t);
+ vertices[2] = video::S3DVertex( 1, -1.0, 1, 0, 1, 0, c, o, o);
vertices[3] = video::S3DVertex(-1, -1.0, 1, 0, 1, 0, c, t, o);
driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
}
}
}
-void Sky::update(float time_of_day, float time_brightness, float direct_brightness,
- bool sunlight_seen, CameraMode cam_mode, float yaw, float pitch)
+void Sky::update(float time_of_day, float time_brightness,
+ float direct_brightness, bool sunlight_seen,
+ CameraMode cam_mode, float yaw, float pitch)
{
// Stabilize initial brightness and color values by flooding updates
if (m_first_update) {
@@ -415,8 +380,8 @@ void Sky::update(float time_of_day, float time_brightness, float direct_brightne
Development colours
video::SColorf bgcolor_bright_normal_f(170. / 255, 200. / 255, 230. / 255, 1.0);
- video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 *
- 0.5, 1.0); video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0);
+ video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 * 0.5, 1.0);
+ video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0);
video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.0, 1.0);
video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.2, 1.0);
@@ -457,58 +422,58 @@ void Sky::update(float time_of_day, float time_brightness, float direct_brightne
if (sunlight_seen) {
if (is_dawn) { // Dawn
m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
- bgcolor_bright_dawn_f, color_change_fraction);
+ bgcolor_bright_dawn_f, color_change_fraction);
m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
- skycolor_bright_dawn_f, color_change_fraction);
+ skycolor_bright_dawn_f, color_change_fraction);
m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
- cloudcolor_bright_dawn_f, color_change_fraction);
+ cloudcolor_bright_dawn_f, color_change_fraction);
} else {
if (time_brightness < 0.13f) { // Night
m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
- bgcolor_bright_night_f,
- color_change_fraction);
+ bgcolor_bright_night_f, color_change_fraction);
m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
- skycolor_bright_night_f,
- color_change_fraction);
+ skycolor_bright_night_f, color_change_fraction);
} else { // Day
m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
- bgcolor_bright_normal_f,
- color_change_fraction);
+ bgcolor_bright_normal_f, color_change_fraction);
m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
- skycolor_bright_normal_f,
- color_change_fraction);
+ skycolor_bright_normal_f, color_change_fraction);
}
m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
- cloudcolor_bright_normal_f,
- color_change_fraction);
+ cloudcolor_bright_normal_f, color_change_fraction);
}
} else {
m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
- bgcolor_bright_indoor_f, color_change_fraction);
+ bgcolor_bright_indoor_f, color_change_fraction);
m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
- bgcolor_bright_indoor_f, color_change_fraction);
+ bgcolor_bright_indoor_f, color_change_fraction);
m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
- cloudcolor_bright_normal_f, color_change_fraction);
+ cloudcolor_bright_normal_f, color_change_fraction);
m_clouds_visible = false;
}
video::SColor bgcolor_bright = m_bgcolor_bright_f.toSColor();
- m_bgcolor = video::SColor(255, bgcolor_bright.getRed() * m_brightness,
- bgcolor_bright.getGreen() * m_brightness,
- bgcolor_bright.getBlue() * m_brightness);
+ m_bgcolor = video::SColor(
+ 255,
+ bgcolor_bright.getRed() * m_brightness,
+ bgcolor_bright.getGreen() * m_brightness,
+ bgcolor_bright.getBlue() * m_brightness
+ );
video::SColor skycolor_bright = m_skycolor_bright_f.toSColor();
- m_skycolor = video::SColor(255, skycolor_bright.getRed() * m_brightness,
- skycolor_bright.getGreen() * m_brightness,
- skycolor_bright.getBlue() * m_brightness);
+ m_skycolor = video::SColor(
+ 255,
+ skycolor_bright.getRed() * m_brightness,
+ skycolor_bright.getGreen() * m_brightness,
+ skycolor_bright.getBlue() * m_brightness
+ );
// Horizon coloring based on sun and moon direction during sunset and sunrise
video::SColor pointcolor = video::SColor(m_bgcolor.getAlpha(), 255, 255, 255);
if (m_directional_colored_fog) {
if (m_horizon_blend() != 0) {
- // Calculate hemisphere value from yaw, (inverted in third person
- // front view)
+ // Calculate hemisphere value from yaw, (inverted in third person front view)
s8 dir_factor = 1;
if (cam_mode > CAMERA_MODE_THIRD)
dir_factor = -1;
@@ -517,14 +482,11 @@ void Sky::update(float time_of_day, float time_brightness, float direct_brightne
pointcolor_blend = 360 - pointcolor_blend;
pointcolor_blend /= 180;
// Bound view angle to determine where transition starts and ends
- pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0,
- 1 / 1.375) *
- 1.375;
- // Combine the colors when looking up or down, otherwise turning
- // looks weird
+ pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0, 1 / 1.375) *
+ 1.375;
+ // Combine the colors when looking up or down, otherwise turning looks weird
pointcolor_blend += (0.5 - pointcolor_blend) *
- (1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5,
- 1));
+ (1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5, 1));
// Invert direction to match where the sun and moon are rising
if (m_time_of_day > 0.5)
pointcolor_blend = 1 - pointcolor_blend;
@@ -535,142 +497,109 @@ void Sky::update(float time_of_day, float time_brightness, float direct_brightne
// Use tonemap only if default sun/moon tinting is used
// which keeps previous behaviour.
if (m_sun_tonemap && m_default_tint) {
- pointcolor_sun_f.r =
- pointcolor_light *
- (float)m_materials[3]
- .EmissiveColor.getRed() /
- 255;
- pointcolor_sun_f.b =
- pointcolor_light *
- (float)m_materials[3]
- .EmissiveColor.getBlue() /
- 255;
+ pointcolor_sun_f.r = pointcolor_light *
+ (float)m_materials[3].EmissiveColor.getRed() / 255;
+ pointcolor_sun_f.b = pointcolor_light *
+ (float)m_materials[3].EmissiveColor.getBlue() / 255;
pointcolor_sun_f.g = pointcolor_light *
- (float)m_materials[3]
- .EmissiveColor
- .getGreen() /
- 255;
+ (float)m_materials[3].EmissiveColor.getGreen() / 255;
} else if (!m_default_tint) {
pointcolor_sun_f = m_sky_params.fog_sun_tint;
} else {
pointcolor_sun_f.r = pointcolor_light * 1;
- pointcolor_sun_f.b =
- pointcolor_light *
- (0.25 + (rangelim(m_time_brightness, 0.25,
- 0.75) -
- 0.25) * 2 *
- 0.75);
- pointcolor_sun_f.g =
- pointcolor_light *
- (pointcolor_sun_f.b * 0.375 +
- (rangelim(m_time_brightness,
- 0.05,
- 0.15) -
- 0.05) *
- 10 *
- 0.625);
+ pointcolor_sun_f.b = pointcolor_light *
+ (0.25 + (rangelim(m_time_brightness, 0.25, 0.75) - 0.25) * 2 * 0.75);
+ pointcolor_sun_f.g = pointcolor_light * (pointcolor_sun_f.b * 0.375 +
+ (rangelim(m_time_brightness, 0.05, 0.15) - 0.05) * 10 * 0.625);
}
video::SColorf pointcolor_moon_f;
if (m_default_tint) {
- pointcolor_moon_f = video::SColorf(0.5 * pointcolor_light,
- 0.6 * pointcolor_light,
- 0.8 * pointcolor_light, 1);
+ pointcolor_moon_f = video::SColorf(
+ 0.5 * pointcolor_light,
+ 0.6 * pointcolor_light,
+ 0.8 * pointcolor_light,
+ 1
+ );
} else {
pointcolor_moon_f = video::SColorf(
- (m_sky_params.fog_moon_tint.getRed() /
- 255) *
- pointcolor_light,
- (m_sky_params.fog_moon_tint.getGreen() /
- 255) *
- pointcolor_light,
- (m_sky_params.fog_moon_tint.getBlue() /
- 255) *
- pointcolor_light,
- 1);
+ (m_sky_params.fog_moon_tint.getRed() / 255) * pointcolor_light,
+ (m_sky_params.fog_moon_tint.getGreen() / 255) * pointcolor_light,
+ (m_sky_params.fog_moon_tint.getBlue() / 255) * pointcolor_light,
+ 1
+ );
}
if (m_moon_tonemap && m_default_tint) {
- pointcolor_moon_f.r =
- pointcolor_light *
- (float)m_materials[4]
- .EmissiveColor.getRed() /
- 255;
- pointcolor_moon_f.b =
- pointcolor_light *
- (float)m_materials[4]
- .EmissiveColor.getBlue() /
- 255;
+ pointcolor_moon_f.r = pointcolor_light *
+ (float)m_materials[4].EmissiveColor.getRed() / 255;
+ pointcolor_moon_f.b = pointcolor_light *
+ (float)m_materials[4].EmissiveColor.getBlue() / 255;
pointcolor_moon_f.g = pointcolor_light *
- (float)m_materials[4]
- .EmissiveColor
- .getGreen() /
- 255;
+ (float)m_materials[4].EmissiveColor.getGreen() / 255;
}
video::SColor pointcolor_sun = pointcolor_sun_f.toSColor();
video::SColor pointcolor_moon = pointcolor_moon_f.toSColor();
// Calculate the blend color
- pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun,
- pointcolor_blend);
+ pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun, pointcolor_blend);
}
m_bgcolor = m_mix_scolor(m_bgcolor, pointcolor, m_horizon_blend() * 0.5);
- m_skycolor = m_mix_scolor(
- m_skycolor, pointcolor, m_horizon_blend() * 0.25);
+ m_skycolor = m_mix_scolor(m_skycolor, pointcolor, m_horizon_blend() * 0.25);
}
float cloud_direct_brightness = 0.0f;
if (sunlight_seen) {
if (!m_directional_colored_fog) {
cloud_direct_brightness = time_brightness;
- // Boost cloud brightness relative to sky, at dawn, dusk and at
- // night
+ // Boost cloud brightness relative to sky, at dawn, dusk and at night
if (time_brightness < 0.7f)
cloud_direct_brightness *= 1.3f;
} else {
- cloud_direct_brightness = std::fmin(
- m_horizon_blend() * 0.15f + m_time_brightness,
- 1.0f);
+ cloud_direct_brightness = std::fmin(m_horizon_blend() * 0.15f +
+ m_time_brightness, 1.0f);
// Set the same minimum cloud brightness at night
if (time_brightness < 0.5f)
- cloud_direct_brightness =
- std::fmax(cloud_direct_brightness,
- time_brightness * 1.3f);
+ cloud_direct_brightness = std::fmax(cloud_direct_brightness,
+ time_brightness * 1.3f);
}
} else {
cloud_direct_brightness = direct_brightness;
}
- m_cloud_brightness =
- m_cloud_brightness * cloud_color_change_fraction +
- cloud_direct_brightness * (1.0 - cloud_color_change_fraction);
- m_cloudcolor_f = video::SColorf(m_cloudcolor_bright_f.r * m_cloud_brightness,
- m_cloudcolor_bright_f.g * m_cloud_brightness,
- m_cloudcolor_bright_f.b * m_cloud_brightness, 1.0);
+ m_cloud_brightness = m_cloud_brightness * cloud_color_change_fraction +
+ cloud_direct_brightness * (1.0 - cloud_color_change_fraction);
+ m_cloudcolor_f = video::SColorf(
+ m_cloudcolor_bright_f.r * m_cloud_brightness,
+ m_cloudcolor_bright_f.g * m_cloud_brightness,
+ m_cloudcolor_bright_f.b * m_cloud_brightness,
+ 1.0
+ );
if (m_directional_colored_fog) {
- m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f, video::SColorf(pointcolor),
- m_horizon_blend() * 0.25);
+ m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f,
+ video::SColorf(pointcolor), m_horizon_blend() * 0.25);
}
}
-void Sky::draw_sun(video::IVideoDriver *driver, float sunsize,
- const video::SColor &suncolor, const video::SColor &suncolor2,
- float wicked_time_of_day)
-/* Draw sun in the sky.
- * driver: Video driver object used to draw
- * sunsize: the default size of the sun
- * suncolor: main sun color
- * suncolor2: second sun color
- * wicked_time_of_day: current time of day, to know where should be the sun in the sky
- */
+void Sky::draw_sun(video::IVideoDriver *driver, float sunsize, const video::SColor &suncolor,
+ const video::SColor &suncolor2, float wicked_time_of_day)
+ /* Draw sun in the sky.
+ * driver: Video driver object used to draw
+ * sunsize: the default size of the sun
+ * suncolor: main sun color
+ * suncolor2: second sun color
+ * wicked_time_of_day: current time of day, to know where should be the sun in the sky
+ */
{
static const u16 indices[4] = {0, 1, 2, 3};
std::array<video::S3DVertex, 4> vertices;
if (!m_sun_texture) {
driver->setMaterial(m_materials[1]);
- const float sunsizes[4] = {(sunsize * 1.7f) * m_sun_params.scale,
- (sunsize * 1.2f) * m_sun_params.scale,
- (sunsize)*m_sun_params.scale,
- (sunsize * 0.7f) * m_sun_params.scale};
+ const float sunsizes[4] = {
+ (sunsize * 1.7f) * m_sun_params.scale,
+ (sunsize * 1.2f) * m_sun_params.scale,
+ (sunsize) * m_sun_params.scale,
+ (sunsize * 0.7f) * m_sun_params.scale
+ };
video::SColor c1 = suncolor;
video::SColor c2 = suncolor;
c1.setAlpha(0.05 * 255);
@@ -695,39 +624,42 @@ void Sky::draw_sun(video::IVideoDriver *driver, float sunsize,
}
}
-void Sky::draw_moon(video::IVideoDriver *driver, float moonsize,
- const video::SColor &mooncolor, const video::SColor &mooncolor2,
- float wicked_time_of_day)
+
+void Sky::draw_moon(video::IVideoDriver *driver, float moonsize, const video::SColor &mooncolor,
+ const video::SColor &mooncolor2, float wicked_time_of_day)
/*
- * Draw moon in the sky.
- * driver: Video driver object used to draw
- * moonsize: the default size of the moon
- * mooncolor: main moon color
- * mooncolor2: second moon color
- * wicked_time_of_day: current time of day, to know where should be the moon in
- * the sky
- */
+ * Draw moon in the sky.
+ * driver: Video driver object used to draw
+ * moonsize: the default size of the moon
+ * mooncolor: main moon color
+ * mooncolor2: second moon color
+ * wicked_time_of_day: current time of day, to know where should be the moon in
+ * the sky
+ */
{
static const u16 indices[4] = {0, 1, 2, 3};
std::array<video::S3DVertex, 4> vertices;
if (!m_moon_texture) {
driver->setMaterial(m_materials[1]);
- const float moonsizes_1[4] = {(-moonsize * 1.9f) * m_moon_params.scale,
- (-moonsize * 1.3f) * m_moon_params.scale,
- (-moonsize) * m_moon_params.scale,
- (-moonsize) * m_moon_params.scale};
- const float moonsizes_2[4] = {(moonsize * 1.9f) * m_moon_params.scale,
- (moonsize * 1.3f) * m_moon_params.scale,
- (moonsize)*m_moon_params.scale,
- (moonsize * 0.6f) * m_moon_params.scale};
+ const float moonsizes_1[4] = {
+ (-moonsize * 1.9f) * m_moon_params.scale,
+ (-moonsize * 1.3f) * m_moon_params.scale,
+ (-moonsize) * m_moon_params.scale,
+ (-moonsize) * m_moon_params.scale
+ };
+ const float moonsizes_2[4] = {
+ (moonsize * 1.9f) * m_moon_params.scale,
+ (moonsize * 1.3f) * m_moon_params.scale,
+ (moonsize) *m_moon_params.scale,
+ (moonsize * 0.6f) * m_moon_params.scale
+ };
video::SColor c1 = mooncolor;
video::SColor c2 = mooncolor;
c1.setAlpha(0.05 * 255);
c2.setAlpha(0.15 * 255);
const video::SColor colors[4] = {c1, c2, mooncolor, mooncolor2};
for (int i = 0; i < 4; i++) {
- draw_sky_body(vertices, moonsizes_1[i], moonsizes_2[i],
- colors[i]);
+ draw_sky_body(vertices, moonsizes_1[i], moonsizes_2[i], colors[i]);
place_sky_body(vertices, -90, wicked_time_of_day * 360 - 90);
driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2);
}
@@ -745,7 +677,7 @@ void Sky::draw_moon(video::IVideoDriver *driver, float moonsize,
}
}
-void Sky::draw_stars(video::IVideoDriver *driver, float wicked_time_of_day)
+void Sky::draw_stars(video::IVideoDriver * driver, float wicked_time_of_day)
{
driver->setMaterial(m_materials[1]);
// Tune values so that stars first appear just after the sun
@@ -754,8 +686,7 @@ void Sky::draw_stars(video::IVideoDriver *driver, float wicked_time_of_day)
// Also tune so that stars are at full brightness from time 20000
// to time 4000.
- float tod = wicked_time_of_day < 0.5f ? wicked_time_of_day
- : (1.0f - wicked_time_of_day);
+ float tod = wicked_time_of_day < 0.5f ? wicked_time_of_day : (1.0f - wicked_time_of_day);
float starbrightness = clamp((0.25f - fabsf(tod)) * 20.0f, 0.0f, 1.0f);
float f = starbrightness;
@@ -769,7 +700,8 @@ void Sky::draw_stars(video::IVideoDriver *driver, float wicked_time_of_day)
return;
#if ENABLE_GLES
u16 *indices = new u16[m_star_params.count * 3];
- video::S3DVertex *vertices = new video::S3DVertex[m_star_params.count * 3];
+ video::S3DVertex *vertices =
+ new video::S3DVertex[m_star_params.count * 3];
for (u32 i = 0; i < m_star_params.count; i++) {
indices[i * 3 + 0] = i * 3 + 0;
indices[i * 3 + 1] = i * 3 + 1;
@@ -793,13 +725,14 @@ void Sky::draw_stars(video::IVideoDriver *driver, float wicked_time_of_day)
vertices[i * 3 + 2].Pos = p2;
vertices[i * 3 + 2].Color = starcolor;
}
- driver->drawIndexedTriangleList(
- vertices, m_star_params.count * 3, indices, m_star_params.count);
+ driver->drawIndexedTriangleList(vertices, m_star_params.count * 3,
+ indices, m_star_params.count);
delete[] indices;
delete[] vertices;
#else
u16 *indices = new u16[m_star_params.count * 4];
- video::S3DVertex *vertices = new video::S3DVertex[m_star_params.count * 4];
+ video::S3DVertex *vertices =
+ new video::S3DVertex[m_star_params.count * 4];
for (u32 i = 0; i < m_star_params.count; i++) {
indices[i * 4 + 0] = i * 4 + 0;
indices[i * 4 + 1] = i * 4 + 1;
@@ -829,22 +762,21 @@ void Sky::draw_stars(video::IVideoDriver *driver, float wicked_time_of_day)
vertices[i * 4 + 3].Pos = p3;
vertices[i * 4 + 3].Color = starcolor;
}
- driver->drawVertexPrimitiveList(vertices, m_star_params.count * 4, indices,
- m_star_params.count, video::EVT_STANDARD, scene::EPT_QUADS,
- video::EIT_16BIT);
+ driver->drawVertexPrimitiveList(vertices, m_star_params.count * 4,
+ indices, m_star_params.count, video::EVT_STANDARD,
+ scene::EPT_QUADS, video::EIT_16BIT);
delete[] indices;
delete[] vertices;
#endif
}
-void Sky::draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1,
- float pos_2, const video::SColor &c)
+void Sky::draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1, float pos_2, const video::SColor &c)
{
/*
- * Create an array of vertices with the dimensions specified.
- * pos_1, pos_2: position of the body's vertices
- * c: color of the body
- */
+ * Create an array of vertices with the dimensions specified.
+ * pos_1, pos_2: position of the body's vertices
+ * c: color of the body
+ */
const f32 t = 1.0f;
const f32 o = 0.0f;
@@ -854,15 +786,15 @@ void Sky::draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1,
vertices[3] = video::S3DVertex(pos_1, pos_2, -1, 0, 0, 1, c, t, o);
}
-void Sky::place_sky_body(std::array<video::S3DVertex, 4> &vertices,
- float horizon_position, float day_position)
-/*
- * Place body in the sky.
- * vertices: The body as a rectangle of 4 vertices
- * horizon_position: turn the body around the Y axis
- * day_position: turn the body around the Z axis, to place it depending of the time of the
- * day
- */
+
+void Sky::place_sky_body(
+ std::array<video::S3DVertex, 4> &vertices, float horizon_position, float day_position)
+ /*
+ * Place body in the sky.
+ * vertices: The body as a rectangle of 4 vertices
+ * horizon_position: turn the body around the Y axis
+ * day_position: turn the body around the Z axis, to place it depending of the time of the day
+ */
{
for (video::S3DVertex &vertex : vertices) {
// Body is directed to -Z (south) by default
@@ -871,15 +803,14 @@ void Sky::place_sky_body(std::array<video::S3DVertex, 4> &vertices,
}
}
-void Sky::setSunTexture(
- std::string sun_texture, std::string sun_tonemap, ITextureSource *tsrc)
+void Sky::setSunTexture(std::string sun_texture,
+ std::string sun_tonemap, ITextureSource *tsrc)
{
// Ignore matching textures (with modifiers) entirely,
// but lets at least update the tonemap before hand.
m_sun_params.tonemap = sun_tonemap;
- m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap)
- ? tsrc->getTexture(m_sun_params.tonemap)
- : NULL;
+ m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
+ tsrc->getTexture(m_sun_params.tonemap) : NULL;
m_materials[3].Lighting = !!m_sun_tonemap;
if (m_sun_params.texture == sun_texture)
@@ -893,45 +824,41 @@ void Sky::setSunTexture(
if (m_sun_texture) {
m_materials[3] = m_materials[0];
m_materials[3].setTexture(0, m_sun_texture);
- m_materials[3].MaterialType =
- video::EMT_TRANSPARENT_ALPHA_CHANNEL;
+ m_materials[3].MaterialType = video::
+ EMT_TRANSPARENT_ALPHA_CHANNEL;
// Disables texture filtering
m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
m_materials[3].setFlag(
- video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
}
} else {
m_sun_texture = nullptr;
}
}
-void Sky::setSunriseTexture(std::string sunglow_texture, ITextureSource *tsrc)
+void Sky::setSunriseTexture(std::string sunglow_texture,
+ ITextureSource* tsrc)
{
// Ignore matching textures (with modifiers) entirely.
if (m_sun_params.sunrise == sunglow_texture)
return;
m_sun_params.sunrise = sunglow_texture;
- m_materials[2].setTexture(
- 0, tsrc->getTextureForMesh(sunglow_texture.empty()
- ? "sunrisebg.png"
- : sunglow_texture));
+ m_materials[2].setTexture(0, tsrc->getTextureForMesh(
+ sunglow_texture.empty() ? "sunrisebg.png" : sunglow_texture)
+ );
}
-void Sky::setMoonTexture(
- std::string moon_texture, std::string moon_tonemap, ITextureSource *tsrc)
+void Sky::setMoonTexture(std::string moon_texture,
+ std::string moon_tonemap, ITextureSource *tsrc)
{
// Ignore matching textures (with modifiers) entirely,
// but lets at least update the tonemap before hand.
m_moon_params.tonemap = moon_tonemap;
- m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap)
- ? tsrc->getTexture(m_moon_params.tonemap)
- : NULL;
+ m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
+ tsrc->getTexture(m_moon_params.tonemap) : NULL;
m_materials[4].Lighting = !!m_moon_tonemap;
if (m_moon_params.texture == moon_texture)
@@ -945,18 +872,15 @@ void Sky::setMoonTexture(
if (m_moon_texture) {
m_materials[4] = m_materials[0];
m_materials[4].setTexture(0, m_moon_texture);
- m_materials[4].MaterialType =
- video::EMT_TRANSPARENT_ALPHA_CHANNEL;
+ m_materials[4].MaterialType = video::
+ EMT_TRANSPARENT_ALPHA_CHANNEL;
// Disables texture filtering
m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
m_materials[4].setFlag(
- video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER,
- false);
+ video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
}
} else {
m_moon_texture = nullptr;
@@ -971,9 +895,11 @@ void Sky::setStarCount(u16 star_count, bool force_update)
m_stars.clear();
// Rebuild the stars surrounding the camera
for (u16 i = 0; i < star_count; i++) {
- v3f star = v3f(myrand_range(-10000, 10000),
- myrand_range(-10000, 10000),
- myrand_range(-10000, 10000));
+ v3f star = v3f(
+ myrand_range(-10000, 10000),
+ myrand_range(-10000, 10000),
+ myrand_range(-10000, 10000)
+ );
star.normalize();
m_stars.emplace_back(star);
@@ -986,8 +912,8 @@ void Sky::setSkyColors(const SkyColor &sky_color)
m_sky_params.sky_color = sky_color;
}
-void Sky::setHorizonTint(
- video::SColor sun_tint, video::SColor moon_tint, std::string use_sun_tint)
+void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint,
+ std::string use_sun_tint)
{
// Change sun and moon tinting:
m_sky_params.fog_sun_tint = sun_tint;
@@ -1001,7 +927,8 @@ void Sky::setHorizonTint(
m_default_tint = true;
}
-void Sky::addTextureToSkybox(std::string texture, int material_id, ITextureSource *tsrc)
+void Sky::addTextureToSkybox(std::string texture, int material_id,
+ ITextureSource *tsrc)
{
// Sanity check for more than six textures.
if (material_id + 5 >= SKY_MATERIAL_COUNT)
@@ -1009,9 +936,9 @@ void Sky::addTextureToSkybox(std::string texture, int material_id, ITextureSourc
// Keep a list of texture names handy.
m_sky_params.textures.emplace_back(texture);
video::ITexture *result = tsrc->getTextureForMesh(texture);
- m_materials[material_id + 5] = m_materials[0];
- m_materials[material_id + 5].setTexture(0, result);
- m_materials[material_id + 5].MaterialType = video::EMT_SOLID;
+ m_materials[material_id+5] = m_materials[0];
+ m_materials[material_id+5].setTexture(0, result);
+ m_materials[material_id+5].MaterialType = video::EMT_SOLID;
}
// To be called once at game init to setup default values.
diff --git a/src/client/sky.h b/src/client/sky.h
index 8983c3775..3227e8f59 100644
--- a/src/client/sky.h
+++ b/src/client/sky.h
@@ -63,29 +63,20 @@ public:
}
void setSunVisible(bool sun_visible) { m_sun_params.visible = sun_visible; }
- void setSunTexture(std::string sun_texture, std::string sun_tonemap,
- ITextureSource *tsrc);
+ void setSunTexture(std::string sun_texture,
+ std::string sun_tonemap, ITextureSource *tsrc);
void setSunScale(f32 sun_scale) { m_sun_params.scale = sun_scale; }
- void setSunriseVisible(bool glow_visible)
- {
- m_sun_params.sunrise_visible = glow_visible;
- }
- void setSunriseTexture(std::string sunglow_texture, ITextureSource *tsrc);
+ void setSunriseVisible(bool glow_visible) { m_sun_params.sunrise_visible = glow_visible; }
+ void setSunriseTexture(std::string sunglow_texture, ITextureSource* tsrc);
void setMoonVisible(bool moon_visible) { m_moon_params.visible = moon_visible; }
- void setMoonTexture(std::string moon_texture, std::string moon_tonemap,
- ITextureSource *tsrc);
+ void setMoonTexture(std::string moon_texture,
+ std::string moon_tonemap, ITextureSource *tsrc);
void setMoonScale(f32 moon_scale) { m_moon_params.scale = moon_scale; }
- void setStarsVisible(bool stars_visible)
- {
- m_star_params.visible = stars_visible;
- }
+ void setStarsVisible(bool stars_visible) { m_star_params.visible = stars_visible; }
void setStarCount(u16 star_count, bool force_update);
- void setStarColor(video::SColor star_color)
- {
- m_star_params.starcolor = star_color;
- }
+ void setStarColor(video::SColor star_color) { m_star_params.starcolor = star_color; }
void setStarScale(f32 star_scale) { m_star_params.scale = star_scale; }
bool getCloudsVisible() const { return m_clouds_visible && m_clouds_enabled; }
@@ -105,12 +96,11 @@ public:
}
void setSkyColors(const SkyColor &sky_color);
void setHorizonTint(video::SColor sun_tint, video::SColor moon_tint,
- std::string use_sun_tint);
+ std::string use_sun_tint);
void setInClouds(bool clouds) { m_in_clouds = clouds; }
void clearSkyboxTextures() { m_sky_params.textures.clear(); }
- void addTextureToSkybox(
- std::string texture, int material_id, ITextureSource *tsrc);
-
+ void addTextureToSkybox(std::string texture, int material_id,
+ ITextureSource *tsrc);
private:
aabb3f m_box;
video::SMaterial m_materials[SKY_MATERIAL_COUNT];
@@ -175,8 +165,11 @@ private:
// pure white: becomes "diffuse light component" for clouds
video::SColorf m_cloudcolor_day_f = video::SColorf(1, 1, 1, 1);
// dawn-factoring version of pure white (note: R is above 1.0)
- video::SColorf m_cloudcolor_dawn_f =
- video::SColorf(255.0f / 240.0f, 223.0f / 240.0f, 191.0f / 255.0f);
+ video::SColorf m_cloudcolor_dawn_f = video::SColorf(
+ 255.0f/240.0f,
+ 223.0f/240.0f,
+ 191.0f/255.0f
+ );
SkyboxParams m_sky_params;
SunParams m_sun_params;
@@ -192,16 +185,14 @@ private:
video::ITexture *m_sun_tonemap;
video::ITexture *m_moon_tonemap;
- void draw_sun(video::IVideoDriver *driver, float sunsize,
- const video::SColor &suncolor, const video::SColor &suncolor2,
- float wicked_time_of_day);
- void draw_moon(video::IVideoDriver *driver, float moonsize,
- const video::SColor &mooncolor, const video::SColor &mooncolor2,
- float wicked_time_of_day);
- void draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1,
- float pos_2, const video::SColor &c);
+ void draw_sun(video::IVideoDriver *driver, float sunsize, const video::SColor &suncolor,
+ const video::SColor &suncolor2, float wicked_time_of_day);
+ void draw_moon(video::IVideoDriver *driver, float moonsize, const video::SColor &mooncolor,
+ const video::SColor &mooncolor2, float wicked_time_of_day);
+ void draw_sky_body(std::array<video::S3DVertex, 4> &vertices,
+ float pos_1, float pos_2, const video::SColor &c);
void draw_stars(video::IVideoDriver *driver, float wicked_time_of_day);
void place_sky_body(std::array<video::S3DVertex, 4> &vertices,
- float horizon_position, float day_position);
+ float horizon_position, float day_position);
void setSkyDefaults();
};
diff --git a/src/client/sound_openal.cpp b/src/client/sound_openal.cpp
index 7cc16d8d7..20a651c1d 100644
--- a/src/client/sound_openal.cpp
+++ b/src/client/sound_openal.cpp
@@ -24,17 +24,17 @@ with this program; ifnot, write to the Free Software Foundation, Inc.,
#include "sound_openal.h"
#if defined(_WIN32)
-#include <al.h>
-#include <alc.h>
-//#include <alext.h>
+ #include <al.h>
+ #include <alc.h>
+ //#include <alext.h>
#elif defined(__APPLE__)
-#include <OpenAL/al.h>
-#include <OpenAL/alc.h>
-//#include <OpenAL/alext.h>
+ #include <OpenAL/al.h>
+ #include <OpenAL/alc.h>
+ //#include <OpenAL/alext.h>
#else
-#include <AL/al.h>
-#include <AL/alc.h>
-#include <AL/alext.h>
+ #include <AL/al.h>
+ #include <AL/alc.h>
+ #include <AL/alext.h>
#endif
#include <cmath>
#include <vorbis/vorbisfile.h>
@@ -52,7 +52,7 @@ with this program; ifnot, write to the Free Software Foundation, Inc.,
std::shared_ptr<SoundManagerSingleton> g_sound_manager_singleton;
typedef std::unique_ptr<ALCdevice, void (*)(ALCdevice *p)> unique_ptr_alcdevice;
-typedef std::unique_ptr<ALCcontext, void (*)(ALCcontext *p)> unique_ptr_alccontext;
+typedef std::unique_ptr<ALCcontext, void(*)(ALCcontext *p)> unique_ptr_alccontext;
static void delete_alcdevice(ALCdevice *p)
{
@@ -90,9 +90,9 @@ static const char *alErrorString(ALenum err)
static ALenum warn_if_error(ALenum err, const char *desc)
{
- if (err == AL_NO_ERROR)
+ if(err == AL_NO_ERROR)
return err;
- warningstream << desc << ": " << alErrorString(err) << std::endl;
+ warningstream<<desc<<": "<<alErrorString(err)<<std::endl;
return err;
}
@@ -111,8 +111,8 @@ struct SoundBuffer
std::vector<char> buffer;
};
-SoundBuffer *load_opened_ogg_file(
- OggVorbis_File *oggFile, const std::string &filename_for_logging)
+SoundBuffer *load_opened_ogg_file(OggVorbis_File *oggFile,
+ const std::string &filename_for_logging)
{
int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
int bitStream;
@@ -126,7 +126,7 @@ SoundBuffer *load_opened_ogg_file(
pInfo = ov_info(oggFile, -1);
// Check the number of channels... always use 16-bit samples
- if (pInfo->channels == 1)
+ if(pInfo->channels == 1)
snd->format = AL_FORMAT_MONO16;
else
snd->format = AL_FORMAT_STEREO16;
@@ -135,14 +135,16 @@ SoundBuffer *load_opened_ogg_file(
snd->freq = pInfo->rate;
// Keep reading until all is read
- do {
+ do
+ {
// Read up to a buffer's worth of decoded sound data
bytes = ov_read(oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
- if (bytes < 0) {
+ if(bytes < 0)
+ {
ov_clear(oggFile);
- infostream << "Audio: Error decoding " << filename_for_logging
- << std::endl;
+ infostream << "Audio: Error decoding "
+ << filename_for_logging << std::endl;
delete snd;
return nullptr;
}
@@ -152,17 +154,18 @@ SoundBuffer *load_opened_ogg_file(
} while (bytes > 0);
alGenBuffers(1, &snd->buffer_id);
- alBufferData(snd->buffer_id, snd->format, &(snd->buffer[0]), snd->buffer.size(),
+ alBufferData(snd->buffer_id, snd->format,
+ &(snd->buffer[0]), snd->buffer.size(),
snd->freq);
ALenum error = alGetError();
- if (error != AL_NO_ERROR) {
+ if(error != AL_NO_ERROR){
infostream << "Audio: OpenAL error: " << alErrorString(error)
- << "preparing sound buffer" << std::endl;
+ << "preparing sound buffer" << std::endl;
}
- // infostream << "Audio file "
+ //infostream << "Audio file "
// << filename_for_logging << " loaded" << std::endl;
// Clean up!
@@ -179,16 +182,15 @@ SoundBuffer *load_ogg_from_file(const std::string &path)
// This requires libvorbis >= 1.3.2, as
// previous versions expect a non-const char *
if (ov_fopen(path.c_str(), &oggFile) != 0) {
- infostream << "Audio: Error opening " << path << " for decoding"
- << std::endl;
+ infostream << "Audio: Error opening " << path
+ << " for decoding" << std::endl;
return nullptr;
}
return load_opened_ogg_file(&oggFile, path);
}
-struct BufferSource
-{
+struct BufferSource {
const char *buf;
size_t cur_offset;
size_t len;
@@ -214,8 +216,8 @@ int buffer_sound_seek_func(void *datasource, ogg_int64_t offset, int whence)
s->cur_offset = offset;
return 0;
} else if (whence == SEEK_CUR) {
- if ((size_t)MYMIN(-offset, 0) > s->cur_offset ||
- s->cur_offset + offset > s->len) {
+ if ((size_t)MYMIN(-offset, 0) > s->cur_offset
+ || s->cur_offset + offset > s->len) {
// offset out of bounds
return -1;
}
@@ -232,8 +234,12 @@ long BufferSourceell_func(void *datasource)
return s->cur_offset;
}
-static ov_callbacks g_buffer_ov_callbacks = {&buffer_sound_read_func,
- &buffer_sound_seek_func, nullptr, &BufferSourceell_func};
+static ov_callbacks g_buffer_ov_callbacks = {
+ &buffer_sound_read_func,
+ &buffer_sound_seek_func,
+ nullptr,
+ &BufferSourceell_func
+};
SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_for_log)
{
@@ -245,8 +251,8 @@ SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_
s.len = buf.size();
if (ov_open_callbacks(&s, &oggFile, nullptr, 0, g_buffer_ov_callbacks) != 0) {
- infostream << "Audio: Error opening " << id_for_log << " for decoding"
- << std::endl;
+ infostream << "Audio: Error opening " << id_for_log
+ << " for decoding" << std::endl;
return nullptr;
}
@@ -262,54 +268,43 @@ struct PlayingSound
class SoundManagerSingleton
{
public:
- unique_ptr_alcdevice m_device;
+ unique_ptr_alcdevice m_device;
unique_ptr_alccontext m_context;
-
public:
SoundManagerSingleton() :
- m_device(nullptr, delete_alcdevice),
- m_context(nullptr, delete_alccontext)
+ m_device(nullptr, delete_alcdevice),
+ m_context(nullptr, delete_alccontext)
{
}
bool init()
{
- if (!(m_device = unique_ptr_alcdevice(
- alcOpenDevice(nullptr), delete_alcdevice))) {
- errorstream << "Audio: Global Initialization: Failed to open "
- "device"
- << std::endl;
+ if (!(m_device = unique_ptr_alcdevice(alcOpenDevice(nullptr), delete_alcdevice))) {
+ errorstream << "Audio: Global Initialization: Failed to open device" << std::endl;
return false;
}
if (!(m_context = unique_ptr_alccontext(
- alcCreateContext(m_device.get(), nullptr),
- delete_alccontext))) {
- errorstream << "Audio: Global Initialization: Failed to create "
- "context"
- << std::endl;
+ alcCreateContext(m_device.get(), nullptr), delete_alccontext))) {
+ errorstream << "Audio: Global Initialization: Failed to create context" << std::endl;
return false;
}
if (!alcMakeContextCurrent(m_context.get())) {
- errorstream << "Audio: Global Initialization: Failed to make "
- "current context"
- << std::endl;
+ errorstream << "Audio: Global Initialization: Failed to make current context" << std::endl;
return false;
}
alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
if (alGetError() != AL_NO_ERROR) {
- errorstream << "Audio: Global Initialization: OpenAL Error "
- << alGetError() << std::endl;
+ errorstream << "Audio: Global Initialization: OpenAL Error " << alGetError() << std::endl;
return false;
}
- infostream << "Audio: Global Initialized: OpenAL "
- << alGetString(AL_VERSION) << ", using "
- << alcGetString(m_device.get(), ALC_DEVICE_SPECIFIER)
- << std::endl;
+ infostream << "Audio: Global Initialized: OpenAL " << alGetString(AL_VERSION)
+ << ", using " << alcGetString(m_device.get(), ALC_DEVICE_SPECIFIER)
+ << std::endl;
return true;
}
@@ -320,24 +315,22 @@ public:
}
};
-class OpenALSoundManager : public ISoundManager
+class OpenALSoundManager: public ISoundManager
{
private:
OnDemandSoundFetcher *m_fetcher;
ALCdevice *m_device;
ALCcontext *m_context;
int m_next_id;
- std::unordered_map<std::string, std::vector<SoundBuffer *>> m_buffers;
- std::unordered_map<int, PlayingSound *> m_sounds_playing;
- struct FadeState
- {
+ std::unordered_map<std::string, std::vector<SoundBuffer*>> m_buffers;
+ std::unordered_map<int, PlayingSound*> m_sounds_playing;
+ struct FadeState {
FadeState() = default;
- FadeState(float step, float current_gain, float target_gain) :
- step(step), current_gain(current_gain),
- target_gain(target_gain)
- {
- }
+ FadeState(float step, float current_gain, float target_gain):
+ step(step),
+ current_gain(current_gain),
+ target_gain(target_gain) {}
float step;
float current_gain;
float target_gain;
@@ -345,11 +338,13 @@ private:
std::unordered_map<int, FadeState> m_sounds_fading;
float m_fade_delay;
-
public:
- OpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher) :
- m_fetcher(fetcher), m_device(smg->m_device.get()),
- m_context(smg->m_context.get()), m_next_id(1), m_fade_delay(0)
+ OpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher):
+ m_fetcher(fetcher),
+ m_device(smg->m_device.get()),
+ m_context(smg->m_context.get()),
+ m_next_id(1),
+ m_fade_delay(0)
{
infostream << "Audio: Initialized: OpenAL " << std::endl;
}
@@ -377,34 +372,37 @@ public:
infostream << "Audio: Deinitialized." << std::endl;
}
- void step(float dtime) { doFades(dtime); }
+ void step(float dtime)
+ {
+ doFades(dtime);
+ }
void addBuffer(const std::string &name, SoundBuffer *buf)
{
- std::unordered_map<std::string, std::vector<SoundBuffer *>>::iterator i =
+ std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i =
m_buffers.find(name);
- if (i != m_buffers.end()) {
+ if(i != m_buffers.end()){
i->second.push_back(buf);
return;
}
- std::vector<SoundBuffer *> bufs;
+ std::vector<SoundBuffer*> bufs;
bufs.push_back(buf);
m_buffers[name] = bufs;
}
- SoundBuffer *getBuffer(const std::string &name)
+ SoundBuffer* getBuffer(const std::string &name)
{
- std::unordered_map<std::string, std::vector<SoundBuffer *>>::iterator i =
+ std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i =
m_buffers.find(name);
- if (i == m_buffers.end())
+ if(i == m_buffers.end())
return nullptr;
- std::vector<SoundBuffer *> &bufs = i->second;
+ std::vector<SoundBuffer*> &bufs = i->second;
int j = myrand() % bufs.size();
return bufs[j];
}
- PlayingSound *createPlayingSound(
- SoundBuffer *buf, bool loop, float volume, float pitch)
+ PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop,
+ float volume, float pitch)
{
infostream << "OpenALSoundManager: Creating playing sound" << std::endl;
assert(buf);
@@ -425,11 +423,11 @@ public:
return sound;
}
- PlayingSound *createPlayingSoundAt(
- SoundBuffer *buf, bool loop, float volume, v3f pos, float pitch)
+ PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop,
+ float volume, v3f pos, float pitch)
{
infostream << "OpenALSoundManager: Creating positional playing sound"
- << std::endl;
+ << std::endl;
assert(buf);
PlayingSound *sound = new PlayingSound;
assert(sound);
@@ -458,7 +456,7 @@ public:
{
assert(buf);
PlayingSound *sound = createPlayingSound(buf, loop, volume, pitch);
- if (!sound)
+ if(!sound)
return -1;
int id = m_next_id++;
m_sounds_playing[id] = sound;
@@ -470,7 +468,7 @@ public:
{
assert(buf);
PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch);
- if (!sound)
+ if(!sound)
return -1;
int id = m_next_id++;
m_sounds_playing[id] = sound;
@@ -479,9 +477,8 @@ public:
void deleteSound(int id)
{
- std::unordered_map<int, PlayingSound *>::iterator i =
- m_sounds_playing.find(id);
- if (i == m_sounds_playing.end())
+ std::unordered_map<int, PlayingSound*>::iterator i = m_sounds_playing.find(id);
+ if(i == m_sounds_playing.end())
return;
PlayingSound *sound = i->second;
@@ -492,12 +489,12 @@ public:
}
/* If buffer does not exist, consult the fetcher */
- SoundBuffer *getFetchBuffer(const std::string &name)
+ SoundBuffer* getFetchBuffer(const std::string &name)
{
SoundBuffer *buf = getBuffer(name);
- if (buf)
+ if(buf)
return buf;
- if (!m_fetcher)
+ if(!m_fetcher)
return nullptr;
std::set<std::string> paths;
std::set<std::string> datas;
@@ -516,9 +513,8 @@ public:
{
if (!m_sounds_playing.empty()) {
verbosestream << "OpenALSoundManager::maintain(): "
- << m_sounds_playing.size() << " playing sounds, "
- << m_buffers.size() << " sound names loaded"
- << std::endl;
+ << m_sounds_playing.size() <<" playing sounds, "
+ << m_buffers.size() <<" sound names loaded"<<std::endl;
}
std::unordered_set<int> del_list;
for (const auto &sp : m_sounds_playing) {
@@ -528,15 +524,14 @@ public:
{
ALint state;
alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state);
- if (state != AL_PLAYING) {
+ if(state != AL_PLAYING){
del_list.insert(id);
}
}
}
- if (!del_list.empty())
- verbosestream << "OpenALSoundManager::maintain(): deleting "
- << del_list.size() << " playing sounds"
- << std::endl;
+ if(!del_list.empty())
+ verbosestream<<"OpenALSoundManager::maintain(): deleting "
+ <<del_list.size()<<" playing sounds"<<std::endl;
for (int i : del_list) {
deleteSound(i);
}
@@ -544,7 +539,8 @@ public:
/* Interface */
- bool loadSoundFile(const std::string &name, const std::string &filepath)
+ bool loadSoundFile(const std::string &name,
+ const std::string &filepath)
{
SoundBuffer *buf = load_ogg_from_file(filepath);
if (buf)
@@ -552,7 +548,8 @@ public:
return !!buf;
}
- bool loadSoundData(const std::string &name, const std::string &filedata)
+ bool loadSoundData(const std::string &name,
+ const std::string &filedata)
{
SoundBuffer *buf = load_ogg_from_buffer(filedata, name);
if (buf)
@@ -566,23 +563,25 @@ public:
alListener3f(AL_VELOCITY, vel.X, vel.Y, vel.Z);
ALfloat f[6];
f3_set(f, at);
- f3_set(f + 3, -up);
+ f3_set(f+3, -up);
alListenerfv(AL_ORIENTATION, f);
warn_if_error(alGetError(), "updateListener");
}
- void setListenerGain(float gain) { alListenerf(AL_GAIN, gain); }
+ void setListenerGain(float gain)
+ {
+ alListenerf(AL_GAIN, gain);
+ }
- int playSound(const std::string &name, bool loop, float volume, float fade,
- float pitch)
+ int playSound(const std::string &name, bool loop, float volume, float fade, float pitch)
{
maintain();
if (name.empty())
return 0;
SoundBuffer *buf = getFetchBuffer(name);
- if (!buf) {
+ if(!buf){
infostream << "OpenALSoundManager: \"" << name << "\" not found."
- << std::endl;
+ << std::endl;
return -1;
}
int handle = -1;
@@ -595,16 +594,15 @@ public:
return handle;
}
- int playSoundAt(const std::string &name, bool loop, float volume, v3f pos,
- float pitch)
+ int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch)
{
maintain();
if (name.empty())
return 0;
SoundBuffer *buf = getFetchBuffer(name);
- if (!buf) {
+ if(!buf){
infostream << "OpenALSoundManager: \"" << name << "\" not found."
- << std::endl;
+ << std::endl;
return -1;
}
return playSoundRawAt(buf, loop, volume, pos, pitch);
@@ -629,7 +627,8 @@ public:
return;
float chkGain = 0;
- for (auto i = m_sounds_fading.begin(); i != m_sounds_fading.end();) {
+ for (auto i = m_sounds_fading.begin();
+ i != m_sounds_fading.end();) {
if (i->second.step < 0.f)
chkGain = -(i->second.current_gain);
else
@@ -637,8 +636,7 @@ public:
if (chkGain < i->second.target_gain) {
i->second.current_gain += (i->second.step * m_fade_delay);
- i->second.current_gain =
- rangelim(i->second.current_gain, 0, 1);
+ i->second.current_gain = rangelim(i->second.current_gain, 0, 1);
updateSoundGain(i->first, i->second.current_gain);
++i;
@@ -704,8 +702,7 @@ std::shared_ptr<SoundManagerSingleton> createSoundManagerSingleton()
return smg;
}
-ISoundManager *createOpenALSoundManager(
- SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher)
+ISoundManager *createOpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher)
{
return new OpenALSoundManager(smg, fetcher);
};
diff --git a/src/client/tile.cpp b/src/client/tile.cpp
index dd159e909..d03588b2b 100644
--- a/src/client/tile.cpp
+++ b/src/client/tile.cpp
@@ -34,6 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "guiscalingfilter.h"
#include "renderingengine.h"
+
#if ENABLE_GLES
#ifdef _IRR_COMPILE_WITH_OGLES1_
#include <GLES/gl.h>
@@ -61,8 +62,10 @@ static bool replace_ext(std::string &path, const char *ext)
return false;
// Find place of last dot, fail if \ or / found.
s32 last_dot_i = -1;
- for (s32 i = path.size() - 1; i >= 0; i--) {
- if (path[i] == '.') {
+ for (s32 i=path.size()-1; i>=0; i--)
+ {
+ if (path[i] == '.')
+ {
last_dot_i = i;
break;
}
@@ -74,7 +77,7 @@ static bool replace_ext(std::string &path, const char *ext)
if (last_dot_i == -1)
return false;
// Else make the new path
- path = path.substr(0, last_dot_i + 1) + ext;
+ path = path.substr(0, last_dot_i+1) + ext;
return true;
}
@@ -87,20 +90,24 @@ static bool replace_ext(std::string &path, const char *ext)
std::string getImagePath(std::string path)
{
// A NULL-ended list of possible image extensions
- const char *extensions[] = {"png", "jpg", "bmp", "tga", "pcx", "ppm", "psd",
- "wal", "rgb", NULL};
+ const char *extensions[] = {
+ "png", "jpg", "bmp", "tga",
+ "pcx", "ppm", "psd", "wal", "rgb",
+ NULL
+ };
// If there is no extension, add one
if (removeStringEnd(path, extensions).empty())
path = path + ".png";
// Check paths until something is found to exist
const char **ext = extensions;
- do {
+ do{
bool r = replace_ext(path, *ext);
if (!r)
return "";
if (fs::PathExists(path))
return path;
- } while ((++ext) != NULL);
+ }
+ while((++ext) != NULL);
return "";
}
@@ -145,9 +152,10 @@ std::string getTexturePath(const std::string &filename, bool *is_base_pack)
/*
Check from default data directory
*/
- if (fullpath.empty()) {
- std::string base_path = porting::path_share + DIR_DELIM + "textures" +
- DIR_DELIM + "base" + DIR_DELIM + "pack";
+ if (fullpath.empty())
+ {
+ std::string base_path = porting::path_share + DIR_DELIM + "textures"
+ + DIR_DELIM + "base" + DIR_DELIM + "pack";
std::string testpath = base_path + DIR_DELIM + filename;
// Check all filename extensions. Returns "" if not found.
fullpath = getImagePath(testpath);
@@ -176,8 +184,12 @@ struct TextureInfo
std::string name;
video::ITexture *texture;
- TextureInfo(const std::string &name_, video::ITexture *texture_ = NULL) :
- name(name_), texture(texture_)
+ TextureInfo(
+ const std::string &name_,
+ video::ITexture *texture_=NULL
+ ):
+ name(name_),
+ texture(texture_)
{
}
};
@@ -189,8 +201,7 @@ struct TextureInfo
class SourceImageCache
{
public:
- ~SourceImageCache()
- {
+ ~SourceImageCache() {
for (auto &m_image : m_images) {
m_image.second->drop();
}
@@ -200,14 +211,14 @@ public:
{
assert(img); // Pre-condition
// Remove old image
- std::map<std::string, video::IImage *>::iterator n;
+ std::map<std::string, video::IImage*>::iterator n;
n = m_images.find(name);
- if (n != m_images.end()) {
+ if (n != m_images.end()){
if (n->second)
n->second->drop();
}
- video::IImage *toadd = img;
+ video::IImage* toadd = img;
bool need_to_grab = true;
// Try to use local texture instead if asked to
@@ -216,11 +227,9 @@ public:
std::string path = getTexturePath(name, &is_base_pack);
// Ignore base pack
if (!path.empty() && !is_base_pack) {
- video::IImage *img2 =
- RenderingEngine::get_video_driver()
- ->createImageFromFile(
- path.c_str());
- if (img2) {
+ video::IImage *img2 = RenderingEngine::get_video_driver()->
+ createImageFromFile(path.c_str());
+ if (img2){
toadd = img2;
need_to_grab = false;
}
@@ -231,9 +240,9 @@ public:
toadd->grab();
m_images[name] = toadd;
}
- video::IImage *get(const std::string &name)
+ video::IImage* get(const std::string &name)
{
- std::map<std::string, video::IImage *>::iterator n;
+ std::map<std::string, video::IImage*>::iterator n;
n = m_images.find(name);
if (n != m_images.end())
return n->second;
@@ -242,33 +251,31 @@ public:
// Primarily fetches from cache, secondarily tries to read from filesystem
video::IImage *getOrLoad(const std::string &name)
{
- std::map<std::string, video::IImage *>::iterator n;
+ std::map<std::string, video::IImage*>::iterator n;
n = m_images.find(name);
- if (n != m_images.end()) {
+ if (n != m_images.end()){
n->second->grab(); // Grab for caller
return n->second;
}
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
std::string path = getTexturePath(name);
if (path.empty()) {
- infostream << "SourceImageCache::getOrLoad(): No path found for "
- "\""
- << name << "\"" << std::endl;
+ infostream<<"SourceImageCache::getOrLoad(): No path found for \""
+ <<name<<"\""<<std::endl;
return NULL;
}
- infostream << "SourceImageCache::getOrLoad(): Loading path \"" << path
- << "\"" << std::endl;
+ infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path
+ <<"\""<<std::endl;
video::IImage *img = driver->createImageFromFile(path.c_str());
- if (img) {
+ if (img){
m_images[name] = img;
img->grab(); // Grab for caller
}
return img;
}
-
private:
- std::map<std::string, video::IImage *> m_images;
+ std::map<std::string, video::IImage*> m_images;
};
/*
@@ -333,9 +340,9 @@ public:
and not found in cache, the call is queued to the main thread
for processing.
*/
- video::ITexture *getTexture(u32 id);
+ video::ITexture* getTexture(u32 id);
- video::ITexture *getTexture(const std::string &name, u32 *id = NULL);
+ video::ITexture* getTexture(const std::string &name, u32 *id = NULL);
/*
Get a texture specifically intended for mesh
@@ -343,9 +350,9 @@ public:
use. This texture may be a different size and may
have had additional filters applied.
*/
- video::ITexture *getTextureForMesh(const std::string &name, u32 *id);
+ video::ITexture* getTextureForMesh(const std::string &name, u32 *id);
- virtual Palette *getPalette(const std::string &name);
+ virtual Palette* getPalette(const std::string &name);
bool isKnownSourceImage(const std::string &name)
{
@@ -371,11 +378,12 @@ public:
// Shall be called from the main thread.
void rebuildImagesAndTextures();
- video::ITexture *getNormalTexture(const std::string &name);
+ video::ITexture* getNormalTexture(const std::string &name);
video::SColor getTextureAverageColor(const std::string &name);
video::ITexture *getShaderFlagsTexture(bool normamap_present);
private:
+
// The id of the thread that is allowed to use irrlicht directly
std::thread::id m_main_thread;
@@ -388,14 +396,14 @@ private:
// Generate image based on a string like "stone.png" or "[crack:1:0".
// if baseimg is NULL, it is created. Otherwise stuff is made on it.
- bool generateImagePart(std::string part_of_name, video::IImage *&baseimg);
+ bool generateImagePart(std::string part_of_name, video::IImage *& baseimg);
/*! Generates an image from a full string like
* "stone.png^mineral_coal.png^[crack:1:0".
* Shall be called from the main thread.
* The returned Image should be dropped.
*/
- video::IImage *generateImage(const std::string &name);
+ video::IImage* generateImage(const std::string &name);
// Thread-safe cache of what source images are known (true = known)
MutexedMap<std::string, bool> m_source_image_existence;
@@ -413,7 +421,7 @@ private:
// Textures that have been overwritten with other ones
// but can't be deleted because the ITexture* might still be used
- std::vector<video::ITexture *> m_texture_trash;
+ std::vector<video::ITexture*> m_texture_trash;
// Maps image file names to loaded palettes.
std::unordered_map<std::string, Palette> m_palettes;
@@ -452,24 +460,24 @@ TextureSource::~TextureSource()
unsigned int textures_before = driver->getTextureCount();
for (const auto &iter : m_textureinfo_cache) {
- // cleanup texture
+ //cleanup texture
if (iter.texture)
driver->removeTexture(iter.texture);
}
m_textureinfo_cache.clear();
for (auto t : m_texture_trash) {
- // cleanup trashed texture
+ //cleanup trashed texture
driver->removeTexture(t);
}
- infostream << "~TextureSource() before cleanup: " << textures_before
- << " after: " << driver->getTextureCount() << std::endl;
+ infostream << "~TextureSource() before cleanup: "<< textures_before
+ << " after: " << driver->getTextureCount() << std::endl;
}
u32 TextureSource::getTextureId(const std::string &name)
{
- // infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;
+ //infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;
{
/*
@@ -478,7 +486,8 @@ u32 TextureSource::getTextureId(const std::string &name)
MutexAutoLock lock(m_textureinfo_cache_mutex);
std::map<std::string, u32>::iterator n;
n = m_name_to_id.find(name);
- if (n != m_name_to_id.end()) {
+ if (n != m_name_to_id.end())
+ {
return n->second;
}
}
@@ -490,7 +499,8 @@ u32 TextureSource::getTextureId(const std::string &name)
return generateTexture(name);
}
- infostream << "getTextureId(): Queued: name=\"" << name << "\"" << std::endl;
+
+ infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
// We're gonna ask the result to be put into here
static ResultQueue<std::string, u32, u8, u8> result_queue;
@@ -499,18 +509,17 @@ u32 TextureSource::getTextureId(const std::string &name)
m_get_texture_queue.add(name, 0, 0, &result_queue);
try {
- while (true) {
+ while(true) {
// Wait result for a second
- GetResult<std::string, u32, u8, u8> result =
- result_queue.pop_front(1000);
+ GetResult<std::string, u32, u8, u8>
+ result = result_queue.pop_front(1000);
if (result.key == name) {
return result.item;
}
}
- } catch (ItemNotFoundException &e) {
- errorstream << "Waiting for texture " << name << " timed out."
- << std::endl;
+ } catch(ItemNotFoundException &e) {
+ errorstream << "Waiting for texture " << name << " timed out." << std::endl;
return 0;
}
@@ -521,13 +530,13 @@ u32 TextureSource::getTextureId(const std::string &name)
// Draw an image on top of an another one, using the alpha channel of the
// source image
-static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos,
- v2s32 dst_pos, v2u32 size);
+static void blit_with_alpha(video::IImage *src, video::IImage *dst,
+ v2s32 src_pos, v2s32 dst_pos, v2u32 size);
// Like blit_with_alpha, but only modifies destination pixels that
// are fully opaque
-static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos,
- v2s32 dst_pos, v2u32 size);
+static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
+ v2s32 src_pos, v2s32 dst_pos, v2u32 size);
// Apply a color to an image. Uses an int (0-255) to calculate the ratio.
// If the ratio is 255 or -1 and keep_alpha is true, then it multiples the
@@ -541,18 +550,18 @@ static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
const video::SColor &color);
// Apply a mask to an image
-static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos,
- v2s32 dst_pos, v2u32 size);
+static void apply_mask(video::IImage *mask, video::IImage *dst,
+ v2s32 mask_pos, v2s32 dst_pos, v2u32 size);
// Draw or overlay a crack
-static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay,
- s32 frame_count, s32 progression, video::IVideoDriver *driver,
- u8 tiles = 1);
+static void draw_crack(video::IImage *crack, video::IImage *dst,
+ bool use_overlay, s32 frame_count, s32 progression,
+ video::IVideoDriver *driver, u8 tiles = 1);
// Brighten image
void brighten(video::IImage *image);
// Parse a transform name
-u32 parseImageTransform(const std::string &s);
+u32 parseImageTransform(const std::string& s);
// Apply transform to image dimension
core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim);
// Apply transform to image data
@@ -563,11 +572,11 @@ void imageTransform(u32 transform, video::IImage *src, video::IImage *dst);
*/
u32 TextureSource::generateTexture(const std::string &name)
{
- // infostream << "generateTexture(): name=\"" << name << "\"" << std::endl;
+ //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl;
// Empty name means texture 0
if (name.empty()) {
- infostream << "generateTexture(): name is empty" << std::endl;
+ infostream<<"generateTexture(): name is empty"<<std::endl;
return 0;
}
@@ -587,9 +596,8 @@ u32 TextureSource::generateTexture(const std::string &name)
Calling only allowed from main thread
*/
if (std::this_thread::get_id() != m_main_thread) {
- errorstream << "TextureSource::generateTexture() "
- "called not from main thread"
- << std::endl;
+ errorstream<<"TextureSource::generateTexture() "
+ "called not from main thread"<<std::endl;
return 0;
}
@@ -628,17 +636,18 @@ std::string TextureSource::getTextureName(u32 id)
{
MutexAutoLock lock(m_textureinfo_cache_mutex);
- if (id >= m_textureinfo_cache.size()) {
- errorstream << "TextureSource::getTextureName(): id=" << id
- << " >= m_textureinfo_cache.size()="
- << m_textureinfo_cache.size() << std::endl;
+ if (id >= m_textureinfo_cache.size())
+ {
+ errorstream<<"TextureSource::getTextureName(): id="<<id
+ <<" >= m_textureinfo_cache.size()="
+ <<m_textureinfo_cache.size()<<std::endl;
return "";
}
return m_textureinfo_cache[id].name;
}
-video::ITexture *TextureSource::getTexture(u32 id)
+video::ITexture* TextureSource::getTexture(u32 id)
{
MutexAutoLock lock(m_textureinfo_cache_mutex);
@@ -648,28 +657,28 @@ video::ITexture *TextureSource::getTexture(u32 id)
return m_textureinfo_cache[id].texture;
}
-video::ITexture *TextureSource::getTexture(const std::string &name, u32 *id)
+video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id)
{
u32 actual_id = getTextureId(name);
- if (id) {
+ if (id){
*id = actual_id;
}
return getTexture(actual_id);
}
-video::ITexture *TextureSource::getTextureForMesh(const std::string &name, u32 *id)
+video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id)
{
static thread_local bool filter_needed =
- g_settings->getBool("texture_clean_transparent") ||
- ((m_setting_trilinear_filter || m_setting_bilinear_filter) &&
- g_settings->getS32("texture_min_size") > 1);
+ g_settings->getBool("texture_clean_transparent") ||
+ ((m_setting_trilinear_filter || m_setting_bilinear_filter) &&
+ g_settings->getS32("texture_min_size") > 1);
// Avoid duplicating texture if it won't actually change
if (filter_needed)
return getTexture(name + "^[applyfiltersformesh", id);
return getTexture(name, id);
}
-Palette *TextureSource::getPalette(const std::string &name)
+Palette* TextureSource::getPalette(const std::string &name)
{
// Only the main thread may load images
sanity_check(std::this_thread::get_id() == m_main_thread);
@@ -683,7 +692,7 @@ Palette *TextureSource::getPalette(const std::string &name)
video::IImage *img = generateImage(name);
if (!img) {
warningstream << "TextureSource::getPalette(): palette \"" << name
- << "\" could not be loaded." << std::endl;
+ << "\" could not be loaded." << std::endl;
return NULL;
}
Palette new_palette;
@@ -695,15 +704,13 @@ Palette *TextureSource::getPalette(const std::string &name)
return NULL;
if (area > 256) {
warningstream << "TextureSource::getPalette(): the specified"
- << " palette image \"" << name
- << "\" is larger than 256"
- << " pixels, using the first 256." << std::endl;
+ << " palette image \"" << name << "\" is larger than 256"
+ << " pixels, using the first 256." << std::endl;
area = 256;
} else if (256 % area != 0)
warningstream << "TextureSource::getPalette(): the "
- << "specified palette image \"" << name
- << "\" does not "
- << "contain power of two pixels." << std::endl;
+ << "specified palette image \"" << name << "\" does not "
+ << "contain power of two pixels." << std::endl;
// We stretch the palette so it will fit 256 values
// This many param2 values will have the same color
u32 step = 256 / area;
@@ -731,9 +738,11 @@ void TextureSource::processQueue()
/*
Fetch textures
*/
- // NOTE this is only thread safe for ONE consumer thread!
- if (!m_get_texture_queue.empty()) {
- GetRequest<std::string, u32, u8, u8> request = m_get_texture_queue.pop();
+ //NOTE this is only thread safe for ONE consumer thread!
+ if (!m_get_texture_queue.empty())
+ {
+ GetRequest<std::string, u32, u8, u8>
+ request = m_get_texture_queue.pop();
/*infostream<<"TextureSource::processQueue(): "
<<"got texture request with "
@@ -746,7 +755,7 @@ void TextureSource::processQueue()
void TextureSource::insertSourceImage(const std::string &name, video::IImage *img)
{
- // infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
+ //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
sanity_check(std::this_thread::get_id() == m_main_thread);
@@ -762,7 +771,7 @@ void TextureSource::rebuildImagesAndTextures()
sanity_check(driver);
infostream << "TextureSource: recreating " << m_textureinfo_cache.size()
- << " textures" << std::endl;
+ << " textures" << std::endl;
// Recreate textures
for (TextureInfo &ti : m_textureinfo_cache) {
@@ -795,19 +804,16 @@ inline static void applyShadeFactor(video::SColor &color, u32 factor)
}
static video::IImage *createInventoryCubeImage(
- video::IImage *top, video::IImage *left, video::IImage *right)
+ video::IImage *top, video::IImage *left, video::IImage *right)
{
core::dimension2du size_top = top->getDimension();
core::dimension2du size_left = left->getDimension();
core::dimension2du size_right = right->getDimension();
u32 size = npot2(std::max({
- size_top.Width,
- size_top.Height,
- size_left.Width,
- size_left.Height,
- size_right.Width,
- size_right.Height,
+ size_top.Width, size_top.Height,
+ size_left.Width, size_left.Height,
+ size_right.Width, size_right.Height,
}));
// It must be divisible by 4, to let everything work correctly.
@@ -822,14 +828,12 @@ static video::IImage *createInventoryCubeImage(
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
- auto lock_image = [size, driver](video::IImage *&image) -> const u32 * {
+ auto lock_image = [size, driver] (video::IImage *&image) -> const u32 * {
image->grab();
core::dimension2du dim = image->getDimension();
video::ECOLOR_FORMAT format = image->getColorFormat();
- if (dim.Width != size || dim.Height != size ||
- format != video::ECF_A8R8G8B8) {
- video::IImage *scaled = driver->createImage(
- video::ECF_A8R8G8B8, {size, size});
+ if (dim.Width != size || dim.Height != size || format != video::ECF_A8R8G8B8) {
+ video::IImage *scaled = driver->createImage(video::ECF_A8R8G8B8, {size, size});
image->copyToScaling(scaled);
image->drop();
image = scaled;
@@ -837,13 +841,12 @@ static video::IImage *createInventoryCubeImage(
sanity_check(image->getPitch() == 4 * size);
return reinterpret_cast<u32 *>(image->lock());
};
- auto free_image = [](video::IImage *image) -> void {
+ auto free_image = [] (video::IImage *image) -> void {
image->unlock();
image->drop();
};
- video::IImage *result =
- driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size});
+ video::IImage *result = driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size});
sanity_check(result->getPitch() == 4 * cube_size);
result->fill(video::SColor(0x00000000u));
u32 *target = reinterpret_cast<u32 *>(result->lock());
@@ -852,9 +855,10 @@ static video::IImage *createInventoryCubeImage(
// `shade_factor` is face brightness, in range [0.0, 1.0]
// (xu, xv, x1; yu, yv, y1) form coordinate transformation matrix
// `offsets` list pixels to be drawn for single source pixel
- auto draw_image = [=](video::IImage *image, float shade_factor, s16 xu, s16 xv,
- s16 x1, s16 yu, s16 yv, s16 y1,
- std::initializer_list<v2s16> offsets) -> void {
+ auto draw_image = [=] (video::IImage *image, float shade_factor,
+ s16 xu, s16 xv, s16 x1,
+ s16 yu, s16 yv, s16 y1,
+ std::initializer_list<v2s16> offsets) -> void {
u32 brightness = core::clamp<u32>(256 * shade_factor, 0, 256);
const u32 *source = lock_image(image);
for (u16 v = 0; v < size; v++) {
@@ -864,87 +868,51 @@ static video::IImage *createInventoryCubeImage(
s16 x = xu * u + xv * v + x1;
s16 y = yu * u + yv * v + y1;
for (const auto &off : offsets)
- target[(y + off.Y) * cube_size + (x + off.X) +
- offset] = pixel.color;
+ target[(y + off.Y) * cube_size + (x + off.X) + offset] = pixel.color;
source++;
}
}
free_image(image);
};
- draw_image(top, 1.000000f, 4, -4, 4 * (size - 1), 2, 2, 0,
+ draw_image(top, 1.000000f,
+ 4, -4, 4 * (size - 1),
+ 2, 2, 0,
{
- {2, 0},
- {3, 0},
- {4, 0},
- {5, 0},
- {0, 1},
- {1, 1},
- {2, 1},
- {3, 1},
- {4, 1},
- {5, 1},
- {6, 1},
- {7, 1},
- {2, 2},
- {3, 2},
- {4, 2},
- {5, 2},
+ {2, 0}, {3, 0}, {4, 0}, {5, 0},
+ {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1},
+ {2, 2}, {3, 2}, {4, 2}, {5, 2},
});
- draw_image(left, 0.836660f, 4, 0, 0, 2, 5, 2 * size,
+ draw_image(left, 0.836660f,
+ 4, 0, 0,
+ 2, 5, 2 * size,
{
- {0, 0},
- {1, 0},
- {0, 1},
- {1, 1},
- {2, 1},
- {3, 1},
- {0, 2},
- {1, 2},
- {2, 2},
- {3, 2},
- {0, 3},
- {1, 3},
- {2, 3},
- {3, 3},
- {0, 4},
- {1, 4},
- {2, 4},
- {3, 4},
- {2, 5},
- {3, 5},
+ {0, 0}, {1, 0},
+ {0, 1}, {1, 1}, {2, 1}, {3, 1},
+ {0, 2}, {1, 2}, {2, 2}, {3, 2},
+ {0, 3}, {1, 3}, {2, 3}, {3, 3},
+ {0, 4}, {1, 4}, {2, 4}, {3, 4},
+ {2, 5}, {3, 5},
});
- draw_image(right, 0.670820f, 4, 0, 4 * size, -2, 5, 4 * size - 2,
+ draw_image(right, 0.670820f,
+ 4, 0, 4 * size,
+ -2, 5, 4 * size - 2,
{
- {2, 0},
- {3, 0},
- {0, 1},
- {1, 1},
- {2, 1},
- {3, 1},
- {0, 2},
- {1, 2},
- {2, 2},
- {3, 2},
- {0, 3},
- {1, 3},
- {2, 3},
- {3, 3},
- {0, 4},
- {1, 4},
- {2, 4},
- {3, 4},
- {0, 5},
- {1, 5},
+ {2, 0}, {3, 0},
+ {0, 1}, {1, 1}, {2, 1}, {3, 1},
+ {0, 2}, {1, 2}, {2, 2}, {3, 2},
+ {0, 3}, {1, 3}, {2, 3}, {3, 3},
+ {0, 4}, {1, 4}, {2, 4}, {3, 4},
+ {0, 5}, {1, 5},
});
result->unlock();
return result;
}
-video::IImage *TextureSource::generateImage(const std::string &name)
+video::IImage* TextureSource::generateImage(const std::string &name)
{
// Get the base image
@@ -957,7 +925,7 @@ video::IImage *TextureSource::generateImage(const std::string &name)
s32 last_separator_pos = -1;
u8 paren_bal = 0;
for (s32 i = name.size() - 1; i >= 0; i--) {
- if (i > 0 && name[i - 1] == escape)
+ if (i > 0 && name[i-1] == escape)
continue;
switch (name[i]) {
case separator:
@@ -969,9 +937,8 @@ video::IImage *TextureSource::generateImage(const std::string &name)
case paren_open:
if (paren_bal == 0) {
errorstream << "generateImage(): unbalanced parentheses"
- << "(extranous '(') while generating texture "
- "\""
- << name << "\"" << std::endl;
+ << "(extranous '(') while generating texture \""
+ << name << "\"" << std::endl;
return NULL;
}
paren_bal--;
@@ -985,11 +952,12 @@ video::IImage *TextureSource::generateImage(const std::string &name)
}
if (paren_bal > 0) {
errorstream << "generateImage(): unbalanced parentheses"
- << "(missing matching '(') while generating texture \""
- << name << "\"" << std::endl;
+ << "(missing matching '(') while generating texture \""
+ << name << "\"" << std::endl;
return NULL;
}
+
video::IImage *baseimg = NULL;
/*
@@ -1011,15 +979,15 @@ video::IImage *TextureSource::generateImage(const std::string &name)
If this name is enclosed in parentheses, generate it
and blit it onto the base image
*/
- if (last_part_of_name[0] == paren_open &&
- last_part_of_name[last_part_of_name.size() - 1] == paren_close) {
- std::string name2 =
- last_part_of_name.substr(1, last_part_of_name.size() - 2);
+ if (last_part_of_name[0] == paren_open
+ && last_part_of_name[last_part_of_name.size() - 1] == paren_close) {
+ std::string name2 = last_part_of_name.substr(1,
+ last_part_of_name.size() - 2);
video::IImage *tmp = generateImage(name2);
if (!tmp) {
errorstream << "generateImage(): "
- "Failed to generate \""
- << name2 << "\"" << std::endl;
+ "Failed to generate \"" << name2 << "\""
+ << std::endl;
return NULL;
}
core::dimension2d<u32> dim = tmp->getDimension();
@@ -1032,15 +1000,14 @@ video::IImage *TextureSource::generateImage(const std::string &name)
} else if (!generateImagePart(last_part_of_name, baseimg)) {
// Generate image according to part of name
errorstream << "generateImage(): "
- "Failed to generate \""
- << last_part_of_name << "\"" << std::endl;
+ "Failed to generate \"" << last_part_of_name << "\""
+ << std::endl;
}
// If no resulting image, print a warning
if (baseimg == NULL) {
errorstream << "generateImage(): baseimg is NULL (attempted to"
- " create texture \""
- << name << "\")" << std::endl;
+ " create texture \"" << name << "\")" << std::endl;
}
return baseimg;
@@ -1048,10 +1015,11 @@ video::IImage *TextureSource::generateImage(const std::string &name)
#if ENABLE_GLES
+
static inline u16 get_GL_major_version()
{
const GLubyte *gl_version = glGetString(GL_VERSION);
- return (u16)(gl_version[0] - '0');
+ return (u16) (gl_version[0] - '0');
}
/**
@@ -1063,9 +1031,9 @@ bool hasNPotSupport()
{
// Only GLES2 is trusted to correctly report npot support
// Note: we cache the boolean result, the GL context will never change.
- static const bool supported =
- get_GL_major_version() > 1 && glGetString(GL_EXTENSIONS) &&
- strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot");
+ static const bool supported = get_GL_major_version() > 1 &&
+ glGetString(GL_EXTENSIONS) &&
+ strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot");
return supported;
}
@@ -1076,7 +1044,8 @@ bool hasNPotSupport()
* @return image or copy of image aligned to npot2
*/
-video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver)
+video::IImage * Align2Npot2(video::IImage * image,
+ video::IVideoDriver* driver)
{
if (image == NULL)
return image;
@@ -1086,7 +1055,7 @@ video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver)
core::dimension2d<u32> dim = image->getDimension();
unsigned int height = npot2(dim.Height);
- unsigned int width = npot2(dim.Width);
+ unsigned int width = npot2(dim.Width);
if (dim.Height == height && dim.Width == width)
return image;
@@ -1096,8 +1065,9 @@ video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver)
if (dim.Width > width)
width *= 2;
- video::IImage *targetimage = driver->createImage(
- video::ECF_A8R8G8B8, core::dimension2d<u32>(width, height));
+ video::IImage *targetimage =
+ driver->createImage(video::ECF_A8R8G8B8,
+ core::dimension2d<u32>(width, height));
if (targetimage != NULL)
image->copyToScaling(targetimage);
@@ -1124,7 +1094,8 @@ static std::string unescape_string(const std::string &str, const char esc = '\\'
return out;
}
-bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&baseimg)
+bool TextureSource::generateImagePart(std::string part_of_name,
+ video::IImage *& baseimg)
{
const char escape = '\\'; // same as in generateImage()
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
@@ -1140,34 +1111,28 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (!part_of_name.empty()) {
// Do not create normalmap dummies
- if (part_of_name.find("_normal.png") !=
- std::string::npos) {
- warningstream << "generateImage(): Could not "
- "load normal map \""
- << part_of_name << "\""
- << std::endl;
+ if (part_of_name.find("_normal.png") != std::string::npos) {
+ warningstream << "generateImage(): Could not load normal map \""
+ << part_of_name << "\"" << std::endl;
return true;
}
errorstream << "generateImage(): Could not load image \""
- << part_of_name
- << "\" while building texture; "
- "Creating a dummy image"
- << std::endl;
+ << part_of_name << "\" while building texture; "
+ "Creating a dummy image" << std::endl;
}
// Just create a dummy image
- // core::dimension2d<u32> dim(2,2);
- core::dimension2d<u32> dim(1, 1);
+ //core::dimension2d<u32> dim(2,2);
+ core::dimension2d<u32> dim(1,1);
image = driver->createImage(video::ECF_A8R8G8B8, dim);
sanity_check(image != NULL);
/*image->setPixel(0,0, video::SColor(255,255,0,0));
image->setPixel(1,0, video::SColor(255,0,255,0));
image->setPixel(0,1, video::SColor(255,0,0,255));
image->setPixel(1,1, video::SColor(255,255,0,255));*/
- image->setPixel(0, 0,
- video::SColor(255, myrand() % 256, myrand() % 256,
- myrand() % 256));
+ image->setPixel(0,0, video::SColor(255,myrand()%256,
+ myrand()%256,myrand()%256));
/*image->setPixel(1,0, video::SColor(255,myrand()%256,
myrand()%256,myrand()%256));
image->setPixel(0,1, video::SColor(255,myrand()%256,
@@ -1177,8 +1142,9 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
}
// If base image is NULL, load as base.
- if (baseimg == NULL) {
- // infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
+ if (baseimg == NULL)
+ {
+ //infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
/*
Copy it this way to get an alpha channel.
Otherwise images with alpha cannot be blitted on
@@ -1189,15 +1155,16 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
image->copyTo(baseimg);
}
// Else blit on base.
- else {
- // infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
+ else
+ {
+ //infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
// Size of the copied area
core::dimension2d<u32> dim = image->getDimension();
- // core::dimension2d<u32> dim(16,16);
+ //core::dimension2d<u32> dim(16,16);
// Position to copy the blitted to in the base image
- core::position2d<s32> pos_to(0, 0);
+ core::position2d<s32> pos_to(0,0);
// Position to copy the blitted from in the blitted image
- core::position2d<s32> pos_from(0, 0);
+ core::position2d<s32> pos_from(0,0);
// Blit
/*image->copyToWithAlpha(baseimg, pos_to,
core::rect<s32>(pos_from, dim),
@@ -1207,23 +1174,18 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
core::dimension2d<u32> dim_dst = baseimg->getDimension();
if (dim == dim_dst) {
blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
- } else if (dim.Width * dim.Height <
- dim_dst.Width * dim_dst.Height) {
+ } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) {
// Upscale overlying image
- video::IImage *scaled_image =
- RenderingEngine::get_video_driver()->createImage(
- video::ECF_A8R8G8B8,
- dim_dst);
+ video::IImage *scaled_image = RenderingEngine::get_video_driver()->
+ createImage(video::ECF_A8R8G8B8, dim_dst);
image->copyToScaling(scaled_image);
- blit_with_alpha(scaled_image, baseimg, pos_from, pos_to,
- dim_dst);
+ blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, dim_dst);
scaled_image->drop();
} else {
// Upscale base image
- video::IImage *scaled_base =
- RenderingEngine::get_video_driver()->createImage(
- video::ECF_A8R8G8B8, dim);
+ video::IImage *scaled_base = RenderingEngine::get_video_driver()->
+ createImage(video::ECF_A8R8G8B8, dim);
baseimg->copyToScaling(scaled_base);
baseimg->drop();
baseimg = scaled_base;
@@ -1231,9 +1193,11 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
}
}
- // cleanup
+ //cleanup
image->drop();
- } else {
+ }
+ else
+ {
// A special texture modification
/*infostream<<"generateImage(): generating special "
@@ -1246,11 +1210,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
Adds a cracking texture
N = animation frame count, P = crack progression
*/
- if (str_starts_with(part_of_name, "[crack")) {
+ if (str_starts_with(part_of_name, "[crack"))
+ {
if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ errorstream<<"generateImagePart(): baseimg == NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
@@ -1280,12 +1245,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
horizontally tiled.
*/
video::IImage *img_crack = m_sourcecache.getOrLoad(
- "crack_anylength.png");
+ "crack_anylength.png");
if (img_crack) {
- draw_crack(img_crack, baseimg, use_overlay,
- frame_count, progression, driver,
- tiles);
+ draw_crack(img_crack, baseimg,
+ use_overlay, frame_count,
+ progression, driver, tiles);
img_crack->drop();
}
}
@@ -1294,55 +1259,53 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
[combine:WxH:X,Y=filename:X,Y=filename2
Creates a bigger texture from any amount of smaller ones
*/
- else if (str_starts_with(part_of_name, "[combine")) {
+ else if (str_starts_with(part_of_name, "[combine"))
+ {
Strfnd sf(part_of_name);
sf.next(":");
u32 w0 = stoi(sf.next("x"));
u32 h0 = stoi(sf.next(":"));
- core::dimension2d<u32> dim(w0, h0);
+ core::dimension2d<u32> dim(w0,h0);
if (baseimg == NULL) {
baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
- baseimg->fill(video::SColor(0, 0, 0, 0));
+ baseimg->fill(video::SColor(0,0,0,0));
}
while (!sf.at_end()) {
u32 x = stoi(sf.next(","));
u32 y = stoi(sf.next("="));
- std::string filename = unescape_string(
- sf.next_esc(":", escape), escape);
- infostream << "Adding \"" << filename
- << "\" to combined (" << x << "," << y << ")"
- << std::endl;
+ std::string filename = unescape_string(sf.next_esc(":", escape), escape);
+ infostream<<"Adding \""<<filename
+ <<"\" to combined ("<<x<<","<<y<<")"
+ <<std::endl;
video::IImage *img = generateImage(filename);
if (img) {
core::dimension2d<u32> dim = img->getDimension();
core::position2d<s32> pos_base(x, y);
- video::IImage *img2 = driver->createImage(
- video::ECF_A8R8G8B8, dim);
+ video::IImage *img2 =
+ driver->createImage(video::ECF_A8R8G8B8, dim);
img->copyTo(img2);
img->drop();
/*img2->copyToWithAlpha(baseimg, pos_base,
core::rect<s32>(v2s32(0,0), dim),
video::SColor(255,255,255,255),
NULL);*/
- blit_with_alpha(img2, baseimg, v2s32(0, 0),
- pos_base, dim);
+ blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim);
img2->drop();
} else {
- errorstream << "generateImagePart(): Failed to "
- "load image \""
- << filename << "\" for [combine"
- << std::endl;
+ errorstream << "generateImagePart(): Failed to load image \""
+ << filename << "\" for [combine" << std::endl;
}
}
}
/*
[brighten
*/
- else if (str_starts_with(part_of_name, "[brighten")) {
+ else if (str_starts_with(part_of_name, "[brighten"))
+ {
if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg==NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ errorstream<<"generateImagePart(): baseimg==NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
@@ -1355,33 +1318,36 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
that the transparent parts don't look completely black
when simple alpha channel is used for rendering.
*/
- else if (str_starts_with(part_of_name, "[noalpha")) {
- if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg==NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ else if (str_starts_with(part_of_name, "[noalpha"))
+ {
+ if (baseimg == NULL){
+ errorstream<<"generateImagePart(): baseimg==NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
core::dimension2d<u32> dim = baseimg->getDimension();
// Set alpha to full
- for (u32 y = 0; y < dim.Height; y++)
- for (u32 x = 0; x < dim.Width; x++) {
- video::SColor c = baseimg->getPixel(x, y);
- c.setAlpha(255);
- baseimg->setPixel(x, y, c);
- }
+ for (u32 y=0; y<dim.Height; y++)
+ for (u32 x=0; x<dim.Width; x++)
+ {
+ video::SColor c = baseimg->getPixel(x,y);
+ c.setAlpha(255);
+ baseimg->setPixel(x,y,c);
+ }
}
/*
[makealpha:R,G,B
Convert one color to transparent.
*/
- else if (str_starts_with(part_of_name, "[makealpha:")) {
+ else if (str_starts_with(part_of_name, "[makealpha:"))
+ {
if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ errorstream<<"generateImagePart(): baseimg == NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
@@ -1398,17 +1364,18 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
oldbaseimg->drop();*/
// Set alpha to full
- for (u32 y = 0; y < dim.Height; y++)
- for (u32 x = 0; x < dim.Width; x++) {
- video::SColor c = baseimg->getPixel(x, y);
- u32 r = c.getRed();
- u32 g = c.getGreen();
- u32 b = c.getBlue();
- if (!(r == r1 && g == g1 && b == b1))
- continue;
- c.setAlpha(0);
- baseimg->setPixel(x, y, c);
- }
+ for (u32 y=0; y<dim.Height; y++)
+ for (u32 x=0; x<dim.Width; x++)
+ {
+ video::SColor c = baseimg->getPixel(x,y);
+ u32 r = c.getRed();
+ u32 g = c.getGreen();
+ u32 b = c.getBlue();
+ if (!(r == r1 && g == g1 && b == b1))
+ continue;
+ c.setAlpha(0);
+ baseimg->setPixel(x,y,c);
+ }
}
/*
[transformN
@@ -1430,11 +1397,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
The resulting transform will be equivalent to one of the
eight existing ones, though (see: dihedral group).
*/
- else if (str_starts_with(part_of_name, "[transform")) {
+ else if (str_starts_with(part_of_name, "[transform"))
+ {
if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ errorstream<<"generateImagePart(): baseimg == NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
@@ -1456,11 +1424,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
Example (a grass block (not actually used in game):
"[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
*/
- else if (str_starts_with(part_of_name, "[inventorycube")) {
- if (baseimg != NULL) {
- errorstream << "generateImagePart(): baseimg != NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ else if (str_starts_with(part_of_name, "[inventorycube"))
+ {
+ if (baseimg != NULL){
+ errorstream<<"generateImagePart(): baseimg != NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
@@ -1477,10 +1446,9 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
video::IImage *img_right = generateImage(imagename_right);
if (img_top == NULL || img_left == NULL || img_right == NULL) {
- errorstream << "generateImagePart(): Failed to create "
- "textures"
- << " for inventorycube \"" << part_of_name
- << "\"" << std::endl;
+ errorstream << "generateImagePart(): Failed to create textures"
+ << " for inventorycube \"" << part_of_name << "\""
+ << std::endl;
baseimg = generateImage(imagename_top);
return true;
}
@@ -1498,32 +1466,32 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
[lowpart:percent:filename
Adds the lower part of a texture
*/
- else if (str_starts_with(part_of_name, "[lowpart:")) {
+ else if (str_starts_with(part_of_name, "[lowpart:"))
+ {
Strfnd sf(part_of_name);
sf.next(":");
u32 percent = stoi(sf.next(":"));
- std::string filename =
- unescape_string(sf.next_esc(":", escape), escape);
+ std::string filename = unescape_string(sf.next_esc(":", escape), escape);
if (baseimg == NULL)
- baseimg = driver->createImage(
- video::ECF_A8R8G8B8, v2u32(16, 16));
+ baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16));
video::IImage *img = generateImage(filename);
- if (img) {
+ if (img)
+ {
core::dimension2d<u32> dim = img->getDimension();
core::position2d<s32> pos_base(0, 0);
- video::IImage *img2 = driver->createImage(
- video::ECF_A8R8G8B8, dim);
+ video::IImage *img2 =
+ driver->createImage(video::ECF_A8R8G8B8, dim);
img->copyTo(img2);
img->drop();
core::position2d<s32> clippos(0, 0);
- clippos.Y = dim.Height * (100 - percent) / 100;
+ clippos.Y = dim.Height * (100-percent) / 100;
core::dimension2d<u32> clipdim = dim;
clipdim.Height = clipdim.Height * percent / 100 + 1;
core::rect<s32> cliprect(clippos, clipdim);
img2->copyToWithAlpha(baseimg, pos_base,
- core::rect<s32>(v2s32(0, 0), dim),
- video::SColor(255, 255, 255, 255),
+ core::rect<s32>(v2s32(0,0), dim),
+ video::SColor(255,255,255,255),
&cliprect);
img2->drop();
}
@@ -1533,41 +1501,42 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
Crops a frame of a vertical animation.
N = frame count, I = frame index
*/
- else if (str_starts_with(part_of_name, "[verticalframe:")) {
+ else if (str_starts_with(part_of_name, "[verticalframe:"))
+ {
Strfnd sf(part_of_name);
sf.next(":");
u32 frame_count = stoi(sf.next(":"));
u32 frame_index = stoi(sf.next(":"));
- if (baseimg == NULL) {
- errorstream << "generateImagePart(): baseimg != NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ if (baseimg == NULL){
+ errorstream<<"generateImagePart(): baseimg != NULL "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
v2u32 frame_size = baseimg->getDimension();
frame_size.Y /= frame_count;
- video::IImage *img = driver->createImage(
- video::ECF_A8R8G8B8, frame_size);
- if (!img) {
- errorstream << "generateImagePart(): Could not create "
- "image "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ video::IImage *img = driver->createImage(video::ECF_A8R8G8B8,
+ frame_size);
+ if (!img){
+ errorstream<<"generateImagePart(): Could not create image "
+ <<"for part_of_name=\""<<part_of_name
+ <<"\", cancelling."<<std::endl;
return false;
}
// Fill target image with transparency
- img->fill(video::SColor(0, 0, 0, 0));
+ img->fill(video::SColor(0,0,0,0));
core::dimension2d<u32> dim = frame_size;
core::position2d<s32> pos_dst(0, 0);
core::position2d<s32> pos_src(0, frame_index * frame_size.Y);
baseimg->copyToWithAlpha(img, pos_dst,
core::rect<s32>(pos_src, dim),
- video::SColor(255, 255, 255, 255), NULL);
+ video::SColor(255,255,255,255),
+ NULL);
// Replace baseimg
baseimg->drop();
baseimg = img;
@@ -1576,17 +1545,17 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
[mask:filename
Applies a mask to an image
*/
- else if (str_starts_with(part_of_name, "[mask:")) {
+ else if (str_starts_with(part_of_name, "[mask:"))
+ {
if (baseimg == NULL) {
errorstream << "generateImage(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
Strfnd sf(part_of_name);
sf.next(":");
- std::string filename =
- unescape_string(sf.next_esc(":", escape), escape);
+ std::string filename = unescape_string(sf.next_esc(":", escape), escape);
video::IImage *img = generateImage(filename);
if (img) {
@@ -1595,7 +1564,7 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
img->drop();
} else {
errorstream << "generateImage(): Failed to load \""
- << filename << "\".";
+ << filename << "\".";
}
}
/*
@@ -1610,8 +1579,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg != NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1620,15 +1589,15 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (!parseColorString(color_str, color, false))
return false;
- apply_multiplication(baseimg, v2u32(0, 0),
- baseimg->getDimension(), color);
+ apply_multiplication(baseimg, v2u32(0, 0), baseimg->getDimension(), color);
}
/*
[colorize:color
Overlays image with given color
color = color as ColorString
*/
- else if (str_starts_with(part_of_name, "[colorize:")) {
+ else if (str_starts_with(part_of_name, "[colorize:"))
+ {
Strfnd sf(part_of_name);
sf.next(":");
std::string color_str = sf.next(":");
@@ -1636,8 +1605,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg != NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1653,14 +1622,14 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
else if (ratio_str == "alpha")
keep_alpha = true;
- apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(),
- color, ratio, keep_alpha);
+ apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha);
}
/*
[applyfiltersformesh
Internal modifier
*/
- else if (str_starts_with(part_of_name, "[applyfiltersformesh")) {
+ else if (str_starts_with(part_of_name, "[applyfiltersformesh"))
+ {
/* IMPORTANT: When changing this, getTextureForMesh() needs to be
* updated too. */
@@ -1668,33 +1637,25 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (g_settings->getBool("texture_clean_transparent"))
imageCleanTransparent(baseimg, 127);
- /* Upscale textures to user's requested minimum size. This is a
- * trick to make filters look as good on low-res textures as on
- * high-res ones, by making low-res textures BECOME high-res ones.
- * This is helpful for worlds that mix high- and low-res textures,
- * or for mods with least-common-denominator textures that don't
- * have the resources to offer high-res alternatives.
+ /* Upscale textures to user's requested minimum size. This is a trick to make
+ * filters look as good on low-res textures as on high-res ones, by making
+ * low-res textures BECOME high-res ones. This is helpful for worlds that
+ * mix high- and low-res textures, or for mods with least-common-denominator
+ * textures that don't have the resources to offer high-res alternatives.
*/
- const bool filter = m_setting_trilinear_filter ||
- m_setting_bilinear_filter;
- const s32 scaleto =
- filter ? g_settings->getS32("texture_min_size")
- : 1;
+ const bool filter = m_setting_trilinear_filter || m_setting_bilinear_filter;
+ const s32 scaleto = filter ? g_settings->getS32("texture_min_size") : 1;
if (scaleto > 1) {
- const core::dimension2d<u32> dim =
- baseimg->getDimension();
+ const core::dimension2d<u32> dim = baseimg->getDimension();
- /* Calculate scaling needed to make the shortest texture
- * dimension equal to the target minimum. If e.g. this is
- * a vertical frames animation, the short dimension will
- * be the real size.
+ /* Calculate scaling needed to make the shortest texture dimension
+ * equal to the target minimum. If e.g. this is a vertical frames
+ * animation, the short dimension will be the real size.
*/
if ((dim.Width == 0) || (dim.Height == 0)) {
- errorstream << "generateImagePart(): Illegal 0 "
- "dimension "
- << "for part_of_name=\""
- << part_of_name << "\", cancelling."
- << std::endl;
+ errorstream << "generateImagePart(): Illegal 0 dimension "
+ << "for part_of_name=\""<< part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
u32 xscale = scaleto / dim.Width;
@@ -1705,11 +1666,9 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
if (scale > 1) {
u32 w = scale * dim.Width;
u32 h = scale * dim.Height;
- const core::dimension2d<u32> newdim =
- core::dimension2d<u32>(w, h);
+ const core::dimension2d<u32> newdim = core::dimension2d<u32>(w, h);
video::IImage *newimg = driver->createImage(
- baseimg->getColorFormat(),
- newdim);
+ baseimg->getColorFormat(), newdim);
baseimg->copyToScaling(newimg);
baseimg->drop();
baseimg = newimg;
@@ -1720,11 +1679,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
[resize:WxH
Resizes the base image to the given dimensions
*/
- else if (str_starts_with(part_of_name, "[resize")) {
+ else if (str_starts_with(part_of_name, "[resize"))
+ {
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\""<< part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1734,9 +1694,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
u32 height = stoi(sf.next(""));
core::dimension2d<u32> dim(width, height);
- video::IImage *image =
- RenderingEngine::get_video_driver()->createImage(
- video::ECF_A8R8G8B8, dim);
+ video::IImage *image = RenderingEngine::get_video_driver()->
+ createImage(video::ECF_A8R8G8B8, dim);
baseimg->copyToScaling(image);
baseimg->drop();
baseimg = image;
@@ -1751,8 +1710,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
else if (str_starts_with(part_of_name, "[opacity:")) {
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1764,12 +1723,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
core::dimension2d<u32> dim = baseimg->getDimension();
for (u32 y = 0; y < dim.Height; y++)
- for (u32 x = 0; x < dim.Width; x++) {
- video::SColor c = baseimg->getPixel(x, y);
- c.setAlpha(floor((c.getAlpha() * ratio) / 255 +
- 0.5));
- baseimg->setPixel(x, y, c);
- }
+ for (u32 x = 0; x < dim.Width; x++)
+ {
+ video::SColor c = baseimg->getPixel(x, y);
+ c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5));
+ baseimg->setPixel(x, y, c);
+ }
}
/*
[invert:mode
@@ -1781,8 +1740,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
else if (str_starts_with(part_of_name, "[invert:")) {
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg == NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1803,11 +1762,12 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
core::dimension2d<u32> dim = baseimg->getDimension();
for (u32 y = 0; y < dim.Height; y++)
- for (u32 x = 0; x < dim.Width; x++) {
- video::SColor c = baseimg->getPixel(x, y);
- c.color ^= mask;
- baseimg->setPixel(x, y, c);
- }
+ for (u32 x = 0; x < dim.Width; x++)
+ {
+ video::SColor c = baseimg->getPixel(x, y);
+ c.color ^= mask;
+ baseimg->setPixel(x, y, c);
+ }
}
/*
[sheet:WxH:X,Y
@@ -1815,11 +1775,11 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
from the base image it assumes to be a
tilesheet with dimensions W,H (in tiles).
*/
- else if (part_of_name.substr(0, 7) == "[sheet:") {
+ else if (part_of_name.substr(0,7) == "[sheet:") {
if (baseimg == NULL) {
errorstream << "generateImagePart(): baseimg != NULL "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
@@ -1836,26 +1796,26 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
video::IImage *img = driver->createImage(
video::ECF_A8R8G8B8, tile_dim);
if (!img) {
- errorstream << "generateImagePart(): Could not create "
- "image "
- << "for part_of_name=\"" << part_of_name
- << "\", cancelling." << std::endl;
+ errorstream << "generateImagePart(): Could not create image "
+ << "for part_of_name=\"" << part_of_name
+ << "\", cancelling." << std::endl;
return false;
}
- img->fill(video::SColor(0, 0, 0, 0));
+ img->fill(video::SColor(0,0,0,0));
v2u32 vdim(tile_dim);
core::rect<s32> rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim);
baseimg->copyToWithAlpha(img, v2s32(0), rect,
- video::SColor(255, 255, 255, 255), NULL);
+ video::SColor(255,255,255,255), NULL);
// Replace baseimg
baseimg->drop();
baseimg = img;
- } else {
+ }
+ else
+ {
errorstream << "generateImagePart(): Invalid "
- " modification: \""
- << part_of_name << "\"" << std::endl;
+ " modification: \"" << part_of_name << "\"" << std::endl;
}
}
@@ -1870,14 +1830,13 @@ bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *&
pixel with alpha=64 drawn atop a pixel with alpha=128 should yield a
pixel with alpha=160, while getInterpolated would yield alpha=96.
*/
-static inline video::SColor blitPixel(
- const video::SColor &src_c, const video::SColor &dst_c, u32 ratio)
+static inline video::SColor blitPixel(const video::SColor &src_c, const video::SColor &dst_c, u32 ratio)
{
if (dst_c.getAlpha() == 0)
return src_c;
video::SColor out_c = src_c.getInterpolated(dst_c, (float)ratio / 255.0f);
- out_c.setAlpha(dst_c.getAlpha() + (255 - dst_c.getAlpha()) * src_c.getAlpha() *
- ratio / (255 * 255));
+ out_c.setAlpha(dst_c.getAlpha() + (255 - dst_c.getAlpha()) *
+ src_c.getAlpha() * ratio / (255 * 255));
return out_c;
}
@@ -1888,42 +1847,45 @@ static inline video::SColor blitPixel(
This exists because IImage::copyToWithAlpha() doesn't seem to always
work.
*/
-static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos,
- v2s32 dst_pos, v2u32 size)
+static void blit_with_alpha(video::IImage *src, video::IImage *dst,
+ v2s32 src_pos, v2s32 dst_pos, v2u32 size)
{
- for (u32 y0 = 0; y0 < size.Y; y0++)
- for (u32 x0 = 0; x0 < size.X; x0++) {
- s32 src_x = src_pos.X + x0;
- s32 src_y = src_pos.Y + y0;
- s32 dst_x = dst_pos.X + x0;
- s32 dst_y = dst_pos.Y + y0;
- video::SColor src_c = src->getPixel(src_x, src_y);
- video::SColor dst_c = dst->getPixel(dst_x, dst_y);
- dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
- dst->setPixel(dst_x, dst_y, dst_c);
- }
+ for (u32 y0=0; y0<size.Y; y0++)
+ for (u32 x0=0; x0<size.X; x0++)
+ {
+ s32 src_x = src_pos.X + x0;
+ s32 src_y = src_pos.Y + y0;
+ s32 dst_x = dst_pos.X + x0;
+ s32 dst_y = dst_pos.Y + y0;
+ video::SColor src_c = src->getPixel(src_x, src_y);
+ video::SColor dst_c = dst->getPixel(dst_x, dst_y);
+ dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
+ dst->setPixel(dst_x, dst_y, dst_c);
+ }
}
/*
Draw an image on top of an another one, using the alpha channel of the
source image; only modify fully opaque pixels in destinaion
*/
-static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos,
- v2s32 dst_pos, v2u32 size)
+static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst,
+ v2s32 src_pos, v2s32 dst_pos, v2u32 size)
{
- for (u32 y0 = 0; y0 < size.Y; y0++)
- for (u32 x0 = 0; x0 < size.X; x0++) {
- s32 src_x = src_pos.X + x0;
- s32 src_y = src_pos.Y + y0;
- s32 dst_x = dst_pos.X + x0;
- s32 dst_y = dst_pos.Y + y0;
- video::SColor src_c = src->getPixel(src_x, src_y);
- video::SColor dst_c = dst->getPixel(dst_x, dst_y);
- if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0) {
- dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
- dst->setPixel(dst_x, dst_y, dst_c);
- }
+ for (u32 y0=0; y0<size.Y; y0++)
+ for (u32 x0=0; x0<size.X; x0++)
+ {
+ s32 src_x = src_pos.X + x0;
+ s32 src_y = src_pos.Y + y0;
+ s32 dst_x = dst_pos.X + x0;
+ s32 dst_y = dst_pos.Y + y0;
+ video::SColor src_c = src->getPixel(src_x, src_y);
+ video::SColor dst_c = dst->getPixel(dst_x, dst_y);
+ if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0)
+ {
+ dst_c = blitPixel(src_c, dst_c, src_c.getAlpha());
+ dst->setPixel(dst_x, dst_y, dst_c);
}
+ }
}
// This function has been disabled because it is currently unused.
@@ -1966,60 +1928,61 @@ static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size,
u32 alpha = color.getAlpha();
video::SColor dst_c;
if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color
- if (keep_alpha) { // replace the color with alpha = dest alpha * color
- // alpha
+ if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha
dst_c = color;
for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
- for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
- u32 dst_alpha = dst->getPixel(x, y).getAlpha();
- if (dst_alpha > 0) {
- dst_c.setAlpha(dst_alpha * alpha / 255);
- dst->setPixel(x, y, dst_c);
- }
+ for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
+ u32 dst_alpha = dst->getPixel(x, y).getAlpha();
+ if (dst_alpha > 0) {
+ dst_c.setAlpha(dst_alpha * alpha / 255);
+ dst->setPixel(x, y, dst_c);
}
+ }
} else { // replace the color including the alpha
for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
- for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++)
- if (dst->getPixel(x, y).getAlpha() > 0)
- dst->setPixel(x, y, color);
+ for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++)
+ if (dst->getPixel(x, y).getAlpha() > 0)
+ dst->setPixel(x, y, color);
}
- } else { // interpolate between the color and destination
+ } else { // interpolate between the color and destination
float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f);
for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
- for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
- dst_c = dst->getPixel(x, y);
- if (dst_c.getAlpha() > 0) {
- dst_c = color.getInterpolated(dst_c, interp);
- dst->setPixel(x, y, dst_c);
- }
+ for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
+ dst_c = dst->getPixel(x, y);
+ if (dst_c.getAlpha() > 0) {
+ dst_c = color.getInterpolated(dst_c, interp);
+ dst->setPixel(x, y, dst_c);
}
+ }
}
}
/*
Apply color to destination
*/
-static void apply_multiplication(
- video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color)
+static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size,
+ const video::SColor &color)
{
video::SColor dst_c;
for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++)
- for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
- dst_c = dst->getPixel(x, y);
- dst_c.set(dst_c.getAlpha(),
- (dst_c.getRed() * color.getRed()) / 255,
- (dst_c.getGreen() * color.getGreen()) / 255,
- (dst_c.getBlue() * color.getBlue()) / 255);
- dst->setPixel(x, y, dst_c);
- }
+ for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) {
+ dst_c = dst->getPixel(x, y);
+ dst_c.set(
+ dst_c.getAlpha(),
+ (dst_c.getRed() * color.getRed()) / 255,
+ (dst_c.getGreen() * color.getGreen()) / 255,
+ (dst_c.getBlue() * color.getBlue()) / 255
+ );
+ dst->setPixel(x, y, dst_c);
+ }
}
/*
Apply mask to destination
*/
-static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos,
- v2s32 dst_pos, v2u32 size)
+static void apply_mask(video::IImage *mask, video::IImage *dst,
+ v2s32 mask_pos, v2s32 dst_pos, v2u32 size)
{
for (u32 y0 = 0; y0 < size.Y; y0++) {
for (u32 x0 = 0; x0 < size.X; x0++) {
@@ -2047,15 +2010,14 @@ video::IImage *create_crack_image(video::IImage *crack, s32 frame_index,
core::rect<s32> frame(v2s32(0, frame_index * frame_size.Height), frame_size);
video::IImage *result = nullptr;
- // extract crack frame
+// extract crack frame
video::IImage *crack_tile = driver->createImage(video::ECF_A8R8G8B8, tile_size);
if (!crack_tile)
return nullptr;
if (tile_size == frame_size) {
crack->copyTo(crack_tile, v2s32(0, 0), frame);
} else {
- video::IImage *crack_frame =
- driver->createImage(video::ECF_A8R8G8B8, frame_size);
+ video::IImage *crack_frame = driver->createImage(video::ECF_A8R8G8B8, frame_size);
if (!crack_frame)
goto exit__has_tile;
crack->copyTo(crack_frame, v2s32(0, 0), frame);
@@ -2065,43 +2027,46 @@ video::IImage *create_crack_image(video::IImage *crack, s32 frame_index,
if (tiles == 1)
return crack_tile;
- // tile it
+// tile it
result = driver->createImage(video::ECF_A8R8G8B8, size);
if (!result)
goto exit__has_tile;
result->fill({});
for (u8 i = 0; i < tiles; i++)
for (u8 j = 0; j < tiles; j++)
- crack_tile->copyTo(result,
- v2s32(i * tile_size.Width, j * tile_size.Height));
+ crack_tile->copyTo(result, v2s32(i * tile_size.Width, j * tile_size.Height));
exit__has_tile:
crack_tile->drop();
return result;
}
-static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay,
- s32 frame_count, s32 progression, video::IVideoDriver *driver, u8 tiles)
+static void draw_crack(video::IImage *crack, video::IImage *dst,
+ bool use_overlay, s32 frame_count, s32 progression,
+ video::IVideoDriver *driver, u8 tiles)
{
// Dimension of destination image
core::dimension2d<u32> dim_dst = dst->getDimension();
// Limit frame_count
- if (frame_count > (s32)dim_dst.Height)
+ if (frame_count > (s32) dim_dst.Height)
frame_count = dim_dst.Height;
if (frame_count < 1)
frame_count = 1;
// Dimension of the scaled crack stage,
// which is the same as the dimension of a single destination frame
- core::dimension2d<u32> frame_size(dim_dst.Width, dim_dst.Height / frame_count);
- video::IImage *crack_scaled =
- create_crack_image(crack, progression, frame_size, tiles, driver);
+ core::dimension2d<u32> frame_size(
+ dim_dst.Width,
+ dim_dst.Height / frame_count
+ );
+ video::IImage *crack_scaled = create_crack_image(crack, progression,
+ frame_size, tiles, driver);
if (!crack_scaled)
return;
auto blit = use_overlay ? blit_with_alpha_overlay : blit_with_alpha;
for (s32 i = 0; i < frame_count; ++i) {
v2s32 dst_pos(0, frame_size.Height * i);
- blit(crack_scaled, dst, v2s32(0, 0), dst_pos, frame_size);
+ blit(crack_scaled, dst, v2s32(0,0), dst_pos, frame_size);
}
crack_scaled->drop();
@@ -2114,17 +2079,18 @@ void brighten(video::IImage *image)
core::dimension2d<u32> dim = image->getDimension();
- for (u32 y = 0; y < dim.Height; y++)
- for (u32 x = 0; x < dim.Width; x++) {
- video::SColor c = image->getPixel(x, y);
- c.setRed(0.5 * 255 + 0.5 * (float)c.getRed());
- c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen());
- c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue());
- image->setPixel(x, y, c);
- }
+ for (u32 y=0; y<dim.Height; y++)
+ for (u32 x=0; x<dim.Width; x++)
+ {
+ video::SColor c = image->getPixel(x,y);
+ c.setRed(0.5 * 255 + 0.5 * (float)c.getRed());
+ c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen());
+ c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue());
+ image->setPixel(x,y,c);
+ }
}
-u32 parseImageTransform(const std::string &s)
+u32 parseImageTransform(const std::string& s)
{
int total_transform = 0;
@@ -2137,20 +2103,21 @@ u32 parseImageTransform(const std::string &s)
transform_names[6] = "fy";
std::size_t pos = 0;
- while (pos < s.size()) {
+ while(pos < s.size())
+ {
int transform = -1;
- for (int i = 0; i <= 7; ++i) {
+ for (int i = 0; i <= 7; ++i)
+ {
const std::string &name_i = transform_names[i];
- if (s[pos] == ('0' + i)) {
+ if (s[pos] == ('0' + i))
+ {
transform = i;
pos++;
break;
}
- if (!(name_i.empty()) &&
- lowercase(s.substr(pos, name_i.size())) ==
- name_i) {
+ if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) {
transform = i;
pos += name_i.size();
break;
@@ -2198,35 +2165,35 @@ void imageTransform(u32 transform, video::IImage *src, video::IImage *dst)
*/
int sxn = 0;
int syn = 2;
- if (transform == 0) // identity
- sxn = 0, syn = 2; // sx = dx, sy = dy
- else if (transform == 1) // rotate by 90 degrees ccw
- sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx
- else if (transform == 2) // rotate by 180 degrees
- sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy
- else if (transform == 3) // rotate by 270 degrees ccw
- sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx
- else if (transform == 4) // flip x
- sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy
- else if (transform == 5) // flip x then rotate by 90 degrees ccw
- sxn = 2, syn = 0; // sx = dy, sy = dx
- else if (transform == 6) // flip y
- sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy
- else if (transform == 7) // flip y then rotate by 90 degrees ccw
- sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx
-
- for (u32 dy = 0; dy < dstdim.Height; dy++)
- for (u32 dx = 0; dx < dstdim.Width; dx++) {
- u32 entries[4] = {dx, dstdim.Width - 1 - dx, dy,
- dstdim.Height - 1 - dy};
- u32 sx = entries[sxn];
- u32 sy = entries[syn];
- video::SColor c = src->getPixel(sx, sy);
- dst->setPixel(dx, dy, c);
- }
+ if (transform == 0) // identity
+ sxn = 0, syn = 2; // sx = dx, sy = dy
+ else if (transform == 1) // rotate by 90 degrees ccw
+ sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx
+ else if (transform == 2) // rotate by 180 degrees
+ sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy
+ else if (transform == 3) // rotate by 270 degrees ccw
+ sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx
+ else if (transform == 4) // flip x
+ sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy
+ else if (transform == 5) // flip x then rotate by 90 degrees ccw
+ sxn = 2, syn = 0; // sx = dy, sy = dx
+ else if (transform == 6) // flip y
+ sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy
+ else if (transform == 7) // flip y then rotate by 90 degrees ccw
+ sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx
+
+ for (u32 dy=0; dy<dstdim.Height; dy++)
+ for (u32 dx=0; dx<dstdim.Width; dx++)
+ {
+ u32 entries[4] = {dx, dstdim.Width-1-dx, dy, dstdim.Height-1-dy};
+ u32 sx = entries[sxn];
+ u32 sy = entries[syn];
+ video::SColor c = src->getPixel(sx,sy);
+ dst->setPixel(dx,dy,c);
+ }
}
-video::ITexture *TextureSource::getNormalTexture(const std::string &name)
+video::ITexture* TextureSource::getNormalTexture(const std::string &name)
{
if (isKnownSourceImage("override_normal.png"))
return getTexture("override_normal.png");
@@ -2252,8 +2219,9 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name)
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
video::SColor c(0, 0, 0, 0);
video::ITexture *texture = getTexture(name);
- video::IImage *image = driver->createImage(
- texture, core::position2d<s32>(0, 0), texture->getOriginalSize());
+ video::IImage *image = driver->createImage(texture,
+ core::position2d<s32>(0, 0),
+ texture->getOriginalSize());
u32 total = 0;
u32 tR = 0;
u32 tG = 0;
@@ -2264,7 +2232,7 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name)
step = dim.Width / 16;
for (u16 x = 0; x < dim.Width; x += step) {
for (u16 y = 0; y < dim.Width; y += step) {
- c = image->getPixel(x, y);
+ c = image->getPixel(x,y);
if (c.getAlpha() > 0) {
total++;
tR += c.getRed();
@@ -2283,6 +2251,7 @@ video::SColor TextureSource::getTextureAverageColor(const std::string &name)
return c;
}
+
video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present)
{
std::string tname = "__shaderFlagsTexture";
@@ -2294,13 +2263,14 @@ video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present)
video::IVideoDriver *driver = RenderingEngine::get_video_driver();
video::IImage *flags_image = driver->createImage(
- video::ECF_A8R8G8B8, core::dimension2d<u32>(1, 1));
+ video::ECF_A8R8G8B8, core::dimension2d<u32>(1, 1));
sanity_check(flags_image != NULL);
video::SColor c(255, normalmap_present ? 255 : 0, 0, 0);
flags_image->setPixel(0, 0, c);
insertSourceImage(tname, flags_image);
flags_image->drop();
return getTexture(tname);
+
}
std::vector<std::string> getTextureDirs()
diff --git a/src/client/tile.h b/src/client/tile.h
index 695bcdeac..49c46f749 100644
--- a/src/client/tile.h
+++ b/src/client/tile.h
@@ -78,7 +78,7 @@ public:
virtual ~ISimpleTextureSource() = default;
- virtual video::ITexture *getTexture(
+ virtual video::ITexture* getTexture(
const std::string &name, u32 *id = nullptr) = 0;
};
@@ -89,12 +89,12 @@ public:
virtual ~ITextureSource() = default;
- virtual u32 getTextureId(const std::string &name) = 0;
- virtual std::string getTextureName(u32 id) = 0;
- virtual video::ITexture *getTexture(u32 id) = 0;
- virtual video::ITexture *getTexture(
- const std::string &name, u32 *id = nullptr) = 0;
- virtual video::ITexture *getTextureForMesh(
+ virtual u32 getTextureId(const std::string &name)=0;
+ virtual std::string getTextureName(u32 id)=0;
+ virtual video::ITexture* getTexture(u32 id)=0;
+ virtual video::ITexture* getTexture(
+ const std::string &name, u32 *id = nullptr)=0;
+ virtual video::ITexture* getTextureForMesh(
const std::string &name, u32 *id = nullptr) = 0;
/*!
* Returns a palette from the given texture name.
@@ -102,11 +102,11 @@ public:
* destructed.
* Should be called from the main thread.
*/
- virtual Palette *getPalette(const std::string &name) = 0;
- virtual bool isKnownSourceImage(const std::string &name) = 0;
- virtual video::ITexture *getNormalTexture(const std::string &name) = 0;
- virtual video::SColor getTextureAverageColor(const std::string &name) = 0;
- virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present) = 0;
+ virtual Palette* getPalette(const std::string &name) = 0;
+ virtual bool isKnownSourceImage(const std::string &name)=0;
+ virtual video::ITexture* getNormalTexture(const std::string &name)=0;
+ virtual video::SColor getTextureAverageColor(const std::string &name)=0;
+ virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0;
};
class IWritableTextureSource : public ITextureSource
@@ -116,30 +116,29 @@ public:
virtual ~IWritableTextureSource() = default;
- virtual u32 getTextureId(const std::string &name) = 0;
- virtual std::string getTextureName(u32 id) = 0;
- virtual video::ITexture *getTexture(u32 id) = 0;
- virtual video::ITexture *getTexture(
- const std::string &name, u32 *id = nullptr) = 0;
- virtual bool isKnownSourceImage(const std::string &name) = 0;
-
- virtual void processQueue() = 0;
- virtual void insertSourceImage(const std::string &name, video::IImage *img) = 0;
- virtual void rebuildImagesAndTextures() = 0;
- virtual video::ITexture *getNormalTexture(const std::string &name) = 0;
- virtual video::SColor getTextureAverageColor(const std::string &name) = 0;
- virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present) = 0;
+ virtual u32 getTextureId(const std::string &name)=0;
+ virtual std::string getTextureName(u32 id)=0;
+ virtual video::ITexture* getTexture(u32 id)=0;
+ virtual video::ITexture* getTexture(
+ const std::string &name, u32 *id = nullptr)=0;
+ virtual bool isKnownSourceImage(const std::string &name)=0;
+
+ virtual void processQueue()=0;
+ virtual void insertSourceImage(const std::string &name, video::IImage *img)=0;
+ virtual void rebuildImagesAndTextures()=0;
+ virtual video::ITexture* getNormalTexture(const std::string &name)=0;
+ virtual video::SColor getTextureAverageColor(const std::string &name)=0;
+ virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0;
};
IWritableTextureSource *createTextureSource();
#if ENABLE_GLES
bool hasNPotSupport();
-video::IImage *Align2Npot2(video::IImage *image, irr::video::IVideoDriver *driver);
+video::IImage * Align2Npot2(video::IImage * image, irr::video::IVideoDriver* driver);
#endif
-enum MaterialType
-{
+enum MaterialType{
TILE_MATERIAL_BASIC,
TILE_MATERIAL_ALPHA,
TILE_MATERIAL_LIQUID_TRANSPARENT,
@@ -193,16 +192,21 @@ struct TileLayer
*/
bool operator==(const TileLayer &other) const
{
- return texture_id == other.texture_id &&
- material_type == other.material_type &&
- material_flags == other.material_flags && color == other.color &&
- scale == other.scale;
+ return
+ texture_id == other.texture_id &&
+ material_type == other.material_type &&
+ material_flags == other.material_flags &&
+ color == other.color &&
+ scale == other.scale;
}
/*!
* Two tiles are not equal if they must have different vertices.
*/
- bool operator!=(const TileLayer &other) const { return !(*this == other); }
+ bool operator!=(const TileLayer &other) const
+ {
+ return !(*this == other);
+ }
// Sets everything else except the texture in the material
void applyMaterialOptions(video::SMaterial &material) const
@@ -228,8 +232,7 @@ struct TileLayer
default:
break;
}
- material.BackfaceCulling =
- (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
+ material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) {
material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
}
@@ -240,8 +243,7 @@ struct TileLayer
void applyMaterialOptionsWithShaders(video::SMaterial &material) const
{
- material.BackfaceCulling =
- (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
+ material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) {
material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
material.TextureLayer[1].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
@@ -254,8 +256,8 @@ struct TileLayer
bool isTileable() const
{
- return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) &&
- (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL);
+ return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)
+ && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL);
}
// Ordered for size, please do not reorder
@@ -273,10 +275,10 @@ struct TileLayer
u8 material_type = TILE_MATERIAL_BASIC;
u8 material_flags =
- // 0 // <- DEBUG, Use the one below
- MATERIAL_FLAG_BACKFACE_CULLING |
- MATERIAL_FLAG_TILEABLE_HORIZONTAL |
- MATERIAL_FLAG_TILEABLE_VERTICAL;
+ //0 // <- DEBUG, Use the one below
+ MATERIAL_FLAG_BACKFACE_CULLING |
+ MATERIAL_FLAG_TILEABLE_HORIZONTAL|
+ MATERIAL_FLAG_TILEABLE_VERTICAL;
//! If true, the tile has its own color.
bool has_color = false;
@@ -302,16 +304,16 @@ struct TileSpec
/*!
* Returns true if this tile can be merged with the other tile.
*/
- bool isTileable(const TileSpec &other) const
- {
+ bool isTileable(const TileSpec &other) const {
for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
if (layers[layer] != other.layers[layer])
return false;
if (!layers[layer].isTileable())
return false;
}
- return rotation == 0 && rotation == other.rotation &&
- emissive_light == other.emissive_light;
+ return rotation == 0
+ && rotation == other.rotation
+ && emissive_light == other.emissive_light;
}
//! If true, the tile rotation is ignored.
diff --git a/src/client/wieldmesh.cpp b/src/client/wieldmesh.cpp
index 06053302f..8cd3e29a9 100644
--- a/src/client/wieldmesh.cpp
+++ b/src/client/wieldmesh.cpp
@@ -45,29 +45,29 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y)
const f32 r = 0.5;
scene::IMeshBuffer *buf = new scene::SMeshBuffer();
- video::SColor c(255, 255, 255, 255);
+ video::SColor c(255,255,255,255);
v3f scale(1.0, 1.0, 0.1);
// Front and back
{
video::S3DVertex vertices[8] = {
- // z-
- video::S3DVertex(-r, +r, -r, 0, 0, -1, c, 0, 0),
- video::S3DVertex(+r, +r, -r, 0, 0, -1, c, 1, 0),
- video::S3DVertex(+r, -r, -r, 0, 0, -1, c, 1, 1),
- video::S3DVertex(-r, -r, -r, 0, 0, -1, c, 0, 1),
- // z+
- video::S3DVertex(-r, +r, +r, 0, 0, +1, c, 0, 0),
- video::S3DVertex(-r, -r, +r, 0, 0, +1, c, 0, 1),
- video::S3DVertex(+r, -r, +r, 0, 0, +1, c, 1, 1),
- video::S3DVertex(+r, +r, +r, 0, 0, +1, c, 1, 0),
+ // z-
+ video::S3DVertex(-r,+r,-r, 0,0,-1, c, 0,0),
+ video::S3DVertex(+r,+r,-r, 0,0,-1, c, 1,0),
+ video::S3DVertex(+r,-r,-r, 0,0,-1, c, 1,1),
+ video::S3DVertex(-r,-r,-r, 0,0,-1, c, 0,1),
+ // z+
+ video::S3DVertex(-r,+r,+r, 0,0,+1, c, 0,0),
+ video::S3DVertex(-r,-r,+r, 0,0,+1, c, 0,1),
+ video::S3DVertex(+r,-r,+r, 0,0,+1, c, 1,1),
+ video::S3DVertex(+r,+r,+r, 0,0,+1, c, 1,0),
};
- u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4};
+ u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4};
buf->append(vertices, 8, indices, 12);
}
- f32 pixelsize_x = 1 / (f32)resolution_x;
- f32 pixelsize_y = 1 / (f32)resolution_y;
+ f32 pixelsize_x = 1 / (f32) resolution_x;
+ f32 pixelsize_y = 1 / (f32) resolution_y;
for (int i = 0; i < resolution_x; ++i) {
f32 pixelpos_x = i * pixelsize_x - 0.5;
@@ -76,18 +76,18 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y)
f32 tex0 = (i + 0.1) * pixelsize_x;
f32 tex1 = (i + 0.9) * pixelsize_x;
video::S3DVertex vertices[8] = {
- // x-
- video::S3DVertex(x0, -r, -r, -1, 0, 0, c, tex0, 1),
- video::S3DVertex(x0, -r, +r, -1, 0, 0, c, tex1, 1),
- video::S3DVertex(x0, +r, +r, -1, 0, 0, c, tex1, 0),
- video::S3DVertex(x0, +r, -r, -1, 0, 0, c, tex0, 0),
- // x+
- video::S3DVertex(x1, -r, -r, +1, 0, 0, c, tex0, 1),
- video::S3DVertex(x1, +r, -r, +1, 0, 0, c, tex0, 0),
- video::S3DVertex(x1, +r, +r, +1, 0, 0, c, tex1, 0),
- video::S3DVertex(x1, -r, +r, +1, 0, 0, c, tex1, 1),
+ // x-
+ video::S3DVertex(x0,-r,-r, -1,0,0, c, tex0,1),
+ video::S3DVertex(x0,-r,+r, -1,0,0, c, tex1,1),
+ video::S3DVertex(x0,+r,+r, -1,0,0, c, tex1,0),
+ video::S3DVertex(x0,+r,-r, -1,0,0, c, tex0,0),
+ // x+
+ video::S3DVertex(x1,-r,-r, +1,0,0, c, tex0,1),
+ video::S3DVertex(x1,+r,-r, +1,0,0, c, tex0,0),
+ video::S3DVertex(x1,+r,+r, +1,0,0, c, tex1,0),
+ video::S3DVertex(x1,-r,+r, +1,0,0, c, tex1,1),
};
- u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4};
+ u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4};
buf->append(vertices, 8, indices, 12);
}
for (int i = 0; i < resolution_y; ++i) {
@@ -97,18 +97,18 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y)
f32 tex0 = (i + 0.1) * pixelsize_y;
f32 tex1 = (i + 0.9) * pixelsize_y;
video::S3DVertex vertices[8] = {
- // y-
- video::S3DVertex(-r, y0, -r, 0, -1, 0, c, 0, tex0),
- video::S3DVertex(+r, y0, -r, 0, -1, 0, c, 1, tex0),
- video::S3DVertex(+r, y0, +r, 0, -1, 0, c, 1, tex1),
- video::S3DVertex(-r, y0, +r, 0, -1, 0, c, 0, tex1),
- // y+
- video::S3DVertex(-r, y1, -r, 0, +1, 0, c, 0, tex0),
- video::S3DVertex(-r, y1, +r, 0, +1, 0, c, 0, tex1),
- video::S3DVertex(+r, y1, +r, 0, +1, 0, c, 1, tex1),
- video::S3DVertex(+r, y1, -r, 0, +1, 0, c, 1, tex0),
+ // y-
+ video::S3DVertex(-r,y0,-r, 0,-1,0, c, 0,tex0),
+ video::S3DVertex(+r,y0,-r, 0,-1,0, c, 1,tex0),
+ video::S3DVertex(+r,y0,+r, 0,-1,0, c, 1,tex1),
+ video::S3DVertex(-r,y0,+r, 0,-1,0, c, 0,tex1),
+ // y+
+ video::S3DVertex(-r,y1,-r, 0,+1,0, c, 0,tex0),
+ video::S3DVertex(-r,y1,+r, 0,+1,0, c, 0,tex1),
+ video::S3DVertex(+r,y1,+r, 0,+1,0, c, 1,tex1),
+ video::S3DVertex(+r,y1,-r, 0,+1,0, c, 1,tex0),
};
- u16 indices[12] = {0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4};
+ u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4};
buf->append(vertices, 8, indices, 12);
}
@@ -116,7 +116,7 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y)
scene::SMesh *mesh = new scene::SMesh();
mesh->addMeshBuffer(buf);
buf->drop();
- scaleMesh(mesh, scale); // also recalculates bounding box
+ scaleMesh(mesh, scale); // also recalculates bounding box
return mesh;
}
@@ -131,7 +131,7 @@ static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y)
rendering related classes (such as WieldMeshSceneNode) will be
used from the rendering thread only.
*/
-class ExtrusionMeshCache : public IReferenceCounted
+class ExtrusionMeshCache: public IReferenceCounted
{
public:
// Constructor
@@ -141,7 +141,7 @@ public:
resolution <= MAX_EXTRUSION_MESH_RESOLUTION;
resolution *= 2) {
m_extrusion_meshes[resolution] =
- createExtrusionMesh(resolution, resolution);
+ createExtrusionMesh(resolution, resolution);
}
m_cube = createCubeMesh(v3f(1.0, 1.0, 1.0));
}
@@ -155,7 +155,7 @@ public:
}
// Get closest extrusion mesh for given image dimensions
// Caller must drop the returned pointer
- scene::IMesh *create(core::dimension2d<u32> dim)
+ scene::IMesh* create(core::dimension2d<u32> dim)
{
// handle non-power of two textures inefficiently without cache
if (!is_power_of_two(dim.Width) || !is_power_of_two(dim.Height)) {
@@ -164,8 +164,8 @@ public:
int maxdim = MYMAX(dim.Width, dim.Height);
- std::map<int, scene::IMesh *>::iterator it =
- m_extrusion_meshes.lower_bound(maxdim);
+ std::map<int, scene::IMesh*>::iterator
+ it = m_extrusion_meshes.lower_bound(maxdim);
if (it == m_extrusion_meshes.end()) {
// no viable resolution found; use largest one
@@ -179,23 +179,24 @@ public:
}
// Returns a 1x1x1 cube mesh with one meshbuffer (material) per face
// Caller must drop the returned pointer
- scene::IMesh *createCube()
+ scene::IMesh* createCube()
{
m_cube->grab();
return m_cube;
}
private:
- std::map<int, scene::IMesh *> m_extrusion_meshes;
+ std::map<int, scene::IMesh*> m_extrusion_meshes;
scene::IMesh *m_cube;
};
ExtrusionMeshCache *g_extrusion_mesh_cache = NULL;
-WieldMeshSceneNode::WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id, bool lighting) :
- scene::ISceneNode(mgr->getRootSceneNode(), mgr, id),
- m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF),
- m_lighting(lighting)
+
+WieldMeshSceneNode::WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id, bool lighting):
+ scene::ISceneNode(mgr->getRootSceneNode(), mgr, id),
+ m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF),
+ m_lighting(lighting)
{
m_enable_shaders = g_settings->getBool("enable_shaders");
m_anisotropic_filter = g_settings->getBool("anisotropic_filter");
@@ -228,7 +229,8 @@ WieldMeshSceneNode::~WieldMeshSceneNode()
g_extrusion_mesh_cache = nullptr;
}
-void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale)
+void WieldMeshSceneNode::setCube(const ContentFeatures &f,
+ v3f wield_scale)
{
scene::IMesh *cubemesh = g_extrusion_mesh_cache->createCube();
scene::SMesh *copy = cloneMesh(cubemesh);
@@ -240,8 +242,8 @@ void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale)
}
void WieldMeshSceneNode::setExtruded(const std::string &imagename,
- const std::string &overlay_name, v3f wield_scale, ITextureSource *tsrc,
- u8 num_frames)
+ const std::string &overlay_name, v3f wield_scale, ITextureSource *tsrc,
+ u8 num_frames)
{
video::ITexture *texture = tsrc->getTexture(imagename);
if (!texture) {
@@ -249,7 +251,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename,
return;
}
video::ITexture *overlay_texture =
- overlay_name.empty() ? NULL : tsrc->getTexture(overlay_name);
+ overlay_name.empty() ? NULL : tsrc->getTexture(overlay_name);
core::dimension2d<u32> dim = texture->getSize();
// Detect animation texture and pull off top frame instead of using entire thing
@@ -260,8 +262,9 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename,
scene::IMesh *original = g_extrusion_mesh_cache->create(dim);
scene::SMesh *mesh = cloneMesh(original);
original->drop();
- // set texture
- mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename));
+ //set texture
+ mesh->getMeshBuffer(0)->getMaterial().setTexture(0,
+ tsrc->getTexture(imagename));
if (overlay_texture) {
scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0));
copy->getMaterial().setTexture(0, overlay_texture);
@@ -291,8 +294,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename,
}
material.setFlag(video::EMF_ANISOTROPIC_FILTER, m_anisotropic_filter);
// mipmaps cause "thin black line" artifacts
-#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || \
- IRRLICHT_VERSION_MAJOR >= 2
+#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
material.setFlag(video::EMF_USE_MIP_MAPS, false);
#endif
if (m_enable_shaders) {
@@ -301,8 +303,7 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename,
}
}
-scene::SMesh *createSpecialNodeMesh(
- Client *client, content_t id, std::vector<ItemPartColor> *colors)
+scene::SMesh *createSpecialNodeMesh(Client *client, content_t id, std::vector<ItemPartColor> *colors)
{
MeshMakeData mesh_make_data(client, false, false);
MeshCollector collector;
@@ -324,17 +325,16 @@ scene::SMesh *createSpecialNodeMesh(
buf->Material.setTexture(0, p.layer.texture);
p.layer.applyMaterialOptions(buf->Material);
mesh->addMeshBuffer(buf);
- buf->append(&p.vertices[0], p.vertices.size(), &p.indices[0],
- p.indices.size());
+ buf->append(&p.vertices[0], p.vertices.size(),
+ &p.indices[0], p.indices.size());
buf->drop();
colors->push_back(
- ItemPartColor(p.layer.has_color, p.layer.color));
+ ItemPartColor(p.layer.has_color, p.layer.color));
}
return mesh;
}
-void WieldMeshSceneNode::setItem(
- const ItemStack &item, Client *client, bool check_wield_image)
+void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool check_wield_image)
{
ITextureSource *tsrc = client->getTextureSource();
IItemDefManager *idef = client->getItemDefManager();
@@ -347,8 +347,7 @@ void WieldMeshSceneNode::setItem(
scene::SMesh *mesh = nullptr;
if (m_enable_shaders) {
- u32 shader_id = shdrsrc->getShader(
- "object_shader", TILE_MATERIAL_BASIC, NDT_NORMAL);
+ u32 shader_id = shdrsrc->getShader("object_shader", TILE_MATERIAL_BASIC, NDT_NORMAL);
m_material_type = shdrsrc->getShaderInfo(shader_id).material;
}
@@ -358,7 +357,8 @@ void WieldMeshSceneNode::setItem(
// If wield_image needs to be checked and is defined, it overrides everything else
if (!def.wield_image.empty() && check_wield_image) {
- setExtruded(def.wield_image, def.wield_overlay, def.wield_scale, tsrc, 1);
+ setExtruded(def.wield_image, def.wield_overlay, def.wield_scale, tsrc,
+ 1);
m_colors.emplace_back();
// overlay is white, if present
m_colors.emplace_back(true, video::SColor(0xFFFFFFFF));
@@ -372,64 +372,55 @@ void WieldMeshSceneNode::setItem(
// e.g. mesh nodes and nodeboxes
mesh = cloneMesh(f.mesh_ptr[0]);
postProcessNodeMesh(mesh, f, m_enable_shaders, true,
- &m_material_type, &m_colors);
+ &m_material_type, &m_colors);
changeToMesh(mesh);
mesh->drop();
// mesh is pre-scaled by BS * f->visual_scale
- m_meshnode->setScale(def.wield_scale * WIELD_SCALE_FACTOR /
- (BS * f.visual_scale));
+ m_meshnode->setScale(
+ def.wield_scale * WIELD_SCALE_FACTOR
+ / (BS * f.visual_scale));
} else {
switch (f.drawtype) {
- case NDT_AIRLIKE: {
- changeToMesh(nullptr);
- break;
- }
- case NDT_PLANTLIKE: {
- setExtruded(tsrc->getTextureName(
- f.tiles[0].layers[0]
- .texture_id),
- tsrc->getTextureName(
- f.tiles[0].layers[1]
- .texture_id),
+ case NDT_AIRLIKE: {
+ changeToMesh(nullptr);
+ break;
+ }
+ case NDT_PLANTLIKE: {
+ setExtruded(tsrc->getTextureName(f.tiles[0].layers[0].texture_id),
+ tsrc->getTextureName(f.tiles[0].layers[1].texture_id),
def.wield_scale, tsrc,
- f.tiles[0].layers[0]
- .animation_frame_count);
- // Add color
- const TileLayer &l0 = f.tiles[0].layers[0];
- m_colors.emplace_back(l0.has_color, l0.color);
- const TileLayer &l1 = f.tiles[0].layers[1];
- m_colors.emplace_back(l1.has_color, l1.color);
- break;
- }
- case NDT_PLANTLIKE_ROOTED: {
- setExtruded(tsrc->getTextureName(
- f.special_tiles[0]
- .layers[0]
- .texture_id),
+ f.tiles[0].layers[0].animation_frame_count);
+ // Add color
+ const TileLayer &l0 = f.tiles[0].layers[0];
+ m_colors.emplace_back(l0.has_color, l0.color);
+ const TileLayer &l1 = f.tiles[0].layers[1];
+ m_colors.emplace_back(l1.has_color, l1.color);
+ break;
+ }
+ case NDT_PLANTLIKE_ROOTED: {
+ setExtruded(tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id),
"", def.wield_scale, tsrc,
- f.special_tiles[0]
- .layers[0]
- .animation_frame_count);
- // Add color
- const TileLayer &l0 = f.special_tiles[0].layers[0];
- m_colors.emplace_back(l0.has_color, l0.color);
- break;
- }
- case NDT_NORMAL:
- case NDT_ALLFACES:
- case NDT_LIQUID:
- case NDT_FLOWINGLIQUID: {
- setCube(f, def.wield_scale);
- break;
- }
- default: {
- mesh = createSpecialNodeMesh(client, id, &m_colors);
- changeToMesh(mesh);
- mesh->drop();
- m_meshnode->setScale(def.wield_scale *
- WIELD_SCALE_FACTOR /
- (BS * f.visual_scale));
- }
+ f.special_tiles[0].layers[0].animation_frame_count);
+ // Add color
+ const TileLayer &l0 = f.special_tiles[0].layers[0];
+ m_colors.emplace_back(l0.has_color, l0.color);
+ break;
+ }
+ case NDT_NORMAL:
+ case NDT_ALLFACES:
+ case NDT_LIQUID:
+ case NDT_FLOWINGLIQUID: {
+ setCube(f, def.wield_scale);
+ break;
+ }
+ default: {
+ mesh = createSpecialNodeMesh(client, id, &m_colors);
+ changeToMesh(mesh);
+ mesh->drop();
+ m_meshnode->setScale(
+ def.wield_scale * WIELD_SCALE_FACTOR
+ / (BS * f.visual_scale));
+ }
}
}
u32 material_count = m_meshnode->getMaterialCount();
@@ -442,9 +433,10 @@ void WieldMeshSceneNode::setItem(
material.setFlag(video::EMF_TRILINEAR_FILTER, m_trilinear_filter);
}
return;
- } else if (!def.inventory_image.empty()) {
+ }
+ else if (!def.inventory_image.empty()) {
setExtruded(def.inventory_image, def.inventory_overlay, def.wield_scale,
- tsrc, 1);
+ tsrc, 1);
m_colors.emplace_back();
// overlay is white, if present
m_colors.emplace_back(true, video::SColor(0xFFFFFFFF));
@@ -470,8 +462,10 @@ void WieldMeshSceneNode::setColor(video::SColor c)
video::SColor bc(m_base_color);
if ((m_colors.size() > j) && (m_colors[j].override_base))
bc = m_colors[j].color;
- video::SColor buffercolor(255, bc.getRed() * red / 255,
- bc.getGreen() * green / 255, bc.getBlue() * blue / 255);
+ video::SColor buffercolor(255,
+ bc.getRed() * red / 255,
+ bc.getGreen() * green / 255,
+ bc.getBlue() * blue / 255);
scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
if (m_enable_shaders)
@@ -508,7 +502,7 @@ void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh)
scene::IMesh *dummymesh = g_extrusion_mesh_cache->createCube();
m_meshnode->setVisible(false);
m_meshnode->setMesh(dummymesh);
- dummymesh->drop(); // m_meshnode grabbed it
+ dummymesh->drop(); // m_meshnode grabbed it
} else {
m_meshnode->setMesh(mesh);
}
@@ -528,9 +522,8 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
const ContentFeatures &f = ndef->get(def.name);
content_t id = ndef->getId(def.name);
- FATAL_ERROR_IF(!g_extrusion_mesh_cache,
- "Extrusion mesh cache is not yet initialized");
-
+ FATAL_ERROR_IF(!g_extrusion_mesh_cache, "Extrusion mesh cache is not yet initialized");
+
scene::SMesh *mesh = nullptr;
// Shading is on by default
@@ -538,7 +531,8 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
// If inventory_image is defined, it overrides everything else
if (!def.inventory_image.empty()) {
- mesh = getExtrudedMesh(tsrc, def.inventory_image, def.inventory_overlay);
+ mesh = getExtrudedMesh(tsrc, def.inventory_image,
+ def.inventory_overlay);
result->buffer_colors.emplace_back();
// overlay is white, if present
result->buffer_colors.emplace_back(true, video::SColor(0xFFFFFFFF));
@@ -549,57 +543,45 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
mesh = cloneMesh(f.mesh_ptr[0]);
scaleMesh(mesh, v3f(0.12, 0.12, 0.12));
postProcessNodeMesh(mesh, f, false, false, nullptr,
- &result->buffer_colors);
+ &result->buffer_colors);
} else {
switch (f.drawtype) {
- case NDT_PLANTLIKE: {
- mesh = getExtrudedMesh(tsrc,
- tsrc->getTextureName(
- f.tiles[0].layers[0]
- .texture_id),
- tsrc->getTextureName(
- f.tiles[0].layers[1]
- .texture_id));
- // Add color
- const TileLayer &l0 = f.tiles[0].layers[0];
- result->buffer_colors.emplace_back(
- l0.has_color, l0.color);
- const TileLayer &l1 = f.tiles[0].layers[1];
- result->buffer_colors.emplace_back(
- l1.has_color, l1.color);
- break;
- }
- case NDT_PLANTLIKE_ROOTED: {
- mesh = getExtrudedMesh(tsrc,
- tsrc->getTextureName(
- f.special_tiles[0]
- .layers[0]
- .texture_id),
- "");
- // Add color
- const TileLayer &l0 = f.special_tiles[0].layers[0];
- result->buffer_colors.emplace_back(
- l0.has_color, l0.color);
- break;
- }
- case NDT_NORMAL:
- case NDT_ALLFACES:
- case NDT_LIQUID:
- case NDT_FLOWINGLIQUID: {
- scene::IMesh *cube = g_extrusion_mesh_cache->createCube();
- mesh = cloneMesh(cube);
- cube->drop();
- scaleMesh(mesh, v3f(1.2, 1.2, 1.2));
- // add overlays
- postProcessNodeMesh(mesh, f, false, false, nullptr,
+ case NDT_PLANTLIKE: {
+ mesh = getExtrudedMesh(tsrc,
+ tsrc->getTextureName(f.tiles[0].layers[0].texture_id),
+ tsrc->getTextureName(f.tiles[0].layers[1].texture_id));
+ // Add color
+ const TileLayer &l0 = f.tiles[0].layers[0];
+ result->buffer_colors.emplace_back(l0.has_color, l0.color);
+ const TileLayer &l1 = f.tiles[0].layers[1];
+ result->buffer_colors.emplace_back(l1.has_color, l1.color);
+ break;
+ }
+ case NDT_PLANTLIKE_ROOTED: {
+ mesh = getExtrudedMesh(tsrc,
+ tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id), "");
+ // Add color
+ const TileLayer &l0 = f.special_tiles[0].layers[0];
+ result->buffer_colors.emplace_back(l0.has_color, l0.color);
+ break;
+ }
+ case NDT_NORMAL:
+ case NDT_ALLFACES:
+ case NDT_LIQUID:
+ case NDT_FLOWINGLIQUID: {
+ scene::IMesh *cube = g_extrusion_mesh_cache->createCube();
+ mesh = cloneMesh(cube);
+ cube->drop();
+ scaleMesh(mesh, v3f(1.2, 1.2, 1.2));
+ // add overlays
+ postProcessNodeMesh(mesh, f, false, false, nullptr,
&result->buffer_colors);
- break;
- }
- default: {
- mesh = createSpecialNodeMesh(
- client, id, &result->buffer_colors);
- scaleMesh(mesh, v3f(0.12, 0.12, 0.12));
- }
+ break;
+ }
+ default: {
+ mesh = createSpecialNodeMesh(client, id, &result->buffer_colors);
+ scaleMesh(mesh, v3f(0.12, 0.12, 0.12));
+ }
}
}
@@ -621,8 +603,10 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
result->mesh = mesh;
}
-scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename,
- const std::string &overlay_name)
+
+
+scene::SMesh *getExtrudedMesh(ITextureSource *tsrc,
+ const std::string &imagename, const std::string &overlay_name)
{
// check textures
video::ITexture *texture = tsrc->getTextureForMesh(imagename);
@@ -630,7 +614,7 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
return NULL;
}
video::ITexture *overlay_texture =
- (overlay_name.empty()) ? NULL : tsrc->getTexture(overlay_name);
+ (overlay_name.empty()) ? NULL : tsrc->getTexture(overlay_name);
// get mesh
core::dimension2d<u32> dim = texture->getSize();
@@ -638,8 +622,9 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
scene::SMesh *mesh = cloneMesh(original);
original->drop();
- // set texture
- mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename));
+ //set texture
+ mesh->getMeshBuffer(0)->getMaterial().setTexture(0,
+ tsrc->getTexture(imagename));
if (overlay_texture) {
scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0));
copy->getMaterial().setTexture(0, overlay_texture);
@@ -663,9 +648,9 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
return mesh;
}
-void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders,
- bool set_material, const video::E_MATERIAL_TYPE *mattype,
- std::vector<ItemPartColor> *colors, bool apply_scale)
+void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f,
+ bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype,
+ std::vector<ItemPartColor> *colors, bool apply_scale)
{
u32 mc = mesh->getMeshBufferCount();
// Allocate colors for existing buffers
@@ -686,11 +671,10 @@ void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_
mesh->addMeshBuffer(copy);
copy->drop();
buf = copy;
- colors->push_back(ItemPartColor(
- layer->has_color, layer->color));
+ colors->push_back(
+ ItemPartColor(layer->has_color, layer->color));
} else {
- (*colors)[i] = ItemPartColor(
- layer->has_color, layer->color);
+ (*colors)[i] = ItemPartColor(layer->has_color, layer->color);
}
video::SMaterial &material = buf->getMaterial();
if (set_material)
@@ -707,13 +691,10 @@ void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_
if (use_shaders) {
if (layer->normal_texture) {
if (layer->animation_frame_count > 1) {
- const FrameSpec &animation_frame =
- (*layer->frames)[0];
- material.setTexture(1,
- animation_frame.normal_texture);
+ const FrameSpec &animation_frame = (*layer->frames)[0];
+ material.setTexture(1, animation_frame.normal_texture);
} else
- material.setTexture(
- 1, layer->normal_texture);
+ material.setTexture(1, layer->normal_texture);
}
material.setTexture(2, layer->flags_texture);
}