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),
s32 rows = (s32) m_rows;
if (rows == 0)
return 0;
- else
- return formatted_count - rows;
+
+ return formatted_count - rows;
}
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() {}
#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;
class MtEvent
{
public:
- virtual ~MtEvent() {};
+ virtual ~MtEvent() = default;
//virtual MtEvent* clone(){ return new IEvent; }
virtual const char* getType() const = 0;
class MtEventReceiver
{
public:
- virtual ~MtEventReceiver(){};
+ virtual ~MtEventReceiver() = default;
virtual void onEvent(MtEvent *e) = 0;
};
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.
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;
{
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;
}
}
}
}
} 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));
{
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();
#include "sound_openal.h"
#endif
-extern Settings *g_settings;
-extern Profiler *g_profiler;
/*
Text input system
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;
};
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)
{
// 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()) {
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)
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 =
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();
}
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;
}
// Get new messages from client
- std::wstring message = L"";
+ std::wstring message;
while (client.getChatMessage(message)) {
chat_backend.addUnparsedMessage(message);
}
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);
GameOnDemandSoundFetcher soundfetcher; // useful when testing
ISoundManager *sound;
- bool sound_is_dummy;
+ bool sound_is_dummy = false;
SoundMaker *soundmaker;
ChatBackend *chat_backend;
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;
itemdef_manager(NULL),
nodedef_manager(NULL),
sound(NULL),
- sound_is_dummy(false),
soundmaker(NULL),
chat_backend(NULL),
current_formspec(NULL),
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);
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;
}
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
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 {
}
// Update selection mesh light level and vertex colors
- if (selectionboxes->size() > 0) {
+ if (!selectionboxes->empty()) {
v3f pf = hud->getSelectionPos();
v3s16 p = floatToInt(pf, BS);
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;
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) {
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 {
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(
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_") +
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 {
} 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;
<< 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;
}
#pragma once
#include "irrlichttypes.h"
-#include <time.h>
+#include <ctime>
#include <string>
enum TimePrecision
class IItemDefManager
{
public:
- IItemDefManager(){}
- virtual ~IItemDefManager(){}
+ IItemDefManager() = default;
+
+ virtual ~IItemDefManager() = default;
// Get item definition
virtual const ItemDefinition& get(const std::string &name) const=0;
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;
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;
}
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);
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);
continue;
for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
- if (channel.queued_commands.size() > 0) {
+ if (!channel.queued_commands.empty()) {
return true;
}
}
class PeerHelper
{
public:
- PeerHelper() = default;;
+ PeerHelper() = default;
PeerHelper(Peer* peer);
~PeerHelper();
// 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();
}
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);
}
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");
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))
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);
}
}
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");
{
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);
}
}
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");
param2 = lua_tonumber(L, -1);
lua_pop(L, 1);
- return MapNode(ndef, name, param1, param2);
+ return {ndef, name, param1, param2};
}
/******************************************************************************/
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
// 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"
//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");
}
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());
}
}
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;
}
// 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
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);
int index,
Server* srv);
-void read_soundspec (lua_State *L,
- int index,
- SimpleSoundSpec &spec);
void push_soundspec (lua_State *L,
const SimpleSoundSpec &spec);
#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); \
" (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) { \
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);
#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__)
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"
{
// 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();
}
}
// 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();
/******************************************************************************/
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);
}
}
AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
const std::string &name) :
Thread(name),
- ScriptApiBase(),
jobDispatcher(jobDispatcher)
{
lua_State *L = getStack();
friend class AsyncWorkerThread;
typedef void (*StateInitializer)(lua_State *L, int top);
public:
- AsyncEngine() {};
+ AsyncEngine() = default;
~AsyncEngine();
/**
#endif
}
-#include <stdio.h>
+#include <cstdio>
#include <cstdarg>
#include "script/common/c_content.h"
#include <sstream>
// 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__)
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;
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;
}
bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user)
{
SCRIPTAPI_PRECHECKHEADER
-
+
int error_handler = PUSH_ERROR_HANDLER(L);
-
+
if (!getItemCallback(item.name.c_str(), "on_secondary_use"))
return false;
-
+
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user);
PointedThing pointed;
// 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;
}
{0, NULL},
};
-ScriptApiNode::ScriptApiNode() {
-}
-
-ScriptApiNode::~ScriptApiNode() {
-}
-
bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed)
{
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)
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,
public ScriptApiNodemeta
{
public:
- ScriptApiNode();
- virtual ~ScriptApiNode();
+ ScriptApiNode() = default;
+ virtual ~ScriptApiNode() = default;
bool node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed);
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
-
-ScriptApiNodemeta::ScriptApiNodemeta()
-{
-}
-
-ScriptApiNodemeta::~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,
runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC);
}
-ScriptApiPlayer::~ScriptApiPlayer()
-{
-}
-
-
class ScriptApiPlayer : virtual public ScriptApiBase
{
public:
- virtual ~ScriptApiPlayer();
+ virtual ~ScriptApiPlayer() = default;
void on_newplayer(ServerActiveObject *player);
void on_dieplayer(ServerActiveObject *player);
static const char *os_whitelist[] = {
"clock",
"date",
- "difftime",
+ "difftime",
"time",
"setlocale",
};
// 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())
// 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;
}
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;
#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);
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) {
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);
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])
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);
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++;
}
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);
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);
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++;
}
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);
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);
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);
class MetaDataRef : public ModApiBase
{
public:
- virtual ~MetaDataRef() {}
+ virtual ~MetaDataRef() = default;
protected:
static MetaDataRef *checkobject(lua_State *L, int narg);
float frame_speed;
player->getLocalAnimations(frames, &frame_speed);
- for (v2s32 frame : frames) {
+ for (const v2s32 &frame : frames) {
push_v2s32(L, frame);
}
#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);
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++) {
{
}
- bool exists() const { return name != ""; }
+ bool exists() const { return !name.empty(); }
std::string name = "";
float gain = 1.0f;
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
{
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);
}
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),
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;
std::vector<SoundBuffer*> bufs;
bufs.push_back(buf);
m_buffers[name] = bufs;
- return;
}
SoundBuffer* getBuffer(const std::string &name)
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);
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);
}
<<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;
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);
}
}
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){
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){
}
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);
}
}
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_)
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)
{
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;
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
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
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;
}
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;
{
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;
}
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);
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;
}
bool isValid() const
{
- return (id != "" && path != "");
+ return (!id.empty() && !path.empty());
}
};
bool isValid() const
{
- return (name != "" && path != "" && gameid != "");
+ return (!name.empty() && !path.empty() && !gameid.empty());
}
};
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));
}
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());
}
}
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);
}
}
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);
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,
){
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;
}
int maxlevel = 1;
int uses = 20;
- ToolGroupCap() {}
+ ToolGroupCap() = default;
bool getTime(int rating, float *time) const
{
int damage = 0;
int wear = 0;
- PunchDamageResult() {}
+ PunchDamageResult() = default;
};
struct ItemStack;
using namespace irr::core;
-extern Settings *g_settings;
-
const char** touchgui_button_imagenames = (const char*[]) {
"up_arrow.png",
"down_arrow.png",
void AutoHideButtonBar::deactivate()
{
- if (m_visible == true) {
+ if (m_visible) {
m_starter.guibutton->setVisible(true);
m_starter.guibutton->setEnabled(true);
}
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) {
// 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;
}
//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) {
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++)
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
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();
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
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
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
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)
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)) {
"{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);
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);
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);
"{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);
}
// 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)) { \
<< 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; \
exception_thrown = true; \
} \
UASSERT(exception_thrown); \
-} while (0)
+}
class IGameDef;
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);
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());
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);
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());
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);
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;
}
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++) {
// 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());
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);
}
}
}
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);
}
}
}
struct Area {
- Area() {}
+ Area() = default;
+
Area(const v3s16 &mine, const v3s16 &maxe) :
minedge(mine), maxedge(maxe)
{
m_res_cache(1000, &cacheMiss, this)
{}
- virtual ~AreaStore() {}
+ virtual ~AreaStore() = default;
static AreaStore *getOptimalImplementation();
parseColorString(wide_to_utf8(parts[1]), m_background, true);
m_has_background = true;
}
- continue;
}
}
{
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]);
}
}
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
class IntervalLimiter
{
public:
- IntervalLimiter() {}
+ IntervalLimiter() = default;
+
/*
dtime: time from last call to this method
wanted_interval: interval wanted
goto cleanup_and_exit;
}
- memcpy((char *)ver->username, username, ulen);
+ memcpy(ver->username, username, ulen);
ver->authenticated = 0;
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));
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;
}
// 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 {
#pragma once
#include "irrlichttypes_bloated.h"
-#include <stdlib.h>
+#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
*/
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;
}
*/
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();
#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
u64 emerge_load_time = 0;
u64 clearflag_time = 0;
-
-VoxelManipulator::VoxelManipulator()
-{
-}
-
VoxelManipulator::~VoxelManipulator()
{
clear();
{
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
{
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);
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);
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);
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);
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
{
{
public:
// Starts as zero sized
- VoxelArea() {}
+ VoxelArea() = default;
VoxelArea(const v3s16 &min_edge, const v3s16 &max_edge):
MinEdge(min_edge),
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};
}
/*
class VoxelManipulator
{
public:
- VoxelManipulator();
+ VoxelManipulator() = default;
virtual ~VoxelManipulator();
/*
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)];
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.
} 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);
}
}
- return SunlightPropagateResult(bottom_sunlight_valid);
+ return {bottom_sunlight_valid};
}
/*!
//! 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),
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);
}
};
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
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) {
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) {
{
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);
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],
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++)
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()) {
// --- 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++)
// 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();
}
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]);
}
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;
}
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) {
}
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();
*/
video::SColor color = 0;
- ItemPartColor() {}
+ ItemPartColor() = default;
ItemPartColor(bool override, video::SColor color)
: override_base(override), color(color)
*/
bool needs_shading = true;
- ItemMesh() {}
+ ItemMesh() = default;
};
/*
* \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);