Code optimizations / refactor (#12704)

Co-authored-by: SmallJoker <SmallJoker@users.noreply.github.com>
Co-authored-by: sfan5 <sfan5@live.de>
This commit is contained in:
Herman Semenov 2022-09-06 13:21:09 +03:00 committed by GitHub
parent ff6dcfea82
commit 038da00e79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 84 additions and 94 deletions

@ -676,11 +676,12 @@ void Camera::drawNametags()
screen_pos.Y = screensize.Y * screen_pos.Y = screensize.Y *
(0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2; (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
core::rect<s32> size(0, 0, textsize.Width, textsize.Height); core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
core::rect<s32> bg_size(-2, 0, textsize.Width+2, textsize.Height);
auto bgcolor = nametag->getBgColor(m_show_nametag_backgrounds); auto bgcolor = nametag->getBgColor(m_show_nametag_backgrounds);
if (bgcolor.getAlpha() != 0) if (bgcolor.getAlpha() != 0) {
core::rect<s32> bg_size(-2, 0, textsize.Width + 2, textsize.Height);
driver->draw2DRectangle(bgcolor, bg_size + screen_pos); driver->draw2DRectangle(bgcolor, bg_size + screen_pos);
}
font->draw( font->draw(
translate_string(utf8_to_wide(nametag->text)).c_str(), translate_string(utf8_to_wide(nametag->text)).c_str(),

@ -417,7 +417,7 @@ bool ClientLauncher::launch_game(std::string &error_message,
menudata.name = start_data.name; menudata.name = start_data.name;
menudata.password = start_data.password; menudata.password = start_data.password;
menudata.port = itos(start_data.socket_port); menudata.port = itos(start_data.socket_port);
menudata.script_data.errormessage = error_message_lua; menudata.script_data.errormessage = std::move(error_message_lua);
menudata.script_data.reconnect_requested = reconnect_requested; menudata.script_data.reconnect_requested = reconnect_requested;
main_menu(&menudata); main_menu(&menudata);
@ -582,8 +582,8 @@ void ClientLauncher::speed_tests()
TimeTaker timer("Testing std::string speed"); TimeTaker timer("Testing std::string speed");
const u32 jj = 10000; const u32 jj = 10000;
for (u32 j = 0; j < jj; j++) { for (u32 j = 0; j < jj; j++) {
tempstring = ""; tempstring.clear();
tempstring2 = ""; tempstring2.clear();
const u32 ii = 10; const u32 ii = 10;
for (u32 i = 0; i < ii; i++) { for (u32 i = 0; i < ii; i++) {
tempstring2 += "asd"; tempstring2 += "asd";

@ -840,8 +840,6 @@ void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir,
v3s16 p_blocks_max; v3s16 p_blocks_max;
getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length); getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
std::vector<v2s16> blocks_in_range;
for (auto &i : m_drawlist_shadow) { for (auto &i : m_drawlist_shadow) {
MapBlock *block = i.second; MapBlock *block = i.second;
block->refDrop(); block->refDrop();

@ -112,7 +112,7 @@ struct TextDestPlayerInventory : public TextDest
TextDestPlayerInventory(Client *client) TextDestPlayerInventory(Client *client)
{ {
m_client = client; m_client = client;
m_formname = ""; m_formname.clear();
} }
TextDestPlayerInventory(Client *client, const std::string &formname) TextDestPlayerInventory(Client *client, const std::string &formname)
{ {
@ -2985,14 +2985,15 @@ void Game::updateCamera(f32 dtime)
camera->update(player, dtime, tool_reload_ratio); camera->update(player, dtime, tool_reload_ratio);
camera->step(dtime); camera->step(dtime);
v3f camera_position = camera->getPosition();
v3f camera_direction = camera->getDirection();
f32 camera_fov = camera->getFovMax(); f32 camera_fov = camera->getFovMax();
v3s16 camera_offset = camera->getOffset(); v3s16 camera_offset = camera->getOffset();
m_camera_offset_changed = (camera_offset != old_camera_offset); m_camera_offset_changed = (camera_offset != old_camera_offset);
if (!m_flags.disable_camera_update) { if (!m_flags.disable_camera_update) {
v3f camera_position = camera->getPosition();
v3f camera_direction = camera->getDirection();
client->getEnv().getClientMap().updateCamera(camera_position, client->getEnv().getClientMap().updateCamera(camera_position,
camera_direction, camera_fov, camera_offset); camera_direction, camera_fov, camera_offset);
@ -3149,7 +3150,7 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud)
runData.punching = false; runData.punching = false;
soundmaker->m_player_leftpunch_sound.name = ""; soundmaker->m_player_leftpunch_sound.name.clear();
// Prepare for repeating, unless we're not supposed to // Prepare for repeating, unless we're not supposed to
if (isKeyDown(KeyType::PLACE) && !g_settings->getBool("safe_dig_and_place")) if (isKeyDown(KeyType::PLACE) && !g_settings->getBool("safe_dig_and_place"))

@ -411,7 +411,7 @@ void Hud::drawLuaElements(const v3s16 &camera_offset)
case HUD_ELEM_WAYPOINT: { case HUD_ELEM_WAYPOINT: {
if (!calculateScreenPos(camera_offset, e, &pos)) if (!calculateScreenPos(camera_offset, e, &pos))
break; break;
v3f p_pos = player->getPosition() / BS;
pos += v2s32(e->offset.X, e->offset.Y); pos += v2s32(e->offset.X, e->offset.Y);
video::SColor color(255, (e->number >> 16) & 0xFF, video::SColor color(255, (e->number >> 16) & 0xFF,
(e->number >> 8) & 0xFF, (e->number >> 8) & 0xFF,
@ -429,6 +429,7 @@ void Hud::drawLuaElements(const v3s16 &camera_offset)
font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() / 2, 0), color); font->draw(text.c_str(), bounds + v2s32((e->align.X - 1.0) * bounds.getWidth() / 2, 0), color);
if (draw_precision) { if (draw_precision) {
std::ostringstream os; std::ostringstream os;
v3f p_pos = player->getPosition() / BS;
float distance = std::floor(precision * p_pos.getDistanceFrom(e->world_pos)) / precision; float distance = std::floor(precision * p_pos.getDistanceFrom(e->world_pos)) / precision;
os << distance << unit; os << distance << unit;
text = unescape_translate(utf8_to_wide(os.str())); text = unescape_translate(utf8_to_wide(os.str()));

@ -111,8 +111,6 @@ void imageCleanTransparent(video::IImage *src, u32 threshold)
if (bitmap.get(ctrx, ctry)) if (bitmap.get(ctrx, ctry))
continue; continue;
video::SColor c = src->getPixel(ctrx, ctry);
// Sample size and total weighted r, g, b values // Sample size and total weighted r, g, b values
u32 ss = 0, sr = 0, sg = 0, sb = 0; u32 ss = 0, sr = 0, sg = 0, sb = 0;
@ -137,6 +135,7 @@ void imageCleanTransparent(video::IImage *src, u32 threshold)
// Set pixel to average weighted by alpha // Set pixel to average weighted by alpha
if (ss > 0) { if (ss > 0) {
video::SColor c = src->getPixel(ctrx, ctry);
c.setRed(sr / ss); c.setRed(sr / ss);
c.setGreen(sg / ss); c.setGreen(sg / ss);
c.setBlue(sb / ss); c.setBlue(sb / ss);

@ -332,7 +332,7 @@ KeyPress::KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character)
else else
m_name = lookup_keychar(Char).Name; m_name = lookup_keychar(Char).Name;
} catch (UnknownKeycode &e) { } catch (UnknownKeycode &e) {
m_name = ""; m_name.clear();
}; };
} }

@ -327,7 +327,7 @@ void Minimap::addMode(MinimapModeDef mode)
int zoom = -1; int zoom = -1;
// Build a default standard label // Build a default standard label
if (mode.label == "") { if (mode.label.empty()) {
switch (mode.type) { switch (mode.type) {
case MINIMAP_TYPE_OFF: case MINIMAP_TYPE_OFF:
mode.label = gettext("Minimap hidden"); mode.label = gettext("Minimap hidden");
@ -361,8 +361,8 @@ void Minimap::addMode(MinimapModeDef mode)
m_modes.push_back(mode); m_modes.push_back(mode);
} }
void Minimap::addMode(MinimapType type, u16 size, std::string label, void Minimap::addMode(MinimapType type, u16 size, const std::string &label,
std::string texture, u16 scale) const std::string &texture, u16 scale)
{ {
MinimapModeDef mode; MinimapModeDef mode;
mode.type = type; mode.type = type;

@ -130,8 +130,8 @@ public:
void clearModes() { m_modes.clear(); }; void clearModes() { m_modes.clear(); };
void addMode(MinimapModeDef mode); void addMode(MinimapModeDef mode);
void addMode(MinimapType type, u16 size = 0, std::string label = "", void addMode(MinimapType type, u16 size = 0, const std::string &label = "",
std::string texture = "", u16 scale = 1); const std::string &texture = "", u16 scale = 1);
void setModeIndex(size_t index); void setModeIndex(size_t index);
size_t getModeIndex() const { return m_current_mode_index; }; size_t getModeIndex() const { return m_current_mode_index; };

@ -184,7 +184,7 @@ public:
ShaderCallback(const Factories &factories) ShaderCallback(const Factories &factories)
{ {
for (auto &&factory : factories) for (auto &&factory : factories)
m_setters.push_back(std::unique_ptr<IShaderConstantSetter>(factory->create())); m_setters.emplace_back(factory->create());
} }
virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) override
@ -402,7 +402,7 @@ public:
void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) override void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) override
{ {
m_setter_factories.push_back(std::unique_ptr<IShaderConstantSetterFactory>(setter)); m_setter_factories.emplace_back(setter);
} }
private: private:

@ -409,7 +409,7 @@ public:
} }
std::vector<SoundBuffer*> bufs; std::vector<SoundBuffer*> bufs;
bufs.push_back(buf); bufs.push_back(buf);
m_buffers[name] = bufs; m_buffers[name] = std::move(bufs);
} }
SoundBuffer* getBuffer(const std::string &name) SoundBuffer* getBuffer(const std::string &name)

@ -979,8 +979,9 @@ video::IImage* TextureSource::generateImage(const std::string &name)
<< std::endl; << std::endl;
return NULL; return NULL;
} }
core::dimension2d<u32> dim = tmp->getDimension();
if (baseimg) { if (baseimg) {
core::dimension2d<u32> dim = tmp->getDimension();
blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim); blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim);
tmp->drop(); tmp->drop();
} else { } else {

@ -227,7 +227,7 @@ void ModConfiguration::resolveDependencies()
// Step 2: get dependencies (including optional dependencies) // Step 2: get dependencies (including optional dependencies)
// of each mod, split mods into satisfied and unsatisfied // of each mod, split mods into satisfied and unsatisfied
std::list<ModSpec> satisfied; std::vector<ModSpec> satisfied;
std::list<ModSpec> unsatisfied; std::list<ModSpec> unsatisfied;
for (ModSpec mod : m_unsatisfied_mods) { for (ModSpec mod : m_unsatisfied_mods) {
mod.unsatisfied_depends = mod.depends; mod.unsatisfied_depends = mod.depends;

@ -36,7 +36,7 @@ void Database_Dummy::loadBlock(const v3s16 &pos, std::string *block)
s64 i = getBlockAsInteger(pos); s64 i = getBlockAsInteger(pos);
auto it = m_database.find(i); auto it = m_database.find(i);
if (it == m_database.end()) { if (it == m_database.end()) {
*block = ""; block->clear();
return; return;
} }

@ -497,5 +497,5 @@ Json::Value *ModMetadataDatabaseFiles::getOrCreateJson(const std::string &modnam
} }
} }
return &(m_mod_meta[modname] = meta); return &(m_mod_meta[modname] = std::move(meta));
} }

@ -639,7 +639,7 @@ std::string RemoveLastPathComponent(const std::string &path,
std::string *removed, int count) std::string *removed, int count)
{ {
if(removed) if(removed)
*removed = ""; removed->clear();
size_t remaining = path.size(); size_t remaining = path.size();

@ -329,10 +329,9 @@ void GUIButton::draw()
if (SpriteBank) if (SpriteBank)
{ {
core::position2di pos(buttonCenter);
if (isEnabled()) if (isEnabled())
{ {
core::position2di pos(buttonCenter);
// pressed / unpressed animation // pressed / unpressed animation
EGUI_BUTTON_STATE state = Pressed ? EGBS_BUTTON_DOWN : EGBS_BUTTON_UP; EGUI_BUTTON_STATE state = Pressed ? EGBS_BUTTON_DOWN : EGBS_BUTTON_UP;
drawSprite(state, ClickTime, pos); drawSprite(state, ClickTime, pos);

@ -195,7 +195,7 @@ GUIEngine::GUIEngine(JoystickController *joystick,
try { try {
m_script->setMainMenuData(&m_data->script_data); m_script->setMainMenuData(&m_data->script_data);
m_data->script_data.errormessage = ""; m_data->script_data.errormessage.clear();
if (!loadMainMenuScript()) { if (!loadMainMenuScript()) {
errorstream << "No future without main menu!" << std::endl; errorstream << "No future without main menu!" << std::endl;

@ -694,7 +694,7 @@ void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &elemen
e->setMax(max); e->setMax(max);
e->setMin(min); e->setMin(min);
e->setPos(stoi(parts[4])); e->setPos(stoi(value));
e->setSmallStep(data->scrollbar_options.small_step); e->setSmallStep(data->scrollbar_options.small_step);
e->setLargeStep(data->scrollbar_options.large_step); e->setLargeStep(data->scrollbar_options.large_step);
@ -1180,7 +1180,6 @@ void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element)
std::string name = parts[2]; std::string name = parts[2];
std::vector<std::string> items = split(parts[3],','); std::vector<std::string> items = split(parts[3],',');
std::string str_initial_selection; std::string str_initial_selection;
std::string str_transparent = "false";
if (parts.size() >= 5) if (parts.size() >= 5)
str_initial_selection = parts[4]; str_initial_selection = parts[4];
@ -2264,7 +2263,7 @@ void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &
} }
// bgcolor // bgcolor
if (parameter_count >= 1 && parts[0] != "") if (parameter_count >= 1 && !parts[0].empty())
parseColorString(parts[0], m_bgcolor, false); parseColorString(parts[0], m_bgcolor, false);
// fullscreen // fullscreen
@ -2275,14 +2274,14 @@ void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &
} else if (parts[1] == "neither") { } else if (parts[1] == "neither") {
m_bgnonfullscreen = false; m_bgnonfullscreen = false;
m_bgfullscreen = false; m_bgfullscreen = false;
} else if (parts[1] != "" || m_formspec_version < 3) { } else if (!parts[1].empty() || m_formspec_version < 3) {
m_bgfullscreen = is_yes(parts[1]); m_bgfullscreen = is_yes(parts[1]);
m_bgnonfullscreen = !m_bgfullscreen; m_bgnonfullscreen = !m_bgfullscreen;
} }
} }
// fbgcolor // fbgcolor
if (parameter_count >= 3 && parts[2] != "") if (parameter_count >= 3 && !parts[2].empty())
parseColorString(parts[2], m_fullscreen_bgcolor, false); parseColorString(parts[2], m_fullscreen_bgcolor, false);
} }
@ -3047,7 +3046,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
} }
} else { } else {
// Don't keep old focus value // Don't keep old focus value
m_focused_element = ""; m_focused_element.clear();
} }
// Remove children // Remove children
@ -3865,7 +3864,7 @@ void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode)
if (!current_field_enter_pending.empty()) { if (!current_field_enter_pending.empty()) {
fields["key_enter_field"] = current_field_enter_pending; fields["key_enter_field"] = current_field_enter_pending;
current_field_enter_pending = ""; current_field_enter_pending.clear();
} }
if (current_keys_pending.key_escape) { if (current_keys_pending.key_escape) {
@ -4600,7 +4599,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
} else if (s.ftype == f_ScrollBar) { } else if (s.ftype == f_ScrollBar) {
s.fdefault = L"Changed"; s.fdefault = L"Changed";
acceptInput(quit_mode_no); acceptInput(quit_mode_no);
s.fdefault = L""; s.fdefault.clear();
} else if (s.ftype == f_Unknown || s.ftype == f_HyperText) { } else if (s.ftype == f_Unknown || s.ftype == f_HyperText) {
if (!s.sound.empty() && m_sound_manager) if (!s.sound.empty() && m_sound_manager)
m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f)); m_sound_manager->playSound(SimpleSoundSpec(s.sound, 1.0f));

@ -86,9 +86,10 @@ void GUIScene::draw()
core::rect<s32> oldViewPort = m_driver->getViewPort(); core::rect<s32> oldViewPort = m_driver->getViewPort();
m_driver->setViewPort(getAbsoluteClippingRect()); m_driver->setViewPort(getAbsoluteClippingRect());
core::recti borderRect = Environment->getRootGUIElement()->getAbsoluteClippingRect();
if (m_bgcolor != 0) { if (m_bgcolor != 0) {
core::recti borderRect =
Environment->getRootGUIElement()->getAbsoluteClippingRect();
Environment->getSkin()->draw3DSunkenPane( Environment->getSkin()->draw3DSunkenPane(
this, m_bgcolor, false, true, borderRect, 0); this, m_bgcolor, false, true, borderRect, 0);
} }

@ -99,14 +99,14 @@ void ItemDefinition::resetInitial()
void ItemDefinition::reset() void ItemDefinition::reset()
{ {
type = ITEM_NONE; type = ITEM_NONE;
name = ""; name.clear();
description = ""; description.clear();
short_description = ""; short_description.clear();
inventory_image = ""; inventory_image.clear();
inventory_overlay = ""; inventory_overlay.clear();
wield_image = ""; wield_image.clear();
wield_overlay = ""; wield_overlay.clear();
palette_image = ""; palette_image.clear();
color = video::SColor(0xFFFFFFFF); color = video::SColor(0xFFFFFFFF);
wield_scale = v3f(1.0, 1.0, 1.0); wield_scale = v3f(1.0, 1.0, 1.0);
stack_max = 99; stack_max = 99;
@ -118,7 +118,7 @@ void ItemDefinition::reset()
sound_place = SimpleSoundSpec(); sound_place = SimpleSoundSpec();
sound_place_failed = SimpleSoundSpec(); sound_place_failed = SimpleSoundSpec();
range = -1; range = -1;
node_placement_prediction = ""; node_placement_prediction.clear();
place_param2 = 0; place_param2 = 0;
} }
@ -462,7 +462,7 @@ public:
// "ignore" is the ignore node // "ignore" is the ignore node
ItemDefinition* hand_def = new ItemDefinition; ItemDefinition* hand_def = new ItemDefinition;
hand_def->name = ""; hand_def->name.clear();
hand_def->wield_image = "wieldhand.png"; hand_def->wield_image = "wieldhand.png";
hand_def->tool_capabilities = new ToolCapabilities; hand_def->tool_capabilities = new ToolCapabilities;
m_item_definitions.insert(std::make_pair("", hand_def)); m_item_definitions.insert(std::make_pair("", hand_def));

@ -484,7 +484,7 @@ static bool setup_log_params(const Settings &cmd_args)
color_mode = color_mode_env; color_mode = color_mode_env;
#endif #endif
} }
if (color_mode != "") { if (!color_mode.empty()) {
if (color_mode == "auto") { if (color_mode == "auto") {
Logger::color_mode = LOG_COLOR_AUTO; Logger::color_mode = LOG_COLOR_AUTO;
} else if (color_mode == "always") { } else if (color_mode == "always") {
@ -586,7 +586,7 @@ static void startup_message()
static bool read_config_file(const Settings &cmd_args) static bool read_config_file(const Settings &cmd_args)
{ {
// Path of configuration file in use // Path of configuration file in use
sanity_check(g_settings_path == ""); // Sanity check sanity_check(g_settings_path.empty()); // Sanity check
if (cmd_args.exists("config")) { if (cmd_args.exists("config")) {
bool r = g_settings->readConfigFile(cmd_args.get("config").c_str()); bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
@ -793,7 +793,7 @@ static bool auto_select_world(GameParams *game_params)
<< world_path << "]" << std::endl; << world_path << "]" << std::endl;
} }
assert(world_path != ""); // Post-condition assert(!world_path.empty()); // Post-condition
game_params->world_path = world_path; game_params->world_path = world_path;
return true; return true;
} }
@ -849,7 +849,7 @@ static bool determine_subgame(GameParams *game_params)
{ {
SubgameSpec gamespec; SubgameSpec gamespec;
assert(game_params->world_path != ""); // Pre-condition assert(!game_params->world_path.empty()); // Pre-condition
// If world doesn't exist // If world doesn't exist
if (!game_params->world_path.empty() if (!game_params->world_path.empty()

@ -533,7 +533,7 @@ void ServerMap::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks,
infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/ infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/
// list of nodes that due to viscosity have not reached their max level height // list of nodes that due to viscosity have not reached their max level height
std::deque<v3s16> must_reflow; std::vector<v3s16> must_reflow;
std::vector<std::pair<v3s16, MapNode> > changed_nodes; std::vector<std::pair<v3s16, MapNode> > changed_nodes;
@ -835,7 +835,7 @@ void ServerMap::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks,
} }
//infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl; //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl;
for (auto &iter : must_reflow) for (const auto &iter : must_reflow)
m_transforming_liquid.push_back(iter); m_transforming_liquid.push_back(iter);
voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks); voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks);

@ -234,7 +234,6 @@ bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags, void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags,
Rotation rot, bool force_place) Rotation rot, bool force_place)
{ {
std::map<v3s16, MapBlock *> lighting_modified_blocks;
std::map<v3s16, MapBlock *> modified_blocks; std::map<v3s16, MapBlock *> modified_blocks;
std::map<v3s16, MapBlock *>::iterator it; std::map<v3s16, MapBlock *>::iterator it;

@ -152,7 +152,7 @@ void Client::handleCommand_AuthAccept(NetworkPacket* pkt)
language code (e.g. "de" for German). */ language code (e.g. "de" for German). */
std::string lang = gettext("LANG_CODE"); std::string lang = gettext("LANG_CODE");
if (lang == "LANG_CODE") if (lang == "LANG_CODE")
lang = ""; lang.clear();
NetworkPacket resp_pkt(TOSERVER_INIT2, sizeof(u16) + lang.size()); NetworkPacket resp_pkt(TOSERVER_INIT2, sizeof(u16) + lang.size());
resp_pkt << lang; resp_pkt << lang;

@ -64,7 +64,7 @@ BufferedPacketPtr makePacket(Address &address, const SharedBuffer<u8> &data,
{ {
u32 packet_size = data.getSize() + BASE_HEADER_SIZE; u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
BufferedPacketPtr p(new BufferedPacket(packet_size)); auto p = std::make_shared<BufferedPacket>(packet_size);
p->address = address; p->address = address;
writeU32(&p->data[0], protocol_id); writeU32(&p->data[0], protocol_id);
@ -492,10 +492,10 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacketPtr &p_ptr, bool reli
void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout) void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
{ {
std::deque<u16> remove_queue; std::vector<u16> remove_queue;
{ {
MutexAutoLock listlock(m_map_mutex); MutexAutoLock listlock(m_map_mutex);
for (auto &i : m_buf) { for (const auto &i : m_buf) {
IncomingSplitPacket *p = i.second; IncomingSplitPacket *p = i.second;
// Reliable ones are not removed by timeout // Reliable ones are not removed by timeout
if (p->reliable) if (p->reliable)

@ -354,12 +354,12 @@ void ContentFeatures::reset()
NOTE: Most of this is always overridden by the default values given NOTE: Most of this is always overridden by the default values given
in builtin.lua in builtin.lua
*/ */
name = ""; name.clear();
groups.clear(); groups.clear();
// Unknown nodes can be dug // Unknown nodes can be dug
groups["dig_immediate"] = 2; groups["dig_immediate"] = 2;
drawtype = NDT_NORMAL; drawtype = NDT_NORMAL;
mesh = ""; mesh.clear();
#ifndef SERVER #ifndef SERVER
for (auto &i : mesh_ptr) for (auto &i : mesh_ptr)
i = NULL; i = NULL;
@ -387,9 +387,9 @@ void ContentFeatures::reset()
leveled = 0; leveled = 0;
leveled_max = LEVELED_MAX; leveled_max = LEVELED_MAX;
liquid_type = LIQUID_NONE; liquid_type = LIQUID_NONE;
liquid_alternative_flowing = ""; liquid_alternative_flowing.clear();
liquid_alternative_flowing_id = CONTENT_IGNORE; liquid_alternative_flowing_id = CONTENT_IGNORE;
liquid_alternative_source = ""; liquid_alternative_source.clear();
liquid_alternative_source_id = CONTENT_IGNORE; liquid_alternative_source_id = CONTENT_IGNORE;
liquid_viscosity = 0; liquid_viscosity = 0;
liquid_renewable = true; liquid_renewable = true;
@ -410,7 +410,7 @@ void ContentFeatures::reset()
connects_to_ids.clear(); connects_to_ids.clear();
connect_sides = 0; connect_sides = 0;
color = video::SColor(0xFFFFFFFF); color = video::SColor(0xFFFFFFFF);
palette_name = ""; palette_name.clear();
palette = NULL; palette = NULL;
node_dig_prediction = "air"; node_dig_prediction = "air";
move_resistance = 0; move_resistance = 0;
@ -1355,7 +1355,7 @@ void NodeDefManager::eraseIdFromGroups(content_t id)
content_t NodeDefManager::set(const std::string &name, const ContentFeatures &def) content_t NodeDefManager::set(const std::string &name, const ContentFeatures &def)
{ {
// Pre-conditions // Pre-conditions
assert(name != ""); assert(!name.empty());
assert(name != "ignore"); assert(name != "ignore");
assert(name == def.name); assert(name == def.name);
@ -1395,7 +1395,7 @@ content_t NodeDefManager::set(const std::string &name, const ContentFeatures &de
content_t NodeDefManager::allocateDummy(const std::string &name) content_t NodeDefManager::allocateDummy(const std::string &name)
{ {
assert(name != ""); // Pre-condition assert(!name.empty()); // Pre-condition
ContentFeatures f; ContentFeatures f;
f.name = name; f.name = name;
return set(name, f); return set(name, f);
@ -1405,7 +1405,7 @@ content_t NodeDefManager::allocateDummy(const std::string &name)
void NodeDefManager::removeNode(const std::string &name) void NodeDefManager::removeNode(const std::string &name)
{ {
// Pre-condition // Pre-condition
assert(name != ""); assert(!name.empty());
// Erase name from name ID mapping // Erase name from name ID mapping
content_t id = CONTENT_IGNORE; content_t id = CONTENT_IGNORE;

@ -93,15 +93,11 @@ public:
} }
} }
// Undefined behaviour if there already is a timer // Undefined behaviour if there already is a timer
void insert(NodeTimer timer) { void insert(const NodeTimer &timer) {
v3s16 p = timer.position; v3s16 p = timer.position;
double trigger_time = m_time + (double)(timer.timeout - timer.elapsed); double trigger_time = m_time + (double)(timer.timeout - timer.elapsed);
std::multimap<double, NodeTimer>::iterator it = std::multimap<double, NodeTimer>::iterator it = m_timers.emplace(trigger_time, timer);
m_timers.insert(std::pair<double, NodeTimer>( m_iterators.emplace(p, it);
trigger_time, timer
));
m_iterators.insert(
std::pair<v3s16, std::multimap<double, NodeTimer>::iterator>(p, it));
if (m_next_trigger_time == -1. || trigger_time < m_next_trigger_time) if (m_next_trigger_time == -1. || trigger_time < m_next_trigger_time)
m_next_trigger_time = trigger_time; m_next_trigger_time = trigger_time;
} }

@ -481,7 +481,7 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype)
else if(lua_istable(L, index)) else if(lua_istable(L, index))
{ {
// name="default_lava.png" // name="default_lava.png"
tiledef.name = ""; tiledef.name.clear();
getstringfield(L, index, "name", tiledef.name); getstringfield(L, index, "name", tiledef.name);
getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat. getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
tiledef.backface_culling = getboolfield_default( tiledef.backface_culling = getboolfield_default(

@ -171,7 +171,7 @@ void ScriptApiBase::clientOpenLibs(lua_State *L)
#endif #endif
}; };
for (const std::pair<std::string, lua_CFunction> &lib : m_libs) { for (const auto &lib : m_libs) {
lua_pushcfunction(L, lib.second); lua_pushcfunction(L, lib.second);
lua_pushstring(L, lib.first.c_str()); lua_pushstring(L, lib.first.c_str());
lua_call(L, 1, 0); lua_call(L, 1, 0);

@ -237,7 +237,7 @@ int ModApiClient::l_get_language(lua_State *L)
#endif #endif
std::string lang = gettext("LANG_CODE"); std::string lang = gettext("LANG_CODE");
if (lang == "LANG_CODE") if (lang == "LANG_CODE")
lang = ""; lang.clear();
lua_pushstring(L, locale); lua_pushstring(L, locale);
lua_pushstring(L, lang.c_str()); lua_pushstring(L, lang.c_str());

@ -600,7 +600,7 @@ int ModApiItemMod::l_register_item_raw(lua_State *L)
if(def.type == ITEM_NODE) if(def.type == ITEM_NODE)
def.node_placement_prediction = name; def.node_placement_prediction = name;
else else
def.node_placement_prediction = ""; def.node_placement_prediction.clear();
} }
// Register item definition // Register item definition

@ -424,7 +424,7 @@ void Server::init()
m_mod_storage_database->beginSave(); m_mod_storage_database->beginSave();
m_modmgr = std::make_unique<ServerModManager>(m_path_world); m_modmgr = std::make_unique<ServerModManager>(m_path_world);
std::vector<ModSpec> unsatisfied_mods = m_modmgr->getUnsatisfiedMods();
// complain about mods with unsatisfied dependencies // complain about mods with unsatisfied dependencies
if (!m_modmgr->isConsistent()) { if (!m_modmgr->isConsistent()) {
std::string error = m_modmgr->getUnsatisfiedModsError(); std::string error = m_modmgr->getUnsatisfiedModsError();
@ -1359,8 +1359,6 @@ void Server::Send(session_t peer_id, NetworkPacket *pkt)
void Server::SendMovement(session_t peer_id) void Server::SendMovement(session_t peer_id)
{ {
std::ostringstream os(std::ios_base::binary);
NetworkPacket pkt(TOCLIENT_MOVEMENT, 12 * sizeof(float), peer_id); NetworkPacket pkt(TOCLIENT_MOVEMENT, 12 * sizeof(float), peer_id);
pkt << g_settings->getFloat("movement_acceleration_default"); pkt << g_settings->getFloat("movement_acceleration_default");

@ -35,7 +35,7 @@ void ToolGroupCap::toJson(Json::Value &object) const
Json::Value times_object; Json::Value times_object;
for (auto time : times) for (auto time : times)
times_object[time.first] = time.second; times_object[time.first] = time.second;
object["times"] = times_object; object["times"] = std::move(times_object);
} }
void ToolGroupCap::fromJson(const Json::Value &json) void ToolGroupCap::fromJson(const Json::Value &json)
@ -134,14 +134,13 @@ void ToolCapabilities::serializeJson(std::ostream &os) const
for (const auto &groupcap : groupcaps) { for (const auto &groupcap : groupcaps) {
groupcap.second.toJson(groupcaps_object[groupcap.first]); groupcap.second.toJson(groupcaps_object[groupcap.first]);
} }
root["groupcaps"] = groupcaps_object; root["groupcaps"] = std::move(groupcaps_object);
Json::Value damage_groups_object; Json::Value damage_groups_object;
DamageGroup::const_iterator dgiter; for (const auto &damagegroup : damageGroups) {
for (dgiter = damageGroups.begin(); dgiter != damageGroups.end(); ++dgiter) { damage_groups_object[damagegroup.first] = damagegroup.second;
damage_groups_object[dgiter->first] = dgiter->second;
} }
root["damage_groups"] = damage_groups_object; root["damage_groups"] = std::move(damage_groups_object);
fastWriteJson(root, os); fastWriteJson(root, os);
} }

@ -238,7 +238,7 @@ void TestFilePath::testRemoveLastPathComponentWithTrailingDelimiter()
void TestFilePath::testRemoveRelativePathComponent() void TestFilePath::testRemoveRelativePathComponent()
{ {
std::string path, result, removed; std::string path, result;
path = p("/home/user/minetest/bin"); path = p("/home/user/minetest/bin");
result = fs::RemoveRelativePathComponents(path); result = fs::RemoveRelativePathComponents(path);

@ -206,7 +206,6 @@ void TestModMetadataDatabase::testRecallFail()
void TestModMetadataDatabase::testCreate() void TestModMetadataDatabase::testCreate()
{ {
ModMetadataDatabase *mod_meta_db = mod_meta_provider->getModMetadataDatabase(); ModMetadataDatabase *mod_meta_db = mod_meta_provider->getModMetadataDatabase();
StringMap recalled;
UASSERT(mod_meta_db->setModEntry("mod1", "key1", "value1")); UASSERT(mod_meta_db->setModEntry("mod1", "key1", "value1"));
} }
@ -222,7 +221,6 @@ void TestModMetadataDatabase::testRecall()
void TestModMetadataDatabase::testChange() void TestModMetadataDatabase::testChange()
{ {
ModMetadataDatabase *mod_meta_db = mod_meta_provider->getModMetadataDatabase(); ModMetadataDatabase *mod_meta_db = mod_meta_provider->getModMetadataDatabase();
StringMap recalled;
UASSERT(mod_meta_db->setModEntry("mod1", "key1", "value2")); UASSERT(mod_meta_db->setModEntry("mod1", "key1", "value2"));
} }

@ -36,7 +36,7 @@ public:
std::string getMessage() std::string getMessage()
{ {
std::string s = m_message; std::string s = m_message;
m_message = ""; m_message.clear();
if (!s.empty()) if (!s.empty())
return std::string("[quicktune] ") + s; return std::string("[quicktune] ") + s;
return ""; return "";

@ -610,7 +610,7 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
} else { } else {
if (si == delim) { if (si == delim) {
tokens.push_back(current); tokens.push_back(current);
current = std::basic_string<T>(); current.clear();
last_was_escape = false; last_was_escape = false;
} else if (si == '\\') { } else if (si == '\\') {
last_was_escape = true; last_was_escape = true;