Modernize source code: last part (#6285)

* Modernize source code: last par

* Use empty when needed
* Use emplace_back instead of push_back when needed
* For range-based loops
* Initializers fixes
* constructors, destructors default
* c++ C stl includes
This commit is contained in:
Loïc Blot 2017-08-20 13:30:50 +02:00 committed by GitHub
parent 50669cd282
commit 1c1c97cbd1
72 changed files with 446 additions and 584 deletions

@ -35,7 +35,7 @@ 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):
const v3f &a_nametag_pos):
parent_node(a_parent_node),
nametag_text(a_nametag_text),
nametag_color(a_nametag_color),

@ -365,8 +365,8 @@ s32 ChatBuffer::getBottomScrollPos() const
s32 rows = (s32) m_rows;
if (rows == 0)
return 0;
else
return formatted_count - rows;
return formatted_count - rows;
}

@ -35,7 +35,7 @@ public:
void savePlayer(RemotePlayer *player) {}
bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) { return true; }
bool removePlayer(const std::string &name) { return true; }
void listPlayers(std::vector<std::string> &) {}
void listPlayers(std::vector<std::string> &res) {}
void beginSave() {}
void endSave() {}

@ -29,10 +29,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define BLOCK_EMERGE_ALLOW_GEN (1 << 0)
#define BLOCK_EMERGE_FORCE_QUEUE (1 << 1)
#define EMERGE_DBG_OUT(x) do { \
#define EMERGE_DBG_OUT(x) { \
if (enable_mapgen_debug_info) \
infostream << "EmergeThread: " x << std::endl; \
} while (0)
}
class EmergeThread;
class INodeDefManager;

@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
class MtEvent
{
public:
virtual ~MtEvent() {};
virtual ~MtEvent() = default;
//virtual MtEvent* clone(){ return new IEvent; }
virtual const char* getType() const = 0;
@ -49,7 +49,7 @@ public:
class MtEventReceiver
{
public:
virtual ~MtEventReceiver(){};
virtual ~MtEventReceiver() = default;
virtual void onEvent(MtEvent *e) = 0;
};
@ -58,7 +58,7 @@ typedef void (*event_receive_func)(MtEvent *e, void *data);
class MtEventManager
{
public:
virtual ~MtEventManager(){};
virtual ~MtEventManager() = default;
virtual void put(MtEvent *e) = 0;
virtual void reg(const char *type, event_receive_func f, void *data) = 0;
// If data==NULL, every occurence of f is deregistered.

@ -43,17 +43,15 @@ class EventManager: public MtEventManager
std::map<std::string, Dest> m_dest;
public:
~EventManager()
{
}
~EventManager() = default;
void put(MtEvent *e)
{
std::map<std::string, Dest>::iterator i = m_dest.find(e->getType());
if(i != m_dest.end()){
std::list<FuncSpec> &funcs = i->second.funcs;
for(std::list<FuncSpec>::iterator i = funcs.begin();
i != funcs.end(); ++i){
(*(i->f))(e, i->d);
for (FuncSpec &func : funcs) {
(*(func.f))(e, func.d);
}
}
delete e;
@ -62,11 +60,11 @@ public:
{
std::map<std::string, Dest>::iterator i = m_dest.find(type);
if(i != m_dest.end()){
i->second.funcs.push_back(FuncSpec(f, data));
i->second.funcs.emplace_back(f, data);
} else{
std::list<FuncSpec> funcs;
Dest dest;
dest.funcs.push_back(FuncSpec(f, data));
dest.funcs.emplace_back(f, data);
m_dest[type] = dest;
}
}
@ -86,9 +84,8 @@ public:
}
}
} else{
for(std::map<std::string, Dest>::iterator
i = m_dest.begin(); i != m_dest.end(); ++i){
std::list<FuncSpec> &funcs = i->second.funcs;
for (auto &dest : m_dest) {
std::list<FuncSpec> &funcs = dest.second.funcs;
std::list<FuncSpec>::iterator j = funcs.begin();
while(j != funcs.end()){
bool remove = (j->f == f && (!data || j->d == data));

@ -27,7 +27,8 @@ class BaseException : public std::exception
{
public:
BaseException(const std::string &s) throw(): m_s(s) {}
~BaseException() throw() {}
~BaseException() throw() = default;
virtual const char * what() const throw()
{
return m_s.c_str();

@ -69,8 +69,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "sound_openal.h"
#endif
extern Settings *g_settings;
extern Profiler *g_profiler;
/*
Text input system
@ -248,7 +246,7 @@ void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
setStaticText(guitext_profiler, text.c_str());
guitext_profiler->setVisible(true);
s32 w = fe->getTextWidth(text.c_str());
s32 w = fe->getTextWidth(text);
if (w < 400)
w = 400;
@ -291,11 +289,9 @@ private:
};
std::deque<Piece> m_log;
public:
u32 m_log_max_size;
u32 m_log_max_size = 200;
ProfilerGraph():
m_log_max_size(200)
{}
ProfilerGraph() = default;
void put(const Profiler::GraphValues &values)
{
@ -314,14 +310,10 @@ public:
// to be the same for each call to prevent flickering
std::map<std::string, Meta> m_meta;
for (std::deque<Piece>::const_iterator k = m_log.begin();
k != m_log.end(); ++k) {
const Piece &piece = *k;
for (Profiler::GraphValues::const_iterator i = piece.values.begin();
i != piece.values.end(); ++i) {
const std::string &id = i->first;
const float &value = i->second;
for (const Piece &piece : m_log) {
for (const auto &i : piece.values) {
const std::string &id = i.first;
const float &value = i.second;
std::map<std::string, Meta>::iterator j = m_meta.find(id);
if (j == m_meta.end()) {
@ -349,9 +341,8 @@ public:
sizeof(usable_colors) / sizeof(*usable_colors);
u32 next_color_i = 0;
for (std::map<std::string, Meta>::iterator i = m_meta.begin();
i != m_meta.end(); ++i) {
Meta &meta = i->second;
for (auto &i : m_meta) {
Meta &meta = i.second;
video::SColor color(255, 200, 200, 200);
if (next_color_i < usable_colors_count)
@ -401,9 +392,7 @@ public:
float lastscaledvalue = 0.0;
bool lastscaledvalue_exists = false;
for (std::deque<Piece>::const_iterator j = m_log.begin();
j != m_log.end(); ++j) {
const Piece &piece = *j;
for (const Piece &piece : m_log) {
float value = 0;
bool value_exists = false;
Profiler::GraphValues::const_iterator k =
@ -763,8 +752,8 @@ public:
void setSky(Sky *sky) {
m_sky = sky;
for (size_t i = 0; i < created_nosky.size(); ++i) {
created_nosky[i]->setSky(m_sky);
for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
ggscs->setSky(m_sky);
}
created_nosky.clear();
}
@ -793,7 +782,7 @@ bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_de
if (!is_valid_position)
return false;
if (prediction != "" && !nodedef->get(node).rightclickable) {
if (!prediction.empty() && !nodedef->get(node).rightclickable) {
verbosestream << "Node placement prediction for "
<< playeritem_def.name << " is "
<< prediction << std::endl;
@ -978,7 +967,7 @@ static void updateChat(Client &client, f32 dtime, bool show_debug,
}
// Get new messages from client
std::wstring message = L"";
std::wstring message;
while (client.getChatMessage(message)) {
chat_backend.addUnparsedMessage(message);
}
@ -1116,8 +1105,8 @@ void KeyCache::populate()
if (handler) {
// First clear all keys, then re-add the ones we listen for
handler->dontListenForKeys();
for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
handler->listenForKey(key[i]);
for (const KeyPress &k : key) {
handler->listenForKey(k);
}
handler->listenForKey(EscapeKey);
handler->listenForKey(CancelKey);
@ -1384,7 +1373,7 @@ private:
GameOnDemandSoundFetcher soundfetcher; // useful when testing
ISoundManager *sound;
bool sound_is_dummy;
bool sound_is_dummy = false;
SoundMaker *soundmaker;
ChatBackend *chat_backend;
@ -1464,9 +1453,9 @@ private:
f32 m_cache_cam_smoothing;
f32 m_cache_fog_start;
bool m_invert_mouse;
bool m_first_loop_after_window_activation;
bool m_camera_offset_changed;
bool m_invert_mouse = false;
bool m_first_loop_after_window_activation = false;
bool m_camera_offset_changed = false;
#ifdef __ANDROID__
bool m_cache_hold_aux1;
@ -1482,7 +1471,6 @@ Game::Game() :
itemdef_manager(NULL),
nodedef_manager(NULL),
sound(NULL),
sound_is_dummy(false),
soundmaker(NULL),
chat_backend(NULL),
current_formspec(NULL),
@ -1496,10 +1484,7 @@ Game::Game() :
sky(NULL),
local_inventory(NULL),
hud(NULL),
mapper(NULL),
m_invert_mouse(false),
m_first_loop_after_window_activation(false),
m_camera_offset_changed(false)
mapper(NULL)
{
g_settings->registerChangedCallback("doubletap_jump",
&settingChangedCallback, this);
@ -1806,7 +1791,7 @@ bool Game::init(
return false;
// Create a server if not connecting to an existing one
if (*address == "") {
if (address->empty()) {
if (!createSingleplayerServer(map_dir, gamespec, port, address))
return false;
}
@ -2168,7 +2153,7 @@ bool Game::connectToServer(const std::string &playername,
wait_time += dtime;
// Only time out if we aren't waiting for the server we started
if ((*address != "") && (wait_time > 10)) {
if ((!address->empty()) && (wait_time > 10)) {
bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
// If no pre v25 init was sent, and no answer was received,
// but the low level connection could be established
@ -3175,8 +3160,9 @@ void Game::processClientEvents(CameraOrientation *cam)
break;
case CE_SHOW_FORMSPEC:
if (*(event.show_formspec.formspec) == "") {
if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
if (event.show_formspec.formspec->empty()) {
if (current_formspec && (event.show_formspec.formname->empty()
|| *(event.show_formspec.formname) == cur_formname)) {
current_formspec->quitMenu();
}
} else {
@ -3713,7 +3699,7 @@ PointedThing Game::updatePointedThing(
}
// Update selection mesh light level and vertex colors
if (selectionboxes->size() > 0) {
if (!selectionboxes->empty()) {
v3f pf = hud->getSelectionPos();
v3s16 p = floatToInt(pf, BS);
@ -3722,8 +3708,8 @@ PointedThing Game::updatePointedThing(
u16 node_light = getInteriorLight(n, -1, nodedef);
u16 light_level = node_light;
for (u8 i = 0; i < 6; i++) {
n = map.getNodeNoEx(p + g_6dirs[i]);
for (const v3s16 &dir : g_6dirs) {
n = map.getNodeNoEx(p + dir);
node_light = getInteriorLight(n, -1, nodedef);
if (node_light > light_level)
light_level = node_light;
@ -3797,7 +3783,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
runData.repeat_rightclick_timer = 0;
infostream << "Ground right-clicked" << std::endl;
if (meta && meta->getString("formspec") != "" && !random_input
if (meta && !meta->getString("formspec").empty() && !random_input
&& !isKeyDown(KeyType::SNEAK)) {
// Report right click to server
if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
@ -3842,7 +3828,7 @@ void Game::handlePointingAtNode(const PointedThing &pointed,
soundmaker->m_player_rightpunch_sound =
SimpleSoundSpec();
if (playeritem_def.node_placement_prediction == "" ||
if (playeritem_def.node_placement_prediction.empty() ||
nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
client->interact(3, pointed); // Report to server
} else {
@ -3862,7 +3848,7 @@ void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &
utf8_to_wide(runData.selected_object->infoText()));
if (show_debug) {
if (infotext != L"") {
if (!infotext.empty()) {
infotext += L"\n";
}
infotext += unescape_enriched(utf8_to_wide(
@ -3973,7 +3959,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
if (sound_dig.exists() && params.diggable) {
if (sound_dig.name == "__group") {
if (params.main_group != "") {
if (!params.main_group.empty()) {
soundmaker->m_player_leftpunch_sound.gain = 0.5;
soundmaker->m_player_leftpunch_sound.name =
std::string("default_dig_") +
@ -4649,7 +4635,7 @@ void Game::showPauseMenu()
static const std::string mode = strgettext("- Mode: ");
if (!simple_singleplayer_mode) {
Address serverAddress = client->getServerAddress();
if (address != "") {
if (!address.empty()) {
os << mode << strgettext("Remote server") << "\n"
<< strgettext("- Address: ") << address;
} else {
@ -4659,7 +4645,7 @@ void Game::showPauseMenu()
} else {
os << mode << strgettext("Singleplayer") << "\n";
}
if (simple_singleplayer_mode || address == "") {
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;
@ -4673,7 +4659,7 @@ void Game::showPauseMenu()
<< strgettext("- Public: ") << announced << "\n";
std::string server_name = g_settings->get("server_name");
str_formspec_escape(server_name);
if (announced == on && server_name != "")
if (announced == on && !server_name.empty())
os << strgettext("- Server Name: ") << server_name;
}

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#pragma once
#include "irrlichttypes.h"
#include <time.h>
#include <ctime>
#include <string>
enum TimePrecision

@ -100,8 +100,9 @@ private:
class IItemDefManager
{
public:
IItemDefManager(){}
virtual ~IItemDefManager(){}
IItemDefManager() = default;
virtual ~IItemDefManager() = default;
// Get item definition
virtual const ItemDefinition& get(const std::string &name) const=0;
@ -133,8 +134,9 @@ public:
class IWritableItemDefManager : public IItemDefManager
{
public:
IWritableItemDefManager(){}
virtual ~IWritableItemDefManager(){}
IWritableItemDefManager() = default;
virtual ~IWritableItemDefManager() = default;
// Get item definition
virtual const ItemDefinition& get(const std::string &name) const=0;

@ -352,8 +352,8 @@ static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
std::string name = worldspec.name;
std::string path = worldspec.path;
if (name.find(' ') != std::string::npos)
name = std::string("'") + name + "'";
path = std::string("'") + path + "'";
name = std::string("'").append(name).append("'");
path = std::string("'").append(path).append("'");
name = padStringRight(name, 14);
os << " " << name << " " << path << std::endl;
}

@ -48,9 +48,11 @@ class MainMenuManager : public IMenuManager
public:
virtual void createdMenu(gui::IGUIElement *menu)
{
#ifndef NDEBUG
for (gui::IGUIElement *i : m_stack) {
assert(i != menu);
}
#endif
if(!m_stack.empty())
m_stack.back()->setVisible(false);

@ -431,12 +431,11 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox,
boxes_size += nodebox.connect_right.size();
boxes.reserve(boxes_size);
#define BOXESPUSHBACK(c) do { \
#define BOXESPUSHBACK(c) \
for (std::vector<aabb3f>::const_iterator \
it = (c).begin(); \
it != (c).end(); ++it) \
(boxes).push_back(*it); \
} while (0)
(boxes).push_back(*it);
BOXESPUSHBACK(nodebox.fixed);

@ -1281,7 +1281,7 @@ bool ConnectionSendThread::packetsQueued()
continue;
for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
if (channel.queued_commands.size() > 0) {
if (!channel.queued_commands.empty()) {
return true;
}
}

@ -604,7 +604,7 @@ public:
class PeerHelper
{
public:
PeerHelper() = default;;
PeerHelper() = default;
PeerHelper(Peer* peer);
~PeerHelper();

@ -91,7 +91,7 @@ void read_item_definition(lua_State* L, int index,
// If name is "" (hand), ensure there are ToolCapabilities
// because it will be looked up there whenever any other item has
// no ToolCapabilities
if(def.name == "" && def.tool_capabilities == NULL){
if (def.name.empty() && def.tool_capabilities == NULL){
def.tool_capabilities = new ToolCapabilities();
}
@ -212,9 +212,9 @@ void read_object_properties(lua_State *L, int index,
while(lua_next(L, table) != 0){
// key at index -2 and value at index -1
if(lua_isstring(L, -1))
prop->textures.push_back(lua_tostring(L, -1));
prop->textures.emplace_back(lua_tostring(L, -1));
else
prop->textures.push_back("");
prop->textures.emplace_back("");
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
@ -303,18 +303,16 @@ void push_object_properties(lua_State *L, ObjectProperties *prop)
lua_newtable(L);
u16 i = 1;
for (std::vector<std::string>::iterator it = prop->textures.begin();
it != prop->textures.end(); ++it) {
lua_pushlstring(L, it->c_str(), it->size());
for (const std::string &texture : prop->textures) {
lua_pushlstring(L, texture.c_str(), texture.size());
lua_rawseti(L, -2, i);
}
lua_setfield(L, -2, "textures");
lua_newtable(L);
i = 1;
for (std::vector<video::SColor>::iterator it = prop->colors.begin();
it != prop->colors.end(); ++it) {
push_ARGB8(L, *it);
for (const video::SColor &color : prop->colors) {
push_ARGB8(L, color);
lua_rawseti(L, -2, i);
}
lua_setfield(L, -2, "colors");
@ -564,7 +562,7 @@ ContentFeatures read_content_features(lua_State *L, int index)
f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
ScriptApiNode::es_ContentParamType2, CPT2_NONE);
if (f.palette_name != "" &&
if (!f.palette_name.empty() &&
!(f.param_type_2 == CPT2_COLOR ||
f.param_type_2 == CPT2_COLORED_FACEDIR ||
f.param_type_2 == CPT2_COLORED_WALLMOUNTED))
@ -646,7 +644,7 @@ ContentFeatures read_content_features(lua_State *L, int index)
lua_pushnil(L);
while (lua_next(L, table) != 0) {
// Value at -1
f.connects_to.push_back(lua_tostring(L, -1));
f.connects_to.emplace_back(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
@ -771,9 +769,8 @@ void push_content_features(lua_State *L, const ContentFeatures &c)
lua_newtable(L);
u16 i = 1;
for (std::vector<std::string>::const_iterator it = c.connects_to.begin();
it != c.connects_to.end(); ++it) {
lua_pushlstring(L, it->c_str(), it->size());
for (const std::string &it : c.connects_to) {
lua_pushlstring(L, it.c_str(), it.size());
lua_rawseti(L, -2, i);
}
lua_setfield(L, -2, "connects_to");
@ -893,9 +890,8 @@ void push_box(lua_State *L, const std::vector<aabb3f> &box)
{
lua_newtable(L);
u8 i = 1;
for (std::vector<aabb3f>::const_iterator it = box.begin();
it != box.end(); ++it) {
push_aabb3f(L, (*it));
for (const aabb3f &it : box) {
push_aabb3f(L, it);
lua_rawseti(L, -2, i);
}
}
@ -987,21 +983,19 @@ NodeBox read_nodebox(lua_State *L, int index)
nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
#define NODEBOXREAD(n, s) \
do { \
#define NODEBOXREAD(n, s){ \
lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \
(n) = read_aabb3f(L, -1, BS); \
lua_pop(L, 1); \
} while (0)
}
#define NODEBOXREADVEC(n, s) \
do { \
lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \
(n) = read_aabb3f_vector(L, -1, BS); \
lua_pop(L, 1); \
} while (0)
lua_pop(L, 1);
NODEBOXREADVEC(nodebox.fixed, "fixed");
NODEBOXREAD(nodebox.wall_top, "wall_top");
NODEBOXREAD(nodebox.wall_bottom, "wall_bottom");
@ -1037,7 +1031,7 @@ MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
param2 = lua_tonumber(L, -1);
lua_pop(L, 1);
return MapNode(ndef, name, param1, param2);
return {ndef, name, param1, param2};
}
/******************************************************************************/
@ -1096,18 +1090,17 @@ ItemStack read_item(lua_State* L, int index, IItemDefManager *idef)
if(index < 0)
index = lua_gettop(L) + 1 + index;
if(lua_isnil(L, index))
{
if (lua_isnil(L, index)) {
return ItemStack();
}
else if(lua_isuserdata(L, index))
{
if (lua_isuserdata(L, index)) {
// Convert from LuaItemStack
LuaItemStack *o = LuaItemStack::checkobject(L, index);
return o->getItem();
}
else if(lua_isstring(L, index))
{
if (lua_isstring(L, index)) {
// Convert from itemstring
std::string itemstring = lua_tostring(L, index);
try
@ -1168,18 +1161,16 @@ void push_tool_capabilities(lua_State *L,
// Create groupcaps table
lua_newtable(L);
// For each groupcap
for (ToolGCMap::const_iterator i = toolcap.groupcaps.begin();
i != toolcap.groupcaps.end(); ++i) {
for (const auto &gc_it : toolcap.groupcaps) {
// Create groupcap table
lua_newtable(L);
const std::string &name = i->first;
const ToolGroupCap &groupcap = i->second;
const std::string &name = gc_it.first;
const ToolGroupCap &groupcap = gc_it.second;
// Create subtable "times"
lua_newtable(L);
for (std::unordered_map<int, float>::const_iterator
i = groupcap.times.begin(); i != groupcap.times.end(); ++i) {
lua_pushinteger(L, i->first);
lua_pushnumber(L, i->second);
for (auto time : groupcap.times) {
lua_pushinteger(L, time.first);
lua_pushnumber(L, time.second);
lua_settable(L, -3);
}
// Set subtable "times"
@ -1195,11 +1186,10 @@ void push_tool_capabilities(lua_State *L,
//Create damage_groups table
lua_newtable(L);
// For each damage group
for (DamageGroup::const_iterator i = toolcap.damageGroups.begin();
i != toolcap.damageGroups.end(); ++i) {
for (const auto &damageGroup : toolcap.damageGroups) {
// Create damage group table
lua_pushinteger(L, i->second);
lua_setfield(L, -2, i->first.c_str());
lua_pushinteger(L, damageGroup.second);
lua_setfield(L, -2, damageGroup.first.c_str());
}
lua_setfield(L, -2, "damage_groups");
}
@ -1459,9 +1449,9 @@ void read_groups(lua_State *L, int index, ItemGroupList &result)
void push_groups(lua_State *L, const ItemGroupList &groups)
{
lua_newtable(L);
for (ItemGroupList::const_iterator it = groups.begin(); it != groups.end(); ++it) {
lua_pushnumber(L, it->second);
lua_setfield(L, -2, it->first.c_str());
for (const auto &group : groups) {
lua_pushnumber(L, group.second);
lua_setfield(L, -2, group.first.c_str());
}
}
@ -1572,9 +1562,8 @@ static int push_json_value_getdepth(const Json::Value &value)
return 1;
int maxdepth = 0;
for (Json::Value::const_iterator it = value.begin();
it != value.end(); ++it) {
int elemdepth = push_json_value_getdepth(*it);
for (const auto &it : value) {
int elemdepth = push_json_value_getdepth(it);
if (elemdepth > maxdepth)
maxdepth = elemdepth;
}
@ -1646,8 +1635,8 @@ bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
// of push_json_value_helper is 2, so make sure there a depth * 2 slots
if (lua_checkstack(L, depth * 2))
return push_json_value_helper(L, value, nullindex);
else
return false;
return false;
}
// Converts Lua table --> JSON

@ -123,7 +123,6 @@ MapNode readnode (lua_State *L, int index,
void pushnode (lua_State *L, const MapNode &n,
INodeDefManager *ndef);
NodeBox read_nodebox (lua_State *L, int index);
void read_groups (lua_State *L, int index,
ItemGroupList &result);
@ -159,9 +158,6 @@ std::vector<ItemStack> read_items (lua_State *L,
int index,
Server* srv);
void read_soundspec (lua_State *L,
int index,
SimpleSoundSpec &spec);
void push_soundspec (lua_State *L,
const SimpleSoundSpec &spec);

@ -30,7 +30,7 @@ extern "C" {
#include "constants.h"
#define CHECK_TYPE(index, name, type) do { \
#define CHECK_TYPE(index, name, type) { \
int t = lua_type(L, (index)); \
if (t != (type)) { \
std::string traceback = script_get_backtrace(L); \
@ -38,7 +38,7 @@ extern "C" {
" (expected " + lua_typename(L, (type)) + \
" got " + lua_typename(L, t) + ").\n" + traceback); \
} \
} while(0)
}
#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER)
#define CHECK_FLOAT_RANGE(value, name) \
if (value < F1000_MIN || value > F1000_MAX) { \

@ -76,8 +76,6 @@ void setfloatfield(lua_State *L, int table,
const char *fieldname, float value);
void setboolfield(lua_State *L, int table,
const char *fieldname, bool value);
void setstringfield(lua_State *L, int table,
const char *fieldname, const char *value);
v3f checkFloatPos (lua_State *L, int index);
v2f check_v2f (lua_State *L, int index);

@ -58,12 +58,12 @@ extern "C" {
#define PUSH_ERROR_HANDLER(L) \
(lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L)))
#define PCALL_RESL(L, RES) do { \
#define PCALL_RESL(L, RES) { \
int result_ = (RES); \
if (result_ != 0) { \
script_error((L), result_, NULL, __FUNCTION__); \
} \
} while (0)
}
#define script_run_callbacks(L, nargs, mode) \
script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__)

@ -17,8 +17,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <cstdlib>
extern "C" {
#include "lua.h"
@ -38,9 +38,8 @@ AsyncEngine::~AsyncEngine()
{
// Request all threads to stop
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
it != workerThreads.end(); ++it) {
(*it)->stop();
for (AsyncWorkerThread *workerThread : workerThreads) {
workerThread->stop();
}
@ -51,15 +50,13 @@ AsyncEngine::~AsyncEngine()
}
// Wait for threads to finish
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
it != workerThreads.end(); ++it) {
(*it)->wait();
for (AsyncWorkerThread *workerThread : workerThreads) {
workerThread->wait();
}
// Force kill all threads
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
it != workerThreads.end(); ++it) {
delete *it;
for (AsyncWorkerThread *workerThread : workerThreads) {
delete workerThread;
}
jobQueueMutex.lock();
@ -192,9 +189,8 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) {
/******************************************************************************/
void AsyncEngine::prepareEnvironment(lua_State* L, int top)
{
for (std::vector<StateInitializer>::iterator it = stateInitializers.begin();
it != stateInitializers.end(); it++) {
(*it)(L, top);
for (StateInitializer &stateInitializer : stateInitializers) {
stateInitializer(L, top);
}
}
@ -202,7 +198,6 @@ void AsyncEngine::prepareEnvironment(lua_State* L, int top)
AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
const std::string &name) :
Thread(name),
ScriptApiBase(),
jobDispatcher(jobDispatcher)
{
lua_State *L = getStack();

@ -68,7 +68,7 @@ class AsyncEngine {
friend class AsyncWorkerThread;
typedef void (*StateInitializer)(lua_State *L, int top);
public:
AsyncEngine() {};
AsyncEngine() = default;
~AsyncEngine();
/**

@ -40,7 +40,7 @@ extern "C" {
#endif
}
#include <stdio.h>
#include <cstdio>
#include <cstdarg>
#include "script/common/c_content.h"
#include <sstream>

@ -40,12 +40,12 @@ extern "C" {
// use that name to bypass security!
#define BUILTIN_MOD_NAME "*builtin*"
#define PCALL_RES(RES) do { \
#define PCALL_RES(RES) { \
int result_ = (RES); \
if (result_ != 0) { \
scriptError(result_, __FUNCTION__); \
} \
} while (0)
}
#define runCallbacks(nargs, mode) \
runCallbacksRaw((nargs), (mode), __FUNCTION__)

@ -218,8 +218,7 @@ bool ScriptApiDetached::getDetachedInventoryCallback(
lua_getfield(L, -1, name.c_str());
lua_remove(L, -2);
// Should be a table
if(lua_type(L, -1) != LUA_TTABLE)
{
if (lua_type(L, -1) != LUA_TTABLE) {
errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl;
lua_pop(L, 1);
return false;
@ -230,20 +229,17 @@ bool ScriptApiDetached::getDetachedInventoryCallback(
lua_getfield(L, -1, callbackname);
lua_remove(L, -2);
// Should be a function or nil
if(lua_type(L, -1) == LUA_TFUNCTION)
{
if (lua_type(L, -1) == LUA_TFUNCTION) {
return true;
}
else if(lua_isnil(L, -1))
{
lua_pop(L, 1);
return false;
}
else
{
errorstream<<"Detached inventory \""<<name<<"\" callback \""
<<callbackname<<"\" is not a function"<<std::endl;
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
return false;
}
errorstream << "Detached inventory \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl;
lua_pop(L, 1);
return false;
}

@ -237,7 +237,9 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname)
// Should be a function or nil
if (lua_type(L, -1) == LUA_TFUNCTION) {
return true;
} else if (!lua_isnil(L, -1)) {
}
if (!lua_isnil(L, -1)) {
errorstream << "Item \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl;
}

@ -93,12 +93,6 @@ struct EnumString ScriptApiNode::es_NodeBoxType[] =
{0, NULL},
};
ScriptApiNode::ScriptApiNode() {
}
ScriptApiNode::~ScriptApiNode() {
}
bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed)
{
@ -198,7 +192,7 @@ bool ScriptApiNode::node_on_flood(v3s16 p, MapNode node, MapNode newnode)
pushnode(L, newnode, ndef);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
lua_remove(L, error_handler);
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1) == true;
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1);
}
void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node)
@ -237,7 +231,7 @@ bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime)
lua_pushnumber(L,dtime);
PCALL_RES(lua_pcall(L, 2, 1, error_handler));
lua_remove(L, error_handler);
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1) == true;
return (bool) lua_isboolean(L, -1) && (bool) lua_toboolean(L, -1);
}
void ScriptApiNode::node_on_receive_fields(v3s16 p,

@ -32,8 +32,8 @@ class ScriptApiNode
public ScriptApiNodemeta
{
public:
ScriptApiNode();
virtual ~ScriptApiNode();
ScriptApiNode() = default;
virtual ~ScriptApiNode() = default;
bool node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed);

@ -232,12 +232,3 @@ void ScriptApiNodemeta::nodemeta_inventory_OnTake(v3s16 p,
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
ScriptApiNodemeta::ScriptApiNodemeta()
{
}
ScriptApiNodemeta::~ScriptApiNodemeta()
{
}

@ -30,8 +30,8 @@ class ScriptApiNodemeta
public ScriptApiItem
{
public:
ScriptApiNodemeta();
virtual ~ScriptApiNodemeta();
ScriptApiNodemeta() = default;
virtual ~ScriptApiNodemeta() = default;
// Return number of accepted items to be moved
int nodemeta_inventory_AllowMove(v3s16 p,

@ -192,8 +192,3 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player,
runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC);
}
ScriptApiPlayer::~ScriptApiPlayer()
{
}

@ -28,7 +28,7 @@ struct ToolCapabilities;
class ScriptApiPlayer : virtual public ScriptApiBase
{
public:
virtual ~ScriptApiPlayer();
virtual ~ScriptApiPlayer() = default;
void on_newplayer(ServerActiveObject *player);
void on_dieplayer(ServerActiveObject *player);

@ -504,7 +504,7 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
// by the operating system anyways.
return false;
}
removed = component + (removed.empty() ? "" : DIR_DELIM + removed);
removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
abs_path = fs::AbsolutePath(cur_path);
}
if (abs_path.empty())
@ -550,9 +550,9 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
// Allow read-only access to all mod directories
if (!write_required) {
const std::vector<ModSpec> mods = gamedef->getMods();
for (size_t i = 0; i < mods.size(); ++i) {
str = fs::AbsolutePath(mods[i].path);
const std::vector<ModSpec> &mods = gamedef->getMods();
for (const ModSpec &mod : mods) {
str = fs::AbsolutePath(mod.path);
if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
return true;
}
@ -617,7 +617,9 @@ int ScriptApiSecurity::sl_g_load(lua_State *L)
int t = lua_type(L, -1);
if (t == LUA_TNIL) {
break;
} else if (t != LUA_TSTRING) {
}
if (t != LUA_TSTRING) {
lua_pushnil(L);
lua_pushliteral(L, "Loader didn't return a string");
return 2;

@ -34,7 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/string.h"
#include "nodedef.h"
int ModApiClient::l_get_current_modname(lua_State *L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);

@ -743,7 +743,7 @@ int ModApiEnvMod::l_find_node_near(lua_State *L)
for (int d = start_radius; d <= radius; d++) {
std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
for (v3s16 i : list) {
for (const v3s16 &i : list) {
v3s16 p = pos + i;
content_t c = env->getMap().getNodeNoEx(p).getContent();
if (filter.count(c) != 0) {
@ -1127,7 +1127,7 @@ int ModApiEnvMod::l_find_path(lua_State *L)
lua_newtable(L);
int top = lua_gettop(L);
unsigned int index = 1;
for (v3s16 i : path) {
for (const v3s16 &i : path) {
lua_pushnumber(L,index);
push_v3s16(L, i);
lua_settable(L, top);

@ -495,28 +495,29 @@ int ModApiInventory::l_get_inventory(lua_State *L)
v3s16 pos = check_v3s16(L, -1);
loc.setNodeMeta(pos);
if(getServer(L)->getInventory(loc) != NULL)
if (getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc);
else
lua_pushnil(L);
return 1;
} else {
NO_MAP_LOCK_REQUIRED;
if(type == "player"){
std::string name = checkstringfield(L, 1, "name");
loc.setPlayer(name);
} else if(type == "detached"){
std::string name = checkstringfield(L, 1, "name");
loc.setDetached(name);
}
if(getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc);
else
lua_pushnil(L);
return 1;
// END NO_MAP_LOCK_REQUIRED;
}
NO_MAP_LOCK_REQUIRED;
if (type == "player") {
std::string name = checkstringfield(L, 1, "name");
loc.setPlayer(name);
} else if (type == "detached") {
std::string name = checkstringfield(L, 1, "name");
loc.setDetached(name);
}
if (getServer(L)->getInventory(loc) != NULL)
InvRef::create(L, loc);
else
lua_pushnil(L);
return 1;
// END NO_MAP_LOCK_REQUIRED;
}
// create_detached_inventory_raw(name, [player_name])

@ -233,23 +233,22 @@ int ModApiMainMenu::l_get_worlds(lua_State *L)
int top = lua_gettop(L);
unsigned int index = 1;
for (unsigned int i = 0; i < worlds.size(); i++)
{
for (const WorldSpec &world : worlds) {
lua_pushnumber(L,index);
lua_newtable(L);
int top_lvl2 = lua_gettop(L);
lua_pushstring(L,"path");
lua_pushstring(L,worlds[i].path.c_str());
lua_pushstring(L, world.path.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"name");
lua_pushstring(L,worlds[i].name.c_str());
lua_pushstring(L, world.name.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"gameid");
lua_pushstring(L,worlds[i].gameid.c_str());
lua_pushstring(L, world.gameid.c_str());
lua_settable(L, top_lvl2);
lua_settable(L, top);
@ -267,40 +266,38 @@ int ModApiMainMenu::l_get_games(lua_State *L)
int top = lua_gettop(L);
unsigned int index = 1;
for (unsigned int i = 0; i < games.size(); i++)
{
for (const SubgameSpec &game : games) {
lua_pushnumber(L,index);
lua_newtable(L);
int top_lvl2 = lua_gettop(L);
lua_pushstring(L,"id");
lua_pushstring(L,games[i].id.c_str());
lua_pushstring(L, game.id.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"path");
lua_pushstring(L,games[i].path.c_str());
lua_pushstring(L, game.path.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"gamemods_path");
lua_pushstring(L,games[i].gamemods_path.c_str());
lua_pushstring(L, game.gamemods_path.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"name");
lua_pushstring(L,games[i].name.c_str());
lua_pushstring(L, game.name.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"menuicon_path");
lua_pushstring(L,games[i].menuicon_path.c_str());
lua_pushstring(L, game.menuicon_path.c_str());
lua_settable(L, top_lvl2);
lua_pushstring(L,"addon_mods_paths");
lua_newtable(L);
int table2 = lua_gettop(L);
int internal_index=1;
for (std::set<std::string>::iterator iter = games[i].addon_mods_paths.begin();
iter != games[i].addon_mods_paths.end(); ++iter) {
for (const std::string &addon_mods_path : game.addon_mods_paths) {
lua_pushnumber(L,internal_index);
lua_pushstring(L,(*iter).c_str());
lua_pushstring(L, addon_mods_path.c_str());
lua_settable(L, table2);
internal_index++;
}
@ -331,112 +328,111 @@ int ModApiMainMenu::l_get_favorites(lua_State *L)
int top = lua_gettop(L);
unsigned int index = 1;
for (unsigned int i = 0; i < servers.size(); i++)
{
for (const Json::Value &server : servers) {
lua_pushnumber(L,index);
lua_newtable(L);
int top_lvl2 = lua_gettop(L);
if (servers[i]["clients"].asString().size()) {
std::string clients_raw = servers[i]["clients"].asString();
if (!server["clients"].asString().empty()) {
std::string clients_raw = server["clients"].asString();
char* endptr = 0;
int numbervalue = strtol(clients_raw.c_str(),&endptr,10);
if ((clients_raw != "") && (*endptr == 0)) {
if ((!clients_raw.empty()) && (*endptr == 0)) {
lua_pushstring(L,"clients");
lua_pushnumber(L,numbervalue);
lua_settable(L, top_lvl2);
}
}
if (servers[i]["clients_max"].asString().size()) {
if (!server["clients_max"].asString().empty()) {
std::string clients_max_raw = servers[i]["clients_max"].asString();
std::string clients_max_raw = server["clients_max"].asString();
char* endptr = 0;
int numbervalue = strtol(clients_max_raw.c_str(),&endptr,10);
if ((clients_max_raw != "") && (*endptr == 0)) {
if ((!clients_max_raw.empty()) && (*endptr == 0)) {
lua_pushstring(L,"clients_max");
lua_pushnumber(L,numbervalue);
lua_settable(L, top_lvl2);
}
}
if (servers[i]["version"].asString().size()) {
if (!server["version"].asString().empty()) {
lua_pushstring(L,"version");
std::string topush = servers[i]["version"].asString();
std::string topush = server["version"].asString();
lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2);
}
if (servers[i]["proto_min"].asString().size()) {
if (!server["proto_min"].asString().empty()) {
lua_pushstring(L,"proto_min");
lua_pushinteger(L,servers[i]["proto_min"].asInt());
lua_pushinteger(L, server["proto_min"].asInt());
lua_settable(L, top_lvl2);
}
if (servers[i]["proto_max"].asString().size()) {
if (!server["proto_max"].asString().empty()) {
lua_pushstring(L,"proto_max");
lua_pushinteger(L,servers[i]["proto_max"].asInt());
lua_pushinteger(L, server["proto_max"].asInt());
lua_settable(L, top_lvl2);
}
if (servers[i]["password"].asString().size()) {
if (!server["password"].asString().empty()) {
lua_pushstring(L,"password");
lua_pushboolean(L,servers[i]["password"].asBool());
lua_pushboolean(L, server["password"].asBool());
lua_settable(L, top_lvl2);
}
if (servers[i]["creative"].asString().size()) {
if (!server["creative"].asString().empty()) {
lua_pushstring(L,"creative");
lua_pushboolean(L,servers[i]["creative"].asBool());
lua_pushboolean(L, server["creative"].asBool());
lua_settable(L, top_lvl2);
}
if (servers[i]["damage"].asString().size()) {
if (!server["damage"].asString().empty()) {
lua_pushstring(L,"damage");
lua_pushboolean(L,servers[i]["damage"].asBool());
lua_pushboolean(L, server["damage"].asBool());
lua_settable(L, top_lvl2);
}
if (servers[i]["pvp"].asString().size()) {
if (!server["pvp"].asString().empty()) {
lua_pushstring(L,"pvp");
lua_pushboolean(L,servers[i]["pvp"].asBool());
lua_pushboolean(L, server["pvp"].asBool());
lua_settable(L, top_lvl2);
}
if (servers[i]["description"].asString().size()) {
if (!server["description"].asString().empty()) {
lua_pushstring(L,"description");
std::string topush = servers[i]["description"].asString();
std::string topush = server["description"].asString();
lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2);
}
if (servers[i]["name"].asString().size()) {
if (!server["name"].asString().empty()) {
lua_pushstring(L,"name");
std::string topush = servers[i]["name"].asString();
std::string topush = server["name"].asString();
lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2);
}
if (servers[i]["address"].asString().size()) {
if (!server["address"].asString().empty()) {
lua_pushstring(L,"address");
std::string topush = servers[i]["address"].asString();
std::string topush = server["address"].asString();
lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2);
}
if (servers[i]["port"].asString().size()) {
if (!server["port"].asString().empty()) {
lua_pushstring(L,"port");
std::string topush = servers[i]["port"].asString();
std::string topush = server["port"].asString();
lua_pushstring(L,topush.c_str());
lua_settable(L, top_lvl2);
}
if (servers[i].isMember("ping")) {
float ping = servers[i]["ping"].asFloat();
if (server.isMember("ping")) {
float ping = server["ping"].asFloat();
lua_pushstring(L, "ping");
lua_pushnumber(L, ping);
lua_settable(L, top_lvl2);
@ -558,7 +554,7 @@ int ModApiMainMenu::l_set_topleft_text(lua_State *L)
GUIEngine* engine = getGuiEngine(L);
sanity_check(engine != NULL);
std::string text = "";
std::string text;
if (!lua_isnone(L,1) && !lua_isnil(L,1))
text = luaL_checkstring(L, 1);

@ -847,9 +847,8 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L)
lua_newtable(L);
int i = 1;
for (std::set<u32>::iterator it = emerge->gen_notify_on_deco_ids.begin();
it != emerge->gen_notify_on_deco_ids.end(); ++it) {
lua_pushnumber(L, *it);
for (u32 gen_notify_on_deco_id : emerge->gen_notify_on_deco_ids) {
lua_pushnumber(L, gen_notify_on_deco_id);
lua_rawseti(L, -2, i);
i++;
}
@ -1322,7 +1321,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L)
lua_pop(L, 1);
u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
prob_list.push_back(std::make_pair(pos, prob));
prob_list.emplace_back(pos, prob);
}
lua_pop(L, 1);
@ -1336,7 +1335,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L)
if (lua_istable(L, -1)) {
s16 ypos = getintfield_default(L, -1, "ypos", 0);
u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
slice_prob_list.push_back(std::make_pair(ypos, prob));
slice_prob_list.emplace_back(ypos, prob);
}
lua_pop(L, 1);

@ -218,10 +218,9 @@ void MetaDataRef::handleToTable(lua_State *L, Metadata *meta)
lua_newtable(L);
{
const StringMap &fields = meta->getStrings();
for (StringMap::const_iterator
it = fields.begin(); it != fields.end(); ++it) {
const std::string &name = it->first;
const std::string &value = it->second;
for (const auto &field : fields) {
const std::string &name = field.first;
const std::string &value = field.second;
lua_pushlstring(L, name.c_str(), name.size());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);

@ -31,7 +31,7 @@ class Metadata;
class MetaDataRef : public ModApiBase
{
public:
virtual ~MetaDataRef() {}
virtual ~MetaDataRef() = default;
protected:
static MetaDataRef *checkobject(lua_State *L, int narg);

@ -551,7 +551,7 @@ int ObjectRef::l_get_local_animation(lua_State *L)
float frame_speed;
player->getLocalAnimations(frames, &frame_speed);
for (v2s32 frame : frames) {
for (const v2s32 &frame : frames) {
push_v2s32(L, frame);
}

@ -32,8 +32,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "lua_api/l_localplayer.h"
#include "lua_api/l_camera.h"
ClientScripting::ClientScripting(Client *client):
ScriptApiBase()
ClientScripting::ClientScripting(Client *client)
{
setGameDef(client);
setType(ScriptingType::Client);

@ -460,7 +460,7 @@ void Sky::render()
driver->drawVertexPrimitiveList(vertices, SKY_STAR_COUNT * 4,
indices, SKY_STAR_COUNT, video::EVT_STANDARD,
scene::EPT_QUADS, video::EIT_16BIT);
} while(0);
} while(false);
// Draw far cloudy fog thing below east and west horizons
for (u32 j = 0; j < 2; j++) {

@ -39,7 +39,7 @@ struct SimpleSoundSpec
{
}
bool exists() const { return name != ""; }
bool exists() const { return !name.empty(); }
std::string name = "";
float gain = 1.0f;
@ -50,7 +50,8 @@ struct SimpleSoundSpec
class ISoundManager
{
public:
virtual ~ISoundManager() {}
virtual ~ISoundManager() = default;
// Multiple sounds can be loaded per name; when played, the sound
// should be chosen randomly from alternatives
// Return value determines success/failure
@ -80,7 +81,7 @@ public:
{
return playSound(spec.name, loop, spec.gain, spec.fade, spec.pitch);
}
int playSoundAt(const SimpleSoundSpec &spec, bool loop, v3f pos)
int playSoundAt(const SimpleSoundSpec &spec, bool loop, const v3f &pos)
{
return playSoundAt(spec.name, loop, spec.gain, pos, spec.pitch);
}

@ -275,7 +275,8 @@ private:
std::unordered_map<int, PlayingSound*> m_sounds_playing;
v3f m_listener_pos;
struct FadeState {
FadeState() {}
FadeState() = default;
FadeState(float step, float current_gain, float target_gain):
step(step),
current_gain(current_gain),
@ -351,13 +352,12 @@ public:
alcCloseDevice(m_device);
m_device = NULL;
for (std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i =
m_buffers.begin(); i != m_buffers.end(); ++i) {
for (std::vector<SoundBuffer*>::iterator iter = (*i).second.begin();
iter != (*i).second.end(); ++iter) {
for (auto &buffer : m_buffers) {
for (std::vector<SoundBuffer*>::iterator iter = buffer.second.begin();
iter != buffer.second.end(); ++iter) {
delete *iter;
}
(*i).second.clear();
buffer.second.clear();
}
m_buffers.clear();
infostream<<"Audio: Deinitialized."<<std::endl;
@ -379,7 +379,6 @@ public:
std::vector<SoundBuffer*> bufs;
bufs.push_back(buf);
m_buffers[name] = bufs;
return;
}
SoundBuffer* getBuffer(const std::string &name)
@ -450,7 +449,8 @@ public:
return id;
}
int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, v3f pos, float pitch)
int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, const v3f &pos,
float pitch)
{
assert(buf);
PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch);
@ -485,13 +485,11 @@ public:
std::set<std::string> paths;
std::set<std::string> datas;
m_fetcher->fetchSounds(name, paths, datas);
for(std::set<std::string>::iterator i = paths.begin();
i != paths.end(); ++i){
loadSoundFile(name, *i);
for (const std::string &path : paths) {
loadSoundFile(name, path);
}
for(std::set<std::string>::iterator i = datas.begin();
i != datas.end(); ++i){
loadSoundData(name, *i);
for (const std::string &data : datas) {
loadSoundData(name, data);
}
return getBuffer(name);
}
@ -503,10 +501,9 @@ public:
<<m_sounds_playing.size()<<" playing sounds, "
<<m_buffers.size()<<" sound names loaded"<<std::endl;
std::set<int> del_list;
for(std::unordered_map<int, PlayingSound*>::iterator i = m_sounds_playing.begin();
i != m_sounds_playing.end(); ++i) {
int id = i->first;
PlayingSound *sound = i->second;
for (auto &sp : m_sounds_playing) {
int id = sp.first;
PlayingSound *sound = sp.second;
// If not playing, remove it
{
ALint state;
@ -519,10 +516,8 @@ public:
if(!del_list.empty())
verbosestream<<"OpenALSoundManager::maintain(): deleting "
<<del_list.size()<<" playing sounds"<<std::endl;
for(std::set<int>::iterator i = del_list.begin();
i != del_list.end(); ++i)
{
deleteSound(*i);
for (int i : del_list) {
deleteSound(i);
}
}
@ -566,7 +561,7 @@ public:
int playSound(const std::string &name, bool loop, float volume, float fade, float pitch)
{
maintain();
if(name == "")
if (name.empty())
return 0;
SoundBuffer *buf = getFetchBuffer(name);
if(!buf){
@ -587,7 +582,7 @@ public:
int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch)
{
maintain();
if(name == "")
if (name.empty())
return 0;
SoundBuffer *buf = getFetchBuffer(name);
if(!buf){

@ -59,17 +59,12 @@ void StaticObjectList::serialize(std::ostream &os)
}
writeU16(os, count);
for(std::vector<StaticObject>::iterator
i = m_stored.begin();
i != m_stored.end(); ++i) {
StaticObject &s_obj = *i;
for (StaticObject &s_obj : m_stored) {
s_obj.serialize(os);
}
for(std::map<u16, StaticObject>::iterator
i = m_active.begin();
i != m_active.end(); ++i)
{
StaticObject s_obj = i->second;
for (auto &i : m_active) {
StaticObject s_obj = i.second;
s_obj.serialize(os);
}
}

@ -32,8 +32,8 @@ struct StaticObject
v3f pos;
std::string data;
StaticObject() {}
StaticObject(u8 type_, v3f pos_, const std::string &data_):
StaticObject() = default;
StaticObject(u8 type_, const v3f &pos_, const std::string &data_):
type(type_),
pos(pos_),
data(data_)
@ -51,7 +51,7 @@ public:
Inserts an object to the container.
Id must be unique (active) or 0 (stored).
*/
void insert(u16 id, StaticObject obj)
void insert(u16 id, const StaticObject &obj)
{
if(id == 0)
{

@ -71,7 +71,7 @@ std::string getSubgamePathEnv()
SubgameSpec findSubgame(const std::string &id)
{
if(id == "")
if (id.empty())
return SubgameSpec();
std::string share = porting::path_share;
std::string user = porting::path_user;
@ -81,32 +81,27 @@ SubgameSpec findSubgame(const std::string &id)
while (!search_paths.at_end()) {
std::string path = search_paths.next(PATH_DELIM);
find_paths.push_back(GameFindPath(
path + DIR_DELIM + id, false));
find_paths.push_back(GameFindPath(
path + DIR_DELIM + id + "_game", false));
find_paths.emplace_back(path + DIR_DELIM + id, false);
find_paths.emplace_back(path + DIR_DELIM + id + "_game", false);
}
find_paths.push_back(GameFindPath(
user + DIR_DELIM + "games" + DIR_DELIM + id + "_game", true));
find_paths.push_back(GameFindPath(
user + DIR_DELIM + "games" + DIR_DELIM + id, true));
find_paths.push_back(GameFindPath(
share + DIR_DELIM + "games" + DIR_DELIM + id + "_game", false));
find_paths.push_back(GameFindPath(
share + DIR_DELIM + "games" + DIR_DELIM + id, false));
find_paths.emplace_back(user + DIR_DELIM + "games" + DIR_DELIM + id + "_game", true);
find_paths.emplace_back(user + DIR_DELIM + "games" + DIR_DELIM + id, true);
find_paths.emplace_back(share + DIR_DELIM + "games" + DIR_DELIM + id + "_game",
false);
find_paths.emplace_back(share + DIR_DELIM + "games" + DIR_DELIM + id, false);
// Find game directory
std::string game_path;
bool user_game = true; // Game is in user's directory
for(u32 i=0; i<find_paths.size(); i++){
const std::string &try_path = find_paths[i].path;
if(fs::PathExists(try_path)){
for (const GameFindPath &find_path : find_paths) {
const std::string &try_path = find_path.path;
if (fs::PathExists(try_path)) {
game_path = try_path;
user_game = find_paths[i].user_specific;
user_game = find_path.user_specific;
break;
}
}
if(game_path == "")
if (game_path.empty())
return SubgameSpec();
std::string gamemod_path = game_path + DIR_DELIM + "mods";
// Find mod directories
@ -116,7 +111,7 @@ SubgameSpec findSubgame(const std::string &id)
if(user != share || user_game)
mods_paths.insert(user + DIR_DELIM + "mods");
std::string game_name = getGameName(game_path);
if(game_name == "")
if (game_name.empty())
game_name = id;
std::string menuicon_path;
#ifndef SERVER
@ -137,7 +132,7 @@ SubgameSpec findWorldSubgame(const std::string &world_path)
gamespec.path = world_gamepath;
gamespec.gamemods_path= world_gamepath + DIR_DELIM + "mods";
gamespec.name = getGameName(world_gamepath);
if(gamespec.name == "")
if (gamespec.name.empty())
gamespec.name = "unknown";
return gamespec;
}
@ -156,23 +151,22 @@ std::set<std::string> getAvailableGameIds()
while (!search_paths.at_end())
gamespaths.insert(search_paths.next(PATH_DELIM));
for (std::set<std::string>::const_iterator i = gamespaths.begin();
i != gamespaths.end(); ++i){
std::vector<fs::DirListNode> dirlist = fs::GetDirListing(*i);
for(u32 j=0; j<dirlist.size(); j++){
if(!dirlist[j].dir)
for (const std::string &gamespath : gamespaths) {
std::vector<fs::DirListNode> dirlist = fs::GetDirListing(gamespath);
for (const fs::DirListNode &dln : dirlist) {
if(!dln.dir)
continue;
// If configuration file is not found or broken, ignore game
Settings conf;
if(!getGameConfig(*i + DIR_DELIM + dirlist[j].name, conf))
if(!getGameConfig(gamespath + DIR_DELIM + dln.name, conf))
continue;
// Add it to result
const char *ends[] = {"_game", NULL};
std::string shorter = removeStringEnd(dirlist[j].name, ends);
if(shorter != "")
std::string shorter = removeStringEnd(dln.name, ends);
if (!shorter.empty())
gameids.insert(shorter);
else
gameids.insert(dirlist[j].name);
gameids.insert(dln.name);
}
}
return gameids;
@ -182,9 +176,8 @@ std::vector<SubgameSpec> getAvailableGames()
{
std::vector<SubgameSpec> specs;
std::set<std::string> gameids = getAvailableGameIds();
for(std::set<std::string>::const_iterator i = gameids.begin();
i != gameids.end(); ++i)
specs.push_back(findSubgame(*i));
for (const auto &gameid : gameids)
specs.push_back(findSubgame(gameid));
return specs;
}
@ -235,15 +228,14 @@ std::vector<WorldSpec> getAvailableWorlds()
worldspaths.insert(porting::path_user + DIR_DELIM + "worlds");
infostream << "Searching worlds..." << std::endl;
for (std::set<std::string>::const_iterator i = worldspaths.begin();
i != worldspaths.end(); ++i) {
infostream << " In " << (*i) << ": " <<std::endl;
std::vector<fs::DirListNode> dirvector = fs::GetDirListing(*i);
for(u32 j=0; j<dirvector.size(); j++){
if(!dirvector[j].dir)
for (const std::string &worldspath : worldspaths) {
infostream << " In " << worldspath << ": " <<std::endl;
std::vector<fs::DirListNode> dirvector = fs::GetDirListing(worldspath);
for (const fs::DirListNode &dln : dirvector) {
if(!dln.dir)
continue;
std::string fullpath = *i + DIR_DELIM + dirvector[j].name;
std::string name = dirvector[j].name;
std::string fullpath = worldspath + DIR_DELIM + dln.name;
std::string name = dln.name;
// Just allow filling in the gameid always for now
bool can_be_legacy = true;
std::string gameid = getWorldGameId(fullpath, can_be_legacy);
@ -267,7 +259,7 @@ std::vector<WorldSpec> getAvailableWorlds()
WorldSpec spec(fullpath, name, gameid);
infostream<<"Old world found."<<std::endl;
worlds.push_back(spec);
}while(0);
}while(false);
infostream<<worlds.size()<<" found."<<std::endl;
return worlds;
}

@ -50,7 +50,7 @@ struct SubgameSpec
bool isValid() const
{
return (id != "" && path != "");
return (!id.empty() && !path.empty());
}
};
@ -89,7 +89,7 @@ struct WorldSpec
bool isValid() const
{
return (name != "" && path != "" && gameid != "");
return (!name.empty() && !path.empty() && !gameid.empty());
}
};

@ -348,7 +348,8 @@ void TerminalChatConsole::step(int ch)
std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first));
if (!g_settings->getBool("disable_escape_sequences")) {
error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
error_message = std::wstring(L"\x1b(c@red)").append(error_message)
.append(L"\x1b(c@white)");
}
m_chat_backend.addMessage(error_message, utf8_to_wide(p.second));
}
@ -439,8 +440,7 @@ void TerminalChatConsole::draw_text()
const ChatFormattedLine& line = buf.getFormattedLine(row);
if (line.fragments.empty())
continue;
for (u32 i = 0; i < line.fragments.size(); ++i) {
const ChatFormattedFragment& fragment = line.fragments[i];
for (const ChatFormattedFragment &fragment : line.fragments) {
addstr(wide_to_utf8(fragment.text.getString()).c_str());
}
}

@ -31,26 +31,24 @@ void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const
writeF1000(os, full_punch_interval);
writeS16(os, max_drop_level);
writeU32(os, groupcaps.size());
for (ToolGCMap::const_iterator i = groupcaps.begin(); i != groupcaps.end(); ++i) {
const std::string *name = &i->first;
const ToolGroupCap *cap = &i->second;
for (const auto &groupcap : groupcaps) {
const std::string *name = &groupcap.first;
const ToolGroupCap *cap = &groupcap.second;
os << serializeString(*name);
writeS16(os, cap->uses);
writeS16(os, cap->maxlevel);
writeU32(os, cap->times.size());
for (std::unordered_map<int, float>::const_iterator
j = cap->times.begin(); j != cap->times.end(); ++j) {
writeS16(os, j->first);
writeF1000(os, j->second);
for (const auto &time : cap->times) {
writeS16(os, time.first);
writeF1000(os, time.second);
}
}
writeU32(os, damageGroups.size());
for (DamageGroup::const_iterator i = damageGroups.begin();
i != damageGroups.end(); ++i) {
os << serializeString(i->first);
writeS16(os, i->second);
for (const auto &damageGroup : damageGroups) {
os << serializeString(damageGroup.first);
writeS16(os, damageGroup.second);
}
}
@ -107,15 +105,14 @@ DigParams getDigParams(const ItemGroupList &groups,
bool result_diggable = false;
float result_time = 0.0;
float result_wear = 0.0;
std::string result_main_group = "";
std::string result_main_group;
int level = itemgroup_get(groups, "level");
//infostream<<"level="<<level<<std::endl;
for (ToolGCMap::const_iterator i = tp->groupcaps.begin();
i != tp->groupcaps.end(); ++i) {
const std::string &name = i->first;
for (const auto &groupcap : tp->groupcaps) {
const std::string &name = groupcap.first;
//infostream<<"group="<<name<<std::endl;
const ToolGroupCap &cap = i->second;
const ToolGroupCap &cap = groupcap.second;
int rating = itemgroup_get(groups, name);
float time = 0;
bool time_exists = cap.getTime(rating, &time);
@ -159,14 +156,14 @@ HitParams getHitParams(const ItemGroupList &armor_groups,
s16 damage = 0;
float full_punch_interval = tp->full_punch_interval;
for (DamageGroup::const_iterator i = tp->damageGroups.begin();
i != tp->damageGroups.end(); ++i) {
s16 armor = itemgroup_get(armor_groups, i->first);
damage += i->second * rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0)
for (const auto &damageGroup : tp->damageGroups) {
s16 armor = itemgroup_get(armor_groups, damageGroup.first);
damage += damageGroup.second
* rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0)
* armor / 100.0;
}
return HitParams(damage, 0);
return {damage, 0};
}
HitParams getHitParams(const ItemGroupList &armor_groups,
@ -183,12 +180,13 @@ PunchDamageResult getPunchDamage(
){
bool do_hit = true;
{
if(do_hit && punchitem){
if(itemgroup_get(armor_groups, "punch_operable") &&
(toolcap == NULL || punchitem->name == ""))
if (do_hit && punchitem) {
if (itemgroup_get(armor_groups, "punch_operable") &&
(toolcap == NULL || punchitem->name.empty()))
do_hit = false;
}
if(do_hit){
if (do_hit) {
if(itemgroup_get(armor_groups, "immortal"))
do_hit = false;
}

@ -30,7 +30,7 @@ struct ToolGroupCap
int maxlevel = 1;
int uses = 20;
ToolGroupCap() {}
ToolGroupCap() = default;
bool getTime(int rating, float *time) const
{
@ -118,7 +118,7 @@ struct PunchDamageResult
int damage = 0;
int wear = 0;
PunchDamageResult() {}
PunchDamageResult() = default;
};
struct ItemStack;

@ -37,8 +37,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
using namespace irr::core;
extern Settings *g_settings;
const char** touchgui_button_imagenames = (const char*[]) {
"up_arrow.png",
"down_arrow.png",
@ -356,7 +354,7 @@ void AutoHideButtonBar::step(float dtime)
void AutoHideButtonBar::deactivate()
{
if (m_visible == true) {
if (m_visible) {
m_starter.guibutton->setVisible(true);
m_starter.guibutton->setEnabled(true);
}

@ -93,7 +93,7 @@ void make_tree(MMVManip &vmanip, v3s16 p0,
u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true &&
if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) {
if (leaves_d[i] == 1) {
@ -131,10 +131,8 @@ treegen::error spawn_ltree(ServerEnvironment *env, v3s16 p0,
// Send a MEET_OTHER event
MapEditEvent event;
event.type = MEET_OTHER;
for (std::map<v3s16, MapBlock*>::iterator
i = modified_blocks.begin();
i != modified_blocks.end(); ++i)
event.modified_blocks.insert(i->first);
for (auto &modified_block : modified_blocks)
event.modified_blocks.insert(modified_block.first);
map->dispatchEvent(&event);
return SUCCESS;
}
@ -182,7 +180,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
//generate axiom
std::string axiom = tree_definition.initial_axiom;
for (s16 i = 0; i < iterations; i++) {
std::string temp = "";
std::string temp;
for (s16 j = 0; j < (s16)axiom.size(); j++) {
char axiom_char = axiom.at(j);
switch (axiom_char) {
@ -403,7 +401,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
v3f(position.X, position.Y, position.Z - 1),
tree_definition
);
} if (stack_orientation.empty() == false) {
} if (!stack_orientation.empty()) {
s16 size = 1;
for (x = -size; x <= size; x++)
for (y = -size; y <= size; y++)
@ -527,7 +525,7 @@ treegen::error make_ltree(MMVManip &vmanip, v3s16 p0,
void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node)
{
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false)
if (!vmanip.m_area.contains(p1))
return;
u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -540,7 +538,7 @@ void tree_node_placement(MMVManip &vmanip, v3f p0, MapNode node)
void tree_trunk_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition)
{
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false)
if (!vmanip.m_area.contains(p1))
return;
u32 vi = vmanip.m_area.index(p1);
content_t current_node = vmanip.m_data[vi].getContent();
@ -560,7 +558,7 @@ void tree_leaves_placement(MMVManip &vmanip, v3f p0,
if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance)
leavesnode = tree_definition.leaves2node;
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false)
if (!vmanip.m_area.contains(p1))
return;
u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -584,7 +582,7 @@ void tree_single_leaves_placement(MMVManip &vmanip, v3f p0,
if (ps.range(1, 100) > 100 - tree_definition.leaves2_chance)
leavesnode = tree_definition.leaves2node;
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false)
if (!vmanip.m_area.contains(p1))
return;
u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -597,7 +595,7 @@ void tree_single_leaves_placement(MMVManip &vmanip, v3f p0,
void tree_fruit_placement(MMVManip &vmanip, v3f p0, TreeDef &tree_definition)
{
v3s16 p1 = v3s16(myround(p0.X), myround(p0.Y), myround(p0.Z));
if (vmanip.m_area.contains(p1) == false)
if (!vmanip.m_area.contains(p1))
return;
u32 vi = vmanip.m_area.index(p1);
if (vmanip.m_data[vi].getContent() != CONTENT_AIR
@ -734,7 +732,7 @@ void make_jungletree(MMVManip &vmanip, v3s16 p0, INodeDefManager *ndef, s32 seed
u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true &&
if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE)) {
if (leaves_d[i] == 1)
@ -856,7 +854,7 @@ void make_pine_tree(MMVManip &vmanip, v3s16 p0, INodeDefManager *ndef, s32 seed)
u32 vi = vmanip.m_area.index(pmin + p1);
for (s16 x = leaves_a.MinEdge.X; x <= leaves_a.MaxEdge.X; x++) {
v3s16 p(x, y, z);
if (vmanip.m_area.contains(p + p1) == true &&
if (vmanip.m_area.contains(p + p1) &&
(vmanip.m_data[vi].getContent() == CONTENT_AIR ||
vmanip.m_data[vi].getContent() == CONTENT_IGNORE ||
vmanip.m_data[vi] == snownode)) {

@ -120,8 +120,8 @@ void TestGameDef::defineSomeNodes()
"{default_stone.png";
f = ContentFeatures();
f.name = itemdef.name;
for(int i = 0; i < 6; i++)
f.tiledef[i].name = "default_stone.png";
for (TileDef &tiledef : f.tiledef)
tiledef.name = "default_stone.png";
f.is_ground_content = true;
idef->registerItem(itemdef);
t_CONTENT_STONE = ndef->set(f.name, f);
@ -175,8 +175,8 @@ void TestGameDef::defineSomeNodes()
f.liquid_viscosity = 4;
f.is_ground_content = true;
f.groups["liquids"] = 3;
for(int i = 0; i < 6; i++)
f.tiledef[i].name = "default_water.png";
for (TileDef &tiledef : f.tiledef)
tiledef.name = "default_water.png";
idef->registerItem(itemdef);
t_CONTENT_WATER = ndef->set(f.name, f);
@ -197,8 +197,8 @@ void TestGameDef::defineSomeNodes()
f.light_source = LIGHT_MAX-1;
f.is_ground_content = true;
f.groups["liquids"] = 3;
for(int i = 0; i < 6; i++)
f.tiledef[i].name = "default_lava.png";
for (TileDef &tiledef : f.tiledef)
tiledef.name = "default_lava.png";
idef->registerItem(itemdef);
t_CONTENT_LAVA = ndef->set(f.name, f);
@ -215,8 +215,8 @@ void TestGameDef::defineSomeNodes()
"{default_brick.png";
f = ContentFeatures();
f.name = itemdef.name;
for(int i = 0; i < 6; i++)
f.tiledef[i].name = "default_brick.png";
for (TileDef &tiledef : f.tiledef)
tiledef.name = "default_brick.png";
f.is_ground_content = true;
idef->registerItem(itemdef);
t_CONTENT_BRICK = ndef->set(f.name, f);

@ -71,7 +71,7 @@ class TestFailedException : public std::exception {
}
// Asserts the comparison specified by CMP is true, or fails the current unit test
#define UASSERTCMP(T, CMP, actual, expected) do { \
#define UASSERTCMP(T, CMP, actual, expected) { \
T a = (actual); \
T e = (expected); \
if (!(a CMP e)) { \
@ -84,12 +84,12 @@ class TestFailedException : public std::exception {
<< e << std::endl; \
throw TestFailedException(); \
} \
} while (0)
}
#define UASSERTEQ(T, actual, expected) UASSERTCMP(T, ==, actual, expected)
// UASSERTs that the specified exception occurs
#define EXCEPTION_CHECK(EType, code) do { \
#define EXCEPTION_CHECK(EType, code) { \
bool exception_thrown = false; \
try { \
code; \
@ -97,7 +97,7 @@ class TestFailedException : public std::exception {
exception_thrown = true; \
} \
UASSERT(exception_thrown); \
} while (0)
}
class IGameDef;

@ -65,8 +65,8 @@ void TestCompression::testRLECompression()
infostream << "str_out.size()="<<str_out.size()<<std::endl;
infostream << "TestCompress: 1,5,5,1 -> ";
for (u32 i = 0; i < str_out.size(); i++)
infostream << (u32)str_out[i] << ",";
for (char i : str_out)
infostream << (u32) i << ",";
infostream << std::endl;
UASSERT(str_out.size() == 10);
@ -89,8 +89,8 @@ void TestCompression::testRLECompression()
std::string str_out2 = os2.str();
infostream << "decompress: ";
for (u32 i = 0; i < str_out2.size(); i++)
infostream << (u32)str_out2[i] << ",";
for (char i : str_out2)
infostream << (u32) i << ",";
infostream << std::endl;
UASSERTEQ(size_t, str_out2.size(), fromdata.getSize());
@ -114,8 +114,8 @@ void TestCompression::testZlibCompression()
infostream << "str_out.size()=" << str_out.size() <<std::endl;
infostream << "TestCompress: 1,5,5,1 -> ";
for (u32 i = 0; i < str_out.size(); i++)
infostream << (u32)str_out[i] << ",";
for (char i : str_out)
infostream << (u32) i << ",";
infostream << std::endl;
std::istringstream is(str_out, std::ios_base::binary);
@ -125,8 +125,8 @@ void TestCompression::testZlibCompression()
std::string str_out2 = os2.str();
infostream << "decompress: ";
for (u32 i = 0; i < str_out2.size(); i++)
infostream << (u32)str_out2[i] << ",";
for (char i : str_out2)
infostream << (u32) i << ",";
infostream << std::endl;
UASSERTEQ(size_t, str_out2.size(), fromdata.getSize());

@ -50,8 +50,8 @@ void TestNodeDef::testContentFeaturesSerialization()
ContentFeatures f;
f.name = "default:stone";
for (int i = 0; i < 6; i++)
f.tiledef[i].name = "default_stone.png";
for (TileDef &tiledef : f.tiledef)
tiledef.name = "default_stone.png";
f.is_ground_content = true;
std::ostringstream os(std::ios::binary);

@ -113,7 +113,7 @@ void TestNoise::testNoiseInvalidParams()
NoiseParams np_highmem(4, 70, v3f(1, 1, 1), 5, 60, 0.7, 10.0);
Noise noise_highmem_3d(&np_highmem, 1337, 200, 200, 200);
noise_highmem_3d.perlinMap3D(0, 0, 0, NULL);
} catch (InvalidNoiseParamsException) {
} catch (InvalidNoiseParamsException &) {
exception_thrown = true;
}

@ -215,11 +215,11 @@ void TestVoxelAlgorithms::testVoxelLineIterator(INodeDefManager *ndef)
for (f32 x = -9.1; x < 9; x += 3.124) {
for (f32 y = -9.2; y < 9; y += 3.123) {
for (f32 z = -9.3; z < 9; z += 3.122) {
lines.push_back(core::line3d<f32>(-x, -y, -z, x, y, z));
lines.emplace_back(-x, -y, -z, x, y, z);
}
}
}
lines.push_back(core::line3d<f32>(0, 0, 0, 0, 0, 0));
lines.emplace_back(0, 0, 0, 0, 0, 0);
// Test every line
std::vector<core::line3d<f32> >::iterator it = lines.begin();
for (; it < lines.end(); it++) {

@ -68,9 +68,8 @@ void AreaStore::serialize(std::ostream &os) const
// TODO: Compression?
writeU16(os, areas_map.size());
for (AreaMap::const_iterator it = areas_map.begin();
it != areas_map.end(); ++it) {
const Area &a = it->second;
for (const auto &it : areas_map) {
const Area &a = it.second;
writeV3S16(os, a.minedge);
writeV3S16(os, a.maxedge);
writeU16(os, a.data.size());
@ -193,10 +192,9 @@ bool VectorAreaStore::removeArea(u32 id)
void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
{
for (size_t i = 0; i < m_areas.size(); ++i) {
Area *b = m_areas[i];
if (AST_CONTAINS_PT(b, pos)) {
result->push_back(b);
for (Area *area : m_areas) {
if (AST_CONTAINS_PT(area, pos)) {
result->push_back(area);
}
}
}
@ -204,11 +202,10 @@ void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
void VectorAreaStore::getAreasInArea(std::vector<Area *> *result,
v3s16 minedge, v3s16 maxedge, bool accept_overlap)
{
for (size_t i = 0; i < m_areas.size(); ++i) {
Area *b = m_areas[i];
if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, b) :
AST_CONTAINS_AREA(minedge, maxedge, b)) {
result->push_back(b);
for (Area *area : m_areas) {
if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, area) :
AST_CONTAINS_AREA(minedge, maxedge, area)) {
result->push_back(area);
}
}
}

@ -37,7 +37,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
struct Area {
Area() {}
Area() = default;
Area(const v3s16 &mine, const v3s16 &maxe) :
minedge(mine), maxedge(maxe)
{
@ -56,7 +57,7 @@ public:
m_res_cache(1000, &cacheMiss, this)
{}
virtual ~AreaStore() {}
virtual ~AreaStore() = default;
static AreaStore *getOptimalImplementation();

@ -97,7 +97,6 @@ void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color
parseColorString(wide_to_utf8(parts[1]), m_background, true);
m_has_background = true;
}
continue;
}
}
@ -111,7 +110,7 @@ void EnrichedString::addCharNoColor(wchar_t c)
{
m_string += c;
if (m_colors.empty()) {
m_colors.push_back(SColor(255, 255, 255, 255));
m_colors.emplace_back(255, 255, 255, 255);
} else {
m_colors.push_back(m_colors[m_colors.size() - 1]);
}
@ -138,15 +137,16 @@ EnrichedString EnrichedString::substr(size_t pos, size_t len) const
}
if (len == std::string::npos || pos + len > m_string.length()) {
return EnrichedString(
m_string.substr(pos, std::string::npos),
std::vector<SColor>(m_colors.begin() + pos, m_colors.end())
);
} else {
return EnrichedString(
m_string.substr(pos, len),
std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len)
);
m_string.substr(pos, std::string::npos),
std::vector<SColor>(m_colors.begin() + pos, m_colors.end())
);
}
return EnrichedString(
m_string.substr(pos, len),
std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len)
);
}
const wchar_t *EnrichedString::c_str() const

@ -281,7 +281,8 @@ inline aabb3f getNodeBox(v3s16 p, float d)
class IntervalLimiter
{
public:
IntervalLimiter() {}
IntervalLimiter() = default;
/*
dtime: time from last call to this method
wanted_interval: interval wanted

@ -697,7 +697,7 @@ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg,
goto cleanup_and_exit;
}
memcpy((char *)ver->username, username, ulen);
memcpy(ver->username, username, ulen);
ver->authenticated = 0;

@ -167,7 +167,7 @@ std::string wide_to_utf8(const std::wstring &input)
wchar_t *utf8_to_wide_c(const char *str)
{
std::wstring ret = utf8_to_wide(std::string(str)).c_str();
std::wstring ret = utf8_to_wide(std::string(str));
size_t len = ret.length();
wchar_t *ret_c = new wchar_t[len + 1];
memset(ret_c, 0, (len + 1) * sizeof(wchar_t));
@ -308,8 +308,8 @@ std::string wide_to_narrow(const std::wstring &wcs)
size_t len = wcstombs(*mbs, wcs.c_str(), mbl);
if (len == (size_t)(-1))
return "Character conversion failed!";
else
mbs[len] = 0;
mbs[len] = 0;
return *mbs;
}
@ -321,8 +321,7 @@ std::string urlencode(const std::string &str)
// followed by two hex digits. See RFC 3986, section 2.3.
static const char url_hex_chars[] = "0123456789ABCDEF";
std::ostringstream oss(std::ios::binary);
for (u32 i = 0; i < str.size(); i++) {
unsigned char c = str[i];
for (unsigned char c : str) {
if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
oss << c;
} else {

@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#pragma once
#include "irrlichttypes_bloated.h"
#include <stdlib.h>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
@ -231,12 +231,12 @@ inline std::vector<std::basic_string<T> > str_split(
*/
inline std::string lowercase(const std::string &str)
{
std::string s2 = "";
std::string s2;
s2.reserve(str.size());
for (size_t i = 0; i < str.size(); i++)
s2 += tolower(str[i]);
for (char i : str)
s2 += tolower(i);
return s2;
}
@ -607,8 +607,8 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
*/
inline bool is_number(const std::string &to_check)
{
for (size_t i = 0; i < to_check.size(); i++)
if (!std::isdigit(to_check[i]))
for (char i : to_check)
if (!std::isdigit(i))
return false;
return !to_check.empty();

@ -21,8 +21,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "map.h"
#include "gettime.h"
#include "nodedef.h"
#include "util/directiontables.h"
#include "util/timetaker.h"
#include <string.h> // memcpy, memset
#include <cstring> // memcpy, memset
/*
Debug stuff
@ -32,11 +33,6 @@ u64 emerge_time = 0;
u64 emerge_load_time = 0;
u64 clearflag_time = 0;
VoxelManipulator::VoxelManipulator()
{
}
VoxelManipulator::~VoxelManipulator()
{
clear();
@ -110,7 +106,7 @@ void VoxelManipulator::print(std::ostream &o, INodeDefManager *ndef,
{
if(ndef->get(m).light_source != 0)
c = 'S';
else if(ndef->get(m).light_propagates == false)
else if(!ndef->get(m).light_propagates)
c = 'X';
else
{
@ -322,23 +318,13 @@ void VoxelManipulator::clearFlag(u8 flags)
void VoxelManipulator::unspreadLight(enum LightBank bank, v3s16 p, u8 oldlight,
std::set<v3s16> & light_sources, INodeDefManager *nodemgr)
{
v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1));
addArea(voxel_area);
// Loop through 6 neighbors
for(u16 i=0; i<6; i++)
{
for (const v3s16 &dir : g_6dirs) {
// Get the position of the neighbor node
v3s16 n2pos = p + dirs[i];
v3s16 n2pos = p + dir;
u32 n2i = m_area.index(n2pos);
@ -387,15 +373,6 @@ void VoxelManipulator::unspreadLight(enum LightBank bank, v3s16 p, u8 oldlight,
void VoxelManipulator::spreadLight(enum LightBank bank, v3s16 p,
INodeDefManager *nodemgr)
{
const v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
VoxelArea voxel_area(p - v3s16(1,1,1), p + v3s16(1,1,1));
addArea(voxel_area);
@ -410,10 +387,9 @@ void VoxelManipulator::spreadLight(enum LightBank bank, v3s16 p,
u8 newlight = diminish_light(oldlight);
// Loop through 6 neighbors
for(u16 i=0; i<6; i++)
{
for (const auto &dir : g_6dirs) {
// Get the position of the neighbor node
v3s16 n2pos = p + dirs[i];
v3s16 n2pos = p + dir;
u32 n2i = m_area.index(n2pos);
@ -457,25 +433,12 @@ const MapNode VoxelManipulator::ContentIgnoreNode = MapNode(CONTENT_IGNORE);
void VoxelManipulator::spreadLight(enum LightBank bank,
std::set<v3s16> & from_nodes, INodeDefManager *nodemgr)
{
const v3s16 dirs[6] = {
v3s16(0,0,1), // back
v3s16(0,1,0), // top
v3s16(1,0,0), // right
v3s16(0,0,-1), // front
v3s16(0,-1,0), // bottom
v3s16(-1,0,0), // left
};
if(from_nodes.empty())
return;
std::set<v3s16> lighted_nodes;
for(std::set<v3s16>::iterator j = from_nodes.begin();
j != from_nodes.end(); ++j)
{
v3s16 pos = *j;
for (const v3s16 &pos : from_nodes) {
VoxelArea voxel_area(pos - v3s16(1,1,1), pos + v3s16(1,1,1));
addArea(voxel_area);
@ -490,10 +453,9 @@ void VoxelManipulator::spreadLight(enum LightBank bank,
u8 newlight = diminish_light(oldlight);
// Loop through 6 neighbors
for(u16 i=0; i<6; i++)
{
for (const v3s16 &dir : g_6dirs) {
// Get the position of the neighbor node
v3s16 n2pos = pos + dirs[i];
v3s16 n2pos = pos + dir;
try
{

@ -59,7 +59,7 @@ class VoxelArea
{
public:
// Starts as zero sized
VoxelArea() {}
VoxelArea() = default;
VoxelArea(const v3s16 &min_edge, const v3s16 &max_edge):
MinEdge(min_edge),
@ -175,12 +175,12 @@ public:
VoxelArea operator+(const v3s16 &off) const
{
return VoxelArea(MinEdge+off, MaxEdge+off);
return {MinEdge+off, MaxEdge+off};
}
VoxelArea operator-(const v3s16 &off) const
{
return VoxelArea(MinEdge-off, MaxEdge-off);
return {MinEdge-off, MaxEdge-off};
}
/*
@ -344,7 +344,7 @@ enum VoxelPrintMode
class VoxelManipulator
{
public:
VoxelManipulator();
VoxelManipulator() = default;
virtual ~VoxelManipulator();
/*
@ -374,7 +374,7 @@ public:
addArea(voxel_area);
if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) {
return MapNode(CONTENT_IGNORE);
return {CONTENT_IGNORE};
}
return m_data[m_area.index(p)];
@ -382,9 +382,9 @@ public:
MapNode getNodeNoExNoEmerge(const v3s16 &p)
{
if (!m_area.contains(p))
return MapNode(CONTENT_IGNORE);
return {CONTENT_IGNORE};
if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA)
return MapNode(CONTENT_IGNORE);
return {CONTENT_IGNORE};
return m_data[m_area.index(p)];
}
// Stuff explodes if non-emerged area is touched with this.

@ -118,7 +118,7 @@ SunlightPropagateResult propagateSunlight(VoxelManipulator &v, VoxelArea a,
} else if(incoming_light == LIGHT_SUN &&
ndef->get(n).sunlight_propagates){
// Do nothing
} else if(ndef->get(n).sunlight_propagates == false){
} else if(!ndef->get(n).sunlight_propagates){
incoming_light = 0;
} else {
incoming_light = diminish_light(incoming_light);
@ -152,7 +152,7 @@ SunlightPropagateResult propagateSunlight(VoxelManipulator &v, VoxelArea a,
}
}
return SunlightPropagateResult(bottom_sunlight_valid);
return {bottom_sunlight_valid};
}
/*!
@ -186,21 +186,16 @@ struct ChangingLight {
//! Position of the node's block.
mapblock_v3 block_position;
//! Pointer to the node's block.
MapBlock *block;
MapBlock *block = NULL;
/*!
* Direction from the node that caused this node's changing
* to this node.
*/
direction source_direction;
direction source_direction = 6;
ChangingLight() :
rel_position(),
block_position(),
block(NULL),
source_direction(6)
{}
ChangingLight() = default;
ChangingLight(relative_v3 rel_pos, mapblock_v3 block_pos,
ChangingLight(const relative_v3 &rel_pos, const mapblock_v3 &block_pos,
MapBlock *b, direction source_dir) :
rel_position(rel_pos),
block_position(block_pos),
@ -265,8 +260,7 @@ struct LightQueue {
direction source_dir)
{
assert(light <= LIGHT_SUN);
lights[light].push_back(
ChangingLight(rel_pos, block_pos, block, source_dir));
lights[light].emplace_back(rel_pos, block_pos, block, source_dir);
}
};
@ -611,8 +605,7 @@ void update_lighting_nodes(Map *map,
bool is_valid_position;
// Process each light bank separately
for (s32 i = 0; i < 2; i++) {
LightBank bank = banks[i];
for (LightBank bank : banks) {
UnlightQueue disappearing_lights(256);
ReLightQueue light_sources(256);
// Nodes that are brighter than the brightest modified node was
@ -663,8 +656,8 @@ void update_lighting_nodes(Map *map,
new_light = LIGHT_SUN;
} else {
new_light = ndef->get(n).light_source;
for (int i = 0; i < 6; i++) {
v3s16 p2 = p + neighbor_dirs[i];
for (const v3s16 &neighbor_dir : neighbor_dirs) {
v3s16 p2 = p + neighbor_dir;
bool is_valid;
MapNode n2 = map->getNodeNoEx(p2, &is_valid);
if (is_valid) {
@ -813,8 +806,8 @@ bool is_light_locally_correct(Map *map, INodeDefManager *ndef, LightBank bank,
u8 light = n.getLightNoChecks(bank, &f);
assert(f.light_source <= LIGHT_MAX);
u8 brightest_neighbor = f.light_source + 1;
for (direction d = 0; d < 6; ++d) {
MapNode n2 = map->getNodeNoEx(pos + neighbor_dirs[d],
for (const v3s16 &neighbor_dir : neighbor_dirs) {
MapNode n2 = map->getNodeNoEx(pos + neighbor_dir,
&is_valid_position);
u8 light2 = n2.getLight(bank, ndef);
if (brightest_neighbor < light2) {
@ -830,8 +823,7 @@ void update_block_border_lighting(Map *map, MapBlock *block,
{
INodeDefManager *ndef = map->getNodeDefManager();
bool is_valid_position;
for (s32 i = 0; i < 2; i++) {
LightBank bank = banks[i];
for (LightBank bank : banks) {
// Since invalid light is not common, do not allocate
// memory if not needed.
UnlightQueue disappearing_lights(0);
@ -1213,8 +1205,7 @@ void blit_back_with_light(ServerMap *map, MMVManip *vm,
data.target_block = v3s16(x, minblock.Y - 1, z);
for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
data.data.push_back(
SunlightPropagationUnit(v2s16(x, z), lights[z][x]));
data.data.emplace_back(v2s16(x, z), lights[z][x]);
// Propagate sunlight and shadow below the voxel manipulator.
while (!data.data.empty()) {
if (propagate_block_sunlight(map, ndef, &data, &unlight[0],
@ -1241,8 +1232,7 @@ void blit_back_with_light(ServerMap *map, MMVManip *vm,
continue;
v3s16 offset = block->getPosRelative();
// For each border of the block:
for (direction d = 0; d < 6; d++) {
VoxelArea a = block_pad[d];
for (const VoxelArea &a : block_pad) {
// For each node of the border:
for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++)
for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++)
@ -1353,8 +1343,7 @@ void repair_block_light(ServerMap *map, MapBlock *block,
data.target_block = v3s16(blockpos.X, blockpos.Y - 1, blockpos.Z);
for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
for (s16 x = 0; x < MAP_BLOCKSIZE; x++) {
data.data.push_back(
SunlightPropagationUnit(v2s16(x, z), lights[z][x]));
data.data.emplace_back(v2s16(x, z), lights[z][x]);
}
// Propagate sunlight and shadow below the voxel manipulator.
while (!data.data.empty()) {
@ -1369,8 +1358,7 @@ void repair_block_light(ServerMap *map, MapBlock *block,
// --- STEP 2: Get nodes from borders to unlight
// For each border of the block:
for (direction d = 0; d < 6; d++) {
VoxelArea a = block_pad[d];
for (const VoxelArea &a : block_pad) {
// For each node of the border:
for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++)
for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++)

@ -146,10 +146,8 @@ public:
// Destructor
virtual ~ExtrusionMeshCache()
{
for (std::map<int, scene::IMesh*>::iterator
it = m_extrusion_meshes.begin();
it != m_extrusion_meshes.end(); ++it) {
it->second->drop();
for (auto &extrusion_meshe : m_extrusion_meshes) {
extrusion_meshe.second->drop();
}
m_cube->drop();
}
@ -309,14 +307,15 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client)
m_base_color = idef->getItemstackColor(item, client);
// If wield_image is defined, it overrides everything else
if (def.wield_image != "") {
if (!def.wield_image.empty()) {
setExtruded(def.wield_image, def.wield_scale, tsrc, 1);
m_colors.push_back(ItemPartColor());
m_colors.emplace_back();
return;
}
// Handle nodes
// See also CItemDefManager::createClientCached()
else if (def.type == ITEM_NODE) {
if (def.type == ITEM_NODE) {
if (f.mesh_ptr[0]) {
// e.g. mesh nodes and nodeboxes
scene::SMesh *mesh = cloneMesh(f.mesh_ptr[0]);
@ -377,9 +376,9 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client)
}
return;
}
else if (def.inventory_image != "") {
else if (!def.inventory_image.empty()) {
setExtruded(def.inventory_image, def.wield_scale, tsrc, 1);
m_colors.push_back(ItemPartColor());
m_colors.emplace_back();
return;
}
@ -455,9 +454,9 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result)
result->needs_shading = true;
// If inventory_image is defined, it overrides everything else
if (def.inventory_image != "") {
if (!def.inventory_image.empty()) {
mesh = getExtrudedMesh(tsrc, def.inventory_image);
result->buffer_colors.push_back(ItemPartColor());
result->buffer_colors.emplace_back();
// Items with inventory images do not need shading
result->needs_shading = false;
} else if (def.type == ITEM_NODE) {
@ -560,7 +559,7 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
}
void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f,
bool use_shaders, bool set_material, video::E_MATERIAL_TYPE *mattype,
bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype,
std::vector<ItemPartColor> *colors)
{
u32 mc = mesh->getMeshBufferCount();

@ -44,7 +44,7 @@ struct ItemPartColor
*/
video::SColor color = 0;
ItemPartColor() {}
ItemPartColor() = default;
ItemPartColor(bool override, video::SColor color)
: override_base(override), color(color)
@ -65,7 +65,7 @@ struct ItemMesh
*/
bool needs_shading = true;
ItemMesh() {}
ItemMesh() = default;
};
/*
@ -135,5 +135,5 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename
* \param colors returns the colors of the mesh buffers in the mesh.
*/
void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders,
bool set_material, video::E_MATERIAL_TYPE *mattype,
bool set_material, const video::E_MATERIAL_TYPE *mattype,
std::vector<ItemPartColor> *colors);