From 8e7449e09253e138716d8dbad6a2ab5c6e089e28 Mon Sep 17 00:00:00 2001 From: Ner'zhul Date: Mon, 9 Jan 2017 20:39:22 +0100 Subject: Environment & IGameDef code refactoring (#4985) * Environment code refactoring * Cleanup includes & class declarations in client & server environment to improve build speed * ServerEnvironment::m_gamedef is now a pointer to Server instead of IGameDef, permitting to cleanup many casts. * Cleanup IGameDef * Move ITextureSource* IGameDef::getTextureSource() to Client only. * Also move ITextureSource *IGameDef::tsrc() helper * drop getShaderSource, getSceneManager, getSoundManager & getCamera abstract call * drop unused emerge() call * cleanup server unused functions (mentionned before) * Drop one unused parameter from ContentFeatures::updateTextures * move checkLocalPrivilege to Client * Remove some unnecessary casts * create_formspec_menu: remove IWritableTextureSource pointer, as client already knows it * Fix some comments * Change required IGameDef to Server/Client pointers * Previous change that game.cpp sometimes calls functions with Client + InventoryManager + IGameDef in same functions but it's the same objects * Remove duplicate Client pointer in GUIFormSpecMenu::GUIFormSpecMenu * drop ClientMap::sectorWasDrawn which is unused --- src/guiFormSpecMenu.h | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 95df11e6a..94b52e6f0 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -34,7 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "util/enriched_string.h" -class IGameDef; class InventoryManager; class ISimpleTextureSource; class Client; @@ -289,12 +288,10 @@ public: JoystickController *joystick, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, - InventoryManager *invmgr, - IGameDef *gamedef, + Client *client, ISimpleTextureSource *tsrc, IFormSource* fs_src, TextDest* txt_dst, - Client* client, bool remap_dbl_click = true); ~GUIFormSpecMenu(); @@ -384,7 +381,6 @@ protected: irr::IrrlichtDevice* m_device; InventoryManager *m_invmgr; - IGameDef *m_gamedef; ISimpleTextureSource *m_tsrc; Client *m_client; -- cgit v1.2.3 From 430d3b28e46b16e1411ec0ecb6c0d0ab9d6feb63 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Wed, 11 Jan 2017 09:03:07 +0100 Subject: Cleanup some header inclusions to improve compilation times --- src/client.h | 1 + src/clientenvironment.cpp | 1 + src/environment.h | 4 ++-- src/guiFormSpecMenu.h | 1 - src/localplayer.cpp | 11 +++++++++++ src/localplayer.h | 11 ++--------- src/minimap.cpp | 1 + src/network/serverpackethandler.cpp | 1 + src/player.h | 1 - src/serverenvironment.h | 3 +++ 10 files changed, 22 insertions(+), 13 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/client.h b/src/client.h index df3e7e605..f84246deb 100644 --- a/src/client.h +++ b/src/client.h @@ -34,6 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "localplayer.h" #include "hud.h" #include "particles.h" +#include "mapnode.h" struct MeshMakeData; class MapBlockMesh; diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index 65646c6b4..b32a02f2d 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -28,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "profiler.h" #include "raycast.h" #include "voxelalgorithms.h" +#include "settings.h" /* ClientEnvironment diff --git a/src/environment.h b/src/environment.h index 0cc3222f9..5154bbdcb 100644 --- a/src/environment.h +++ b/src/environment.h @@ -36,12 +36,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irr_v3d.h" #include "activeobject.h" #include "util/numeric.h" -#include "mapnode.h" -#include "mapblock.h" #include "threading/mutex.h" #include "threading/atomic.h" #include "network/networkprotocol.h" // for AccessDeniedCode +class Map; + class Environment { public: diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 94b52e6f0..2ab7db4f1 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -25,7 +25,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "irrlichttypes_extrabloated.h" -#include "inventory.h" #include "inventorymanager.h" #include "modalMenu.h" #include "guiTable.h" diff --git a/src/localplayer.cpp b/src/localplayer.cpp index b859c6455..857d95d8b 100644 --- a/src/localplayer.cpp +++ b/src/localplayer.cpp @@ -655,6 +655,17 @@ v3s16 LocalPlayer::getStandingNodePos() return floatToInt(getPosition() - v3f(0, BS, 0), BS); } +v3s16 LocalPlayer::getLightPosition() const +{ + return floatToInt(m_position + v3f(0,BS+BS/2,0), BS); +} + +v3f LocalPlayer::getEyeOffset() const +{ + float eye_height = camera_barely_in_ceiling ? 1.5f : 1.625f; + return v3f(0, BS * eye_height, 0); +} + // Horizontal acceleration (X and Z), Y direction is ignored void LocalPlayer::accelerateHorizontal(const v3f &target_speed, const f32 max_increase) { diff --git a/src/localplayer.h b/src/localplayer.h index cbdcb9867..685a78cb3 100644 --- a/src/localplayer.h +++ b/src/localplayer.h @@ -105,10 +105,7 @@ public: u16 getBreath() const { return m_breath; } void setBreath(u16 breath) { m_breath = breath; } - v3s16 getLightPosition() const - { - return floatToInt(m_position + v3f(0,BS+BS/2,0), BS); - } + v3s16 getLightPosition() const; void setYaw(f32 yaw) { @@ -131,11 +128,7 @@ public: v3f getPosition() const { return m_position; } v3f getEyePosition() const { return m_position + getEyeOffset(); } - v3f getEyeOffset() const - { - float eye_height = camera_barely_in_ceiling ? 1.5f : 1.625f; - return v3f(0, BS * eye_height, 0); - } + v3f getEyeOffset() const; private: void accelerateHorizontal(const v3f &target_speed, const f32 max_increase); void accelerateVertical(const v3f &target_speed, const f32 max_increase); diff --git a/src/minimap.cpp b/src/minimap.cpp index 8cd0a7beb..f49adb517 100644 --- a/src/minimap.cpp +++ b/src/minimap.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "porting.h" #include "util/numeric.h" #include "util/string.h" +#include "mapblock.h" #include diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index eeabcca71..408fe7706 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "content_abm.h" #include "content_sao.h" #include "emerge.h" +#include "mapblock.h" #include "nodedef.h" #include "player.h" #include "rollback_interface.h" diff --git a/src/player.h b/src/player.h index 5f9bb7ec9..3432069c0 100644 --- a/src/player.h +++ b/src/player.h @@ -22,7 +22,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_bloated.h" #include "inventory.h" -#include "constants.h" // BS #include "threading/mutex.h" #include diff --git a/src/serverenvironment.h b/src/serverenvironment.h index d71d29a9c..b7056c00c 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -21,6 +21,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #define SERVER_ENVIRONMENT_HEADER #include "environment.h" +#include "mapnode.h" +#include "mapblock.h" +#include class IGameDef; class ServerMap; -- cgit v1.2.3 From 6de83a2756316653ed67b23bbeb0fb43aa2a68c6 Mon Sep 17 00:00:00 2001 From: adelcoding1 Date: Sat, 4 Mar 2017 10:46:55 +0100 Subject: FormSpec: Add position and anchor elements (#5284) --- doc/lua_api.txt | 10 +++++ src/guiFormSpecMenu.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++++---- src/guiFormSpecMenu.h | 6 +++ 3 files changed, 109 insertions(+), 8 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 9c96c41db..7b956dc74 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1522,6 +1522,16 @@ examples. * `fixed_size`: `true`/`false` (optional) * deprecated: `invsize[,;]` +#### `position[,]` +* Define the position of the formspec +* A value between 0.0 and 1.0 represents a position inside the screen +* The default value is the center of the screen (0.5, 0.5) + +#### `anchor[,]` +* Define the anchor of the formspec +* A value between 0.0 and 1.0 represents an anchor inside the formspec +* The default value is the center of the formspec (0.5, 0.5) + #### `container[,]` * Start of a container block, moves all physical elements in the container by (X, Y) * Must have matching container_end diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 67b3a9ad0..ae3fad7c6 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -1706,6 +1706,74 @@ bool GUIFormSpecMenu::parseSizeDirect(parserData* data, std::string element) return true; } +bool GUIFormSpecMenu::parsePositionDirect(parserData *data, const std::string &element) +{ + if (element.empty()) + return false; + + std::vector parts = split(element, '['); + + if (parts.size() != 2) + return false; + + std::string type = trim(parts[0]); + std::string description = trim(parts[1]); + + if (type != "position") + return false; + + parsePosition(data, description); + + return true; +} + +void GUIFormSpecMenu::parsePosition(parserData *data, const std::string &element) +{ + std::vector parts = split(element, ','); + + if (parts.size() == 2) { + data->offset.X = stof(parts[0]); + data->offset.Y = stof(parts[1]); + return; + } + + errorstream << "Invalid position element (" << parts.size() << "): '" << element << "'" << std::endl; +} + +bool GUIFormSpecMenu::parseAnchorDirect(parserData *data, const std::string &element) +{ + if (element.empty()) + return false; + + std::vector parts = split(element, '['); + + if (parts.size() != 2) + return false; + + std::string type = trim(parts[0]); + std::string description = trim(parts[1]); + + if (type != "anchor") + return false; + + parseAnchor(data, description); + + return true; +} + +void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element) +{ + std::vector parts = split(element, ','); + + if (parts.size() == 2) { + data->anchor.X = stof(parts[0]); + data->anchor.Y = stof(parts[1]); + return; + } + + errorstream << "Invalid anchor element (" << parts.size() << "): '" << element << "'" << std::endl; +} + void GUIFormSpecMenu::parseElement(parserData* data, std::string element) { //some prechecks @@ -1917,6 +1985,8 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) mydata.size= v2s32(100,100); mydata.screensize = screensize; + mydata.offset = v2f32(0.5f, 0.5f); + mydata.anchor = v2f32(0.5f, 0.5f); // Base position of contents of form mydata.basepos = getBasePos(); @@ -1983,6 +2053,21 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) } } + /* "position" element is always after "size" element if it used */ + for (; i< elements.size(); i++) { + if (!parsePositionDirect(&mydata, elements[i])) { + break; + } + } + + /* "anchor" element is always after "position" (or "size" element) if it used */ + for (; i< elements.size(); i++) { + if (!parseAnchorDirect(&mydata, elements[i])) { + break; + } + } + + if (mydata.explicit_size) { // compute scaling for specified form size if (m_lock) { @@ -2066,10 +2151,10 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) padding.Y*2+spacing.Y*(mydata.invsize.Y-1.0)+imgsize.Y + m_btn_height*2.0/3.0 ); DesiredRect = mydata.rect = core::rect( - mydata.screensize.X/2 - mydata.size.X/2 + offset.X, - mydata.screensize.Y/2 - mydata.size.Y/2 + offset.Y, - mydata.screensize.X/2 + mydata.size.X/2 + offset.X, - mydata.screensize.Y/2 + mydata.size.Y/2 + offset.Y + (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * (f32)mydata.size.X) + offset.X, + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * (f32)mydata.size.Y) + offset.Y, + (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * (f32)mydata.size.X) + offset.X, + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * (f32)mydata.size.Y) + offset.Y ); } else { // Non-size[] form must consist only of text fields and @@ -2078,10 +2163,10 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize) m_font = g_fontengine->getFont(); m_btn_height = font_line_height(m_font) * 0.875; DesiredRect = core::rect( - mydata.screensize.X/2 - 580/2, - mydata.screensize.Y/2 - 300/2, - mydata.screensize.X/2 + 580/2, - mydata.screensize.Y/2 + 300/2 + (s32)((f32)mydata.screensize.X * mydata.offset.X) - (s32)(mydata.anchor.X * 580.0), + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) - (s32)(mydata.anchor.Y * 300.0), + (s32)((f32)mydata.screensize.X * mydata.offset.X) + (s32)((1.0 - mydata.anchor.X) * 580.0), + (s32)((f32)mydata.screensize.Y * mydata.offset.Y) + (s32)((1.0 - mydata.anchor.Y) * 300.0) ); } recalculateAbsolutePosition(false); diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 2ab7db4f1..bbab9c164 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -447,6 +447,8 @@ private: bool explicit_size; v2f invsize; v2s32 size; + v2f32 offset; + v2f32 anchor; core::rect rect; v2s32 basepos; v2u32 screensize; @@ -502,6 +504,10 @@ private: bool parseVersionDirect(std::string data); bool parseSizeDirect(parserData* data, std::string element); void parseScrollBar(parserData* data, std::string element); + bool parsePositionDirect(parserData *data, const std::string &element); + void parsePosition(parserData *data, const std::string &element); + bool parseAnchorDirect(parserData *data, const std::string &element); + void parseAnchor(parserData *data, const std::string &element); void tryClose(); -- cgit v1.2.3 From c42c53fccf87a3819ca78de52f8f20c47c4fbb9f Mon Sep 17 00:00:00 2001 From: red-001 Date: Tue, 24 Jan 2017 16:26:15 +0000 Subject: [CSM] Add local formspecs. (#5094) --- builtin/client/init.lua | 10 ++++++ builtin/client/preview.lua | 2 +- builtin/client/register.lua | 1 + builtin/common/misc_helpers.lua | 3 +- doc/client_lua_api.txt | 15 +++++++-- src/client.h | 6 ++++ src/game.cpp | 67 ++++++----------------------------------- src/guiFormSpecMenu.h | 4 +-- src/script/cpp_api/s_client.cpp | 24 +++++++++++++++ src/script/cpp_api/s_client.h | 7 ++++- src/script/lua_api/l_client.cpp | 45 +++++++++++++++++++++++++-- src/script/lua_api/l_client.h | 9 ++++++ 12 files changed, 126 insertions(+), 67 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/builtin/client/init.lua b/builtin/client/init.lua index dd218aab6..b204ee5e6 100644 --- a/builtin/client/init.lua +++ b/builtin/client/init.lua @@ -6,8 +6,18 @@ local commonpath = scriptpath.."common"..DIR_DELIM dofile(clientpath .. "register.lua") dofile(commonpath .. "after.lua") dofile(commonpath .. "chatcommands.lua") +dofile(clientpath .. "chatcommands.lua") dofile(clientpath .. "preview.lua") core.register_on_death(function() core.display_chat_message("You died.") + local formspec = "size[11,5.5]bgcolor[#320000b4;true]" .. + "label[4.85,1.35;" .. fgettext("You died.") .. "]button_exit[4,3;3,0.5;btn_respawn;".. fgettext("Respawn") .."]" + core.show_formspec("bultin:death", formspec) +end) + +core.register_on_formspec_input(function(formname, fields) + if formname == "bultin:death" then + core.send_respawn() + end end) diff --git a/builtin/client/preview.lua b/builtin/client/preview.lua index 22e8bb97f..4c01d665f 100644 --- a/builtin/client/preview.lua +++ b/builtin/client/preview.lua @@ -32,7 +32,7 @@ end) -- This is an example function to ensure it's working properly, should be removed before merge core.register_chatcommand("dump", { - func = function(name, param) + func = function(param) return true, dump(_G) end, }) diff --git a/builtin/client/register.lua b/builtin/client/register.lua index 8b60c1222..1e6ac4342 100644 --- a/builtin/client/register.lua +++ b/builtin/client/register.lua @@ -62,5 +62,6 @@ core.registered_on_sending_chat_messages, core.register_on_sending_chat_messages core.registered_on_death, core.register_on_death = make_registration() core.registered_on_hp_modification, core.register_on_hp_modification = make_registration() core.registered_on_damage_taken, core.register_on_damage_taken = make_registration() +core.registered_on_formspec_input, core.register_on_formspec_input = make_registration() diff --git a/builtin/common/misc_helpers.lua b/builtin/common/misc_helpers.lua index c2dc7514d..70b23600a 100644 --- a/builtin/common/misc_helpers.lua +++ b/builtin/common/misc_helpers.lua @@ -606,7 +606,9 @@ if INIT == "mainmenu" then return nil end +end +if INIT == "client" or INIT == "mainmenu" then function fgettext_ne(text, ...) text = core.gettext(text) local arg = {n=select('#', ...), ...} @@ -636,4 +638,3 @@ if INIT == "mainmenu" then return core.formspec_escape(fgettext_ne(text, ...)) end end - diff --git a/doc/client_lua_api.txt b/doc/client_lua_api.txt index 8ce487bf8..3170f4c84 100644 --- a/doc/client_lua_api.txt +++ b/doc/client_lua_api.txt @@ -699,7 +699,10 @@ Call these functions only at load time! * Called when server modified player's HP * `minetest.register_on_damage_taken(func(hp))` * Called when player take damages - +* `minetest.register_on_formspec_input(func(formname, fields))` + * Called when a button is pressed in player's inventory form + * Newest functions are called first + * If function returns `true`, remaining functions are not called ### Sounds * `minetest.sound_play(spec, parameters)`: returns a handle * `spec` is a `SimpleSoundSpec` @@ -754,7 +757,15 @@ Call these functions only at load time! * Encodes a string in base64. * `minetest.decode_base64(string)`: returns string * Decodes a string encoded in base64. - +* `core.gettext(string) : returns string + * look up the translation of a string in the gettext message catalog +* `fgettext_ne(string, ...)` + * call core.gettext(string), replace "$1"..."$9" with the given + extra arguments and return the result +* `fgettext(string, ...)` : returns string + * same as fgettext_ne(), but calls core.formspec_escape before returning result +* `show_formspec(formname, formspec)` : returns true on success + * Shows a formspec to the player Class reference --------------- diff --git a/src/client.h b/src/client.h index ff8aea591..d170f9a07 100644 --- a/src/client.h +++ b/src/client.h @@ -142,6 +142,7 @@ enum ClientEventType CE_PLAYER_FORCE_MOVE, CE_DEATHSCREEN, CE_SHOW_FORMSPEC, + CE_SHOW_LOCAL_FORMSPEC, CE_SPAWN_PARTICLE, CE_ADD_PARTICLESPAWNER, CE_DELETE_PARTICLESPAWNER, @@ -570,6 +571,11 @@ public: ClientScripting *getScript() { return m_script; } + inline void pushToEventQueue(const ClientEvent &event) + { + m_client_event_queue.push(event); + } + private: // Virtual methods from con::PeerHandler diff --git a/src/game.cpp b/src/game.cpp index 2e2a8e0c1..c84e08b01 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -125,6 +125,7 @@ struct TextDestPlayerInventory : public TextDest { struct LocalFormspecHandler : public TextDest { LocalFormspecHandler(); + LocalFormspecHandler(std::string formname) : m_client(0) { @@ -178,39 +179,7 @@ struct LocalFormspecHandler : public TextDest { return; } } - - if (m_formname == "MT_DEATH_SCREEN") { - assert(m_client != 0); - - if ((fields.find("btn_respawn") != fields.end())) { - m_client->sendRespawn(); - return; - } - - if (fields.find("quit") != fields.end()) { - m_client->sendRespawn(); - return; - } - } - - // don't show error message for unhandled cursor keys - if ((fields.find("key_up") != fields.end()) || - (fields.find("key_down") != fields.end()) || - (fields.find("key_left") != fields.end()) || - (fields.find("key_right") != fields.end())) { - return; - } - - errorstream << "LocalFormspecHandler::gotText unhandled >" - << m_formname << "< event" << std::endl; - - int i = 0; - StringMap::const_iterator it; - for (it = fields.begin(); it != fields.end(); ++it) { - errorstream << "\t" << i << ": " << it->first - << "=" << it->second << std::endl; - i++; - } + m_client->getScript()->on_formspec_input(m_formname, fields); } Client *m_client; @@ -956,28 +925,6 @@ static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec, #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop #endif -static void show_deathscreen(GUIFormSpecMenu **cur_formspec, - Client *client, - IWritableTextureSource *tsrc, IrrlichtDevice *device, - JoystickController *joystick) -{ - std::string formspec = - std::string(FORMSPEC_VERSION_STRING) + - SIZE_TAG - "bgcolor[#320000b4;true]" - "label[4.85,1.35;" + gettext("You died.") + "]" - "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]" - ; - - /* Create menu */ - /* Note: FormspecFormSource and LocalFormspecHandler - * are deleted by guiFormSpecMenu */ - FormspecFormSource *fs_src = new FormspecFormSource(formspec); - LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client); - - create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst); -} - /******************************************************************************/ static void show_pause_menu(GUIFormSpecMenu **cur_formspec, Client *client, @@ -3255,9 +3202,6 @@ void Game::processClientEvents(CameraOrientation *cam, float *damage_flash) cam->camera_yaw = event.player_force_move.yaw; cam->camera_pitch = event.player_force_move.pitch; } else if (event.type == CE_DEATHSCREEN) { - show_deathscreen(¤t_formspec, client, texture_src, - device, &input->joystick); - client->getScript()->on_death(); /* Handle visualization */ @@ -3283,6 +3227,13 @@ void Game::processClientEvents(CameraOrientation *cam, float *damage_flash) delete(event.show_formspec.formspec); delete(event.show_formspec.formname); + } else if (event.type == CE_SHOW_LOCAL_FORMSPEC) { + FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec); + LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client); + create_formspec_menu(¤t_formspec, client, device, &input->joystick, + fs_src, txt_dst); + delete event.show_formspec.formspec; + delete event.show_formspec.formname; } else if ((event.type == CE_SPAWN_PARTICLE) || (event.type == CE_ADD_PARTICLESPAWNER) || (event.type == CE_DELETE_PARTICLESPAWNER)) { diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index bbab9c164..35365a94b 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -548,7 +548,7 @@ private: class FormspecFormSource: public IFormSource { public: - FormspecFormSource(std::string formspec) + FormspecFormSource(const std::string &formspec) { m_formspec = formspec; } @@ -556,7 +556,7 @@ public: ~FormspecFormSource() {} - void setForm(std::string formspec) { + void setForm(const std::string &formspec) { m_formspec = FORMSPEC_VERSION_STRING + formspec; } diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp index ce88d67e3..1827d483b 100644 --- a/src/script/cpp_api/s_client.cpp +++ b/src/script/cpp_api/s_client.cpp @@ -112,3 +112,27 @@ void ScriptApiClient::environment_step(float dtime) + script_get_backtrace(L)); } } + +void ScriptApiClient::on_formspec_input(const std::string &formname, + const StringMap &fields) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_chat_messages + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_formspec_input"); + // Call callbacks + // param 1 + lua_pushstring(L, formname.c_str()); + // param 2 + lua_newtable(L); + StringMap::const_iterator it; + for (it = fields.begin(); it != fields.end(); ++it) { + const std::string &name = it->first; + const std::string &value = it->second; + lua_pushstring(L, name.c_str()); + lua_pushlstring(L, value.c_str(), value.size()); + lua_settable(L, -3); + } + runCallbacks(2, RUN_CALLBACKS_MODE_OR_SC); +} diff --git a/src/script/cpp_api/s_client.h b/src/script/cpp_api/s_client.h index 3d373f97c..42c41f8a4 100644 --- a/src/script/cpp_api/s_client.h +++ b/src/script/cpp_api/s_client.h @@ -22,6 +22,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #define S_CLIENT_H_ #include "cpp_api/s_base.h" +#include "util/string.h" + +#ifdef _CRT_MSVCP_CURRENT +#include +#endif class ScriptApiClient: virtual public ScriptApiBase { @@ -36,7 +41,7 @@ public: void on_damage_taken(int32_t damage_amount); void on_hp_modification(int32_t newhp); void on_death(); - void environment_step(float dtime); + void on_formspec_input(const std::string &formname, const StringMap &fields); }; #endif diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 7eb340d78..9a04bd02f 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "l_internal.h" #include "util/string.h" #include "cpp_api/s_base.h" +#include "gettext.h" int ModApiClient::l_get_current_modname(lua_State *L) { @@ -44,18 +45,55 @@ int ModApiClient::l_get_last_run_mod(lua_State *L) // set_last_run_mod(modname) int ModApiClient::l_set_last_run_mod(lua_State *L) { + if (!lua_isstring(L, 1)) + return 0; + const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); - return 0; + lua_pushboolean(L, true); + return 1; } // display_chat_message(message) int ModApiClient::l_display_chat_message(lua_State *L) { - NO_MAP_LOCK_REQUIRED; + if (!lua_isstring(L, 1)) + return 0; std::string message = luaL_checkstring(L, 1); getClient(L)->pushToChatQueue(utf8_to_wide(message)); + lua_pushboolean(L, true); + return 1; +} + +// show_formspec(formspec) +int ModApiClient::l_show_formspec(lua_State *L) +{ + if ( !lua_isstring(L, 1) || !lua_isstring(L, 2) ) + return 0; + + ClientEvent event; + event.type = CE_SHOW_LOCAL_FORMSPEC; + event.show_formspec.formname = new std::string(luaL_checkstring(L, 1)); + event.show_formspec.formspec = new std::string(luaL_checkstring(L, 2)); + getClient(L)->pushToEventQueue(event); + lua_pushboolean(L, true); + return 1; +} + +// send_respawn() +int ModApiClient::l_send_respawn(lua_State *L) +{ + getClient(L)->sendRespawn(); + return 0; +} + +// gettext(text) +int ModApiClient::l_gettext(lua_State *L) +{ + std::string text = strgettext(std::string(luaL_checkstring(L, 1))); + lua_pushstring(L, text.c_str()); + return 1; } @@ -65,4 +103,7 @@ void ModApiClient::Initialize(lua_State *L, int top) API_FCT(display_chat_message); API_FCT(set_last_run_mod); API_FCT(get_last_run_mod); + API_FCT(show_formspec); + API_FCT(send_respawn); + API_FCT(gettext); } diff --git a/src/script/lua_api/l_client.h b/src/script/lua_api/l_client.h index 150880e3c..14ef5aecc 100644 --- a/src/script/lua_api/l_client.h +++ b/src/script/lua_api/l_client.h @@ -33,6 +33,15 @@ private: // display_chat_message(message) static int l_display_chat_message(lua_State *L); + // show_formspec(name, fornspec) + static int l_show_formspec(lua_State *L); + + // send_respawn() + static int l_send_respawn(lua_State *L); + + // gettext(text) + static int l_gettext(lua_State *L); + // get_last_run_mod(n) static int l_get_last_run_mod(lua_State *L); -- cgit v1.2.3 From 3c4ac70348db5375118d1e714a6d4681c3cfcd05 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Sun, 19 Mar 2017 13:18:52 +0100 Subject: Refactor Game class (part 2) (#5422) * showPauseMenu is now part of game * remove many flags parameters passed to game functions, use the member. * rename VolatileRunFlags to GameUIFlags (this will permit to share structure with client and CSM * updatePointedThing: remove pointer ref, we already have the pointer in rundata * move some attributes outside of VolatileRunFlags after renaming, to game class * rename statustext to m_statustext * make some const variables static * All those changes permit to reduce a little bit function class cost and will permit to interface CSM with some interesting Game flags * Expose GameUIFlags to client * Client now have GameUIFlags parameter and setters for other classes * Fix minimap show/hide in Lua because we now have access to the real flag --- src/client.cpp | 37 ++- src/client.h | 12 +- src/game.cpp | 478 ++++++++++++++++++--------------------- src/game.h | 12 + src/guiFormSpecMenu.h | 2 +- src/script/lua_api/l_minimap.cpp | 10 + 6 files changed, 285 insertions(+), 266 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/client.cpp b/src/client.cpp index e87c0ff94..0c4819bc5 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -46,6 +46,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serialization.h" #include "guiscalingfilter.h" #include "script/clientscripting.h" +#include "game.h" extern gui::IGUIEnvironment* guienv; @@ -198,7 +199,8 @@ Client::Client( IWritableNodeDefManager *nodedef, ISoundManager *sound, MtEventManager *event, - bool ipv6 + bool ipv6, + GameUIFlags *game_ui_flags ): m_packetcounter_timer(0.0), m_connection_reinit_timer(0.1), @@ -250,7 +252,8 @@ Client::Client( m_state(LC_Created), m_localdb(NULL), m_script(NULL), - m_mod_storage_save_timer(10.0f) + m_mod_storage_save_timer(10.0f), + m_game_ui_flags(game_ui_flags) { // Add local player m_env.setLocalPlayer(new LocalPlayer(this, playername)); @@ -1935,6 +1938,36 @@ bool Client::shouldShowMinimap() const return !m_minimap_disabled_by_server; } +void Client::showGameChat(const bool show) +{ + m_game_ui_flags->show_chat = show; +} + +void Client::showGameHud(const bool show) +{ + m_game_ui_flags->show_hud = show; +} + +void Client::showMinimap(const bool show) +{ + m_game_ui_flags->show_minimap = show; +} + +void Client::showProfiler(const bool show) +{ + m_game_ui_flags->show_profiler_graph = show; +} + +void Client::showGameFog(const bool show) +{ + m_game_ui_flags->force_fog_off = !show; +} + +void Client::showGameDebug(const bool show) +{ + m_game_ui_flags->show_debug = show; +} + // IGameDef interface // Under envlock IItemDefManager* Client::getItemDefManager() diff --git a/src/client.h b/src/client.h index fc1cbe310..b1310424d 100644 --- a/src/client.h +++ b/src/client.h @@ -307,6 +307,7 @@ private: }; class ClientScripting; +class GameUIFlags; class Client : public con::PeerHandler, public InventoryManager, public IGameDef { @@ -326,7 +327,8 @@ public: IWritableNodeDefManager *nodedef, ISoundManager *sound, MtEventManager *event, - bool ipv6 + bool ipv6, + GameUIFlags *game_ui_flags ); ~Client(); @@ -578,6 +580,13 @@ public: m_client_event_queue.push(event); } + void showGameChat(const bool show = true); + void showGameHud(const bool show = true); + void showMinimap(const bool show = true); + void showProfiler(const bool show = true); + void showGameFog(const bool show = true); + void showGameDebug(const bool show = true); + private: // Virtual methods from con::PeerHandler @@ -725,6 +734,7 @@ private: bool m_modding_enabled; UNORDERED_MAP m_mod_storages; float m_mod_storage_save_timer; + GameUIFlags *m_game_ui_flags; DISABLE_CLASS_COPY(Client); }; diff --git a/src/game.cpp b/src/game.cpp index 12c81bf2f..7d7da35e8 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -123,16 +123,15 @@ struct TextDestPlayerInventory : public TextDest { Client *m_client; }; -struct LocalFormspecHandler : public TextDest { - LocalFormspecHandler(); - - LocalFormspecHandler(std::string formname) : +struct LocalFormspecHandler : public TextDest +{ + LocalFormspecHandler(std::string formname): m_client(0) { m_formname = formname; } - LocalFormspecHandler(std::string formname, Client *client) : + LocalFormspecHandler(std::string formname, Client *client): m_client(client) { m_formname = formname; @@ -927,81 +926,6 @@ static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec, #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop #endif -/******************************************************************************/ -static void show_pause_menu(GUIFormSpecMenu **cur_formspec, - Client *client, - IWritableTextureSource *tsrc, IrrlichtDevice *device, - JoystickController *joystick, bool singleplayermode) -{ -#ifdef __ANDROID__ - std::string control_text = strgettext("Default Controls:\n" - "No menu visible:\n" - "- single tap: button activate\n" - "- double tap: place/use\n" - "- slide finger: look around\n" - "Menu/Inventory visible:\n" - "- double tap (outside):\n" - " -->close\n" - "- touch stack, touch slot:\n" - " --> move stack\n" - "- touch&drag, tap 2nd finger\n" - " --> place single item to slot\n" - ); -#else - std::string control_text = strgettext("Default Controls:\n" - "- WASD: move\n" - "- Space: jump/climb\n" - "- Shift: sneak/go down\n" - "- Q: drop item\n" - "- I: inventory\n" - "- Mouse: turn/look\n" - "- Mouse left: dig/punch\n" - "- Mouse right: place/use\n" - "- Mouse wheel: select item\n" - "- T: chat\n" - ); -#endif - - float ypos = singleplayermode ? 0.5 : 0.1; - std::ostringstream os; - - os << FORMSPEC_VERSION_STRING << SIZE_TAG - << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;" - << strgettext("Continue") << "]"; - - if (!singleplayermode) { - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;" - << strgettext("Change Password") << "]"; - } - -#ifndef __ANDROID__ - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;" - << strgettext("Sound Volume") << "]"; - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;" - << strgettext("Change Keys") << "]"; -#endif - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;" - << strgettext("Exit to Menu") << "]"; - os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;" - << strgettext("Exit to OS") << "]" - << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]" - << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n" - << g_build_info << "\n" - << "path_user = " << wrap_rows(porting::path_user, 20) - << "\n;]"; - - /* Create menu */ - /* Note: FormspecFormSource and LocalFormspecHandler * - * are deleted by guiFormSpecMenu */ - FormspecFormSource *fs_src = new FormspecFormSource(os.str()); - LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU"); - - create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst); - std::string con("btn_continue"); - (*cur_formspec)->setFocus(con); - (*cur_formspec)->doPause = true; -} - /******************************************************************************/ static void updateChat(Client &client, f32 dtime, bool show_debug, const v2u32 &screensize, bool show_chat, u32 show_profiler, @@ -1219,28 +1143,10 @@ struct Jitter { struct RunStats { u32 drawtime; - u32 beginscenetime; - u32 endscenetime; Jitter dtime_jitter, busy_time_jitter; }; -/* Flags that can, or may, change during main game loop - */ -struct VolatileRunFlags { - bool invert_mouse; - bool show_chat; - bool show_hud; - bool show_minimap; - bool force_fog_off; - bool show_debug; - bool show_profiler_graph; - bool disable_camera_update; - bool first_loop_after_window_activation; - bool camera_offset_changed; -}; - - /**************************************************************************** THE GAME ****************************************************************************/ @@ -1322,29 +1228,24 @@ protected: void toggleCinematic(); void toggleAutorun(); - void toggleChat(bool *flag); - void toggleHud(bool *flag); - void toggleMinimap(bool *flag, bool show_hud, - bool shift_pressed); - void toggleFog(bool *flag); - void toggleDebug(bool *show_debug, - bool *show_profiler_graph, bool *show_wireframe); - void toggleUpdateCamera(bool *flag); - void toggleProfiler(u32 *profiler_current_page, - u32 profiler_max_page); + void toggleChat(); + void toggleHud(); + void toggleMinimap(bool shift_pressed); + void toggleFog(); + void toggleDebug(); + void toggleUpdateCamera(); + void toggleProfiler(); void increaseViewRange(); void decreaseViewRange(); void toggleFullViewRange(); - void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags, - float dtime); - void updateCameraOrientation(CameraOrientation *cam, - const VolatileRunFlags &flags, float dtime); + void updateCameraDirection(CameraOrientation *cam, float dtime); + void updateCameraOrientation(CameraOrientation *cam, float dtime); void updatePlayerControl(const CameraOrientation &cam); void step(f32 *dtime); void processClientEvents(CameraOrientation *cam); - void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime); + void updateCamera(u32 busy_time, f32 dtime); void updateSound(f32 dtime); void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug); /*! @@ -1362,8 +1263,7 @@ protected: */ PointedThing updatePointedThing( const core::line3d &shootline, bool liquids_pointable, - bool look_for_object, const v3s16 &camera_offset, - ClientActiveObject *&selected_object); + bool look_for_object, const v3s16 &camera_offset); void handlePointingAtNothing(const ItemStack &playerItem); void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def, const ToolCapabilities &playeritem_toolcap, f32 dtime); @@ -1372,9 +1272,8 @@ protected: void handleDigging(const PointedThing &pointed, const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap, f32 dtime); void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, - const VolatileRunFlags &flags, const CameraOrientation &cam); - void updateGui(const RunStats &stats, f32 dtime, - const VolatileRunFlags &flags, const CameraOrientation &cam); + const CameraOrientation &cam); + void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam); void updateProfilerGraphs(ProfilerGraph *graph); // Misc @@ -1426,6 +1325,8 @@ protected: #endif private: + void showPauseMenu(); + InputHandler *input; Client *client; @@ -1462,7 +1363,7 @@ private: Minimap *mapper; GameRunData runData; - VolatileRunFlags flags; + GameUIFlags flags; /* 'cache' This class does take ownership/responsibily for cleaning up etc of any of @@ -1494,7 +1395,7 @@ private: gui::IGUIStaticText *guitext_profiler; // Profiler text std::wstring infotext; - std::wstring statustext; + std::wstring m_statustext; KeyCache keycache; @@ -1519,6 +1420,10 @@ private: f32 m_cache_cam_smoothing; f32 m_cache_fog_start; + bool m_invert_mouse; + bool m_first_loop_after_window_activation; + bool m_camera_offset_changed; + #ifdef __ANDROID__ bool m_cache_hold_aux1; bool m_android_chat_open; @@ -1547,7 +1452,10 @@ Game::Game() : sky(NULL), local_inventory(NULL), hud(NULL), - mapper(NULL) + mapper(NULL), + m_invert_mouse(false), + m_first_loop_after_window_activation(false), + m_camera_offset_changed(false) { g_settings->registerChangedCallback("doubletap_jump", &settingChangedCallback, this); @@ -1678,8 +1586,8 @@ bool Game::startup(bool *kill, flags.show_chat = true; flags.show_hud = true; flags.show_debug = g_settings->getBool("show_debug"); - flags.invert_mouse = g_settings->getBool("invert_mouse"); - flags.first_loop_after_window_activation = true; + m_invert_mouse = g_settings->getBool("invert_mouse"); + m_first_loop_after_window_activation = true; if (!init(map_dir, address, port, gamespec)) return false; @@ -1738,7 +1646,7 @@ void Game::run() updateProfilers(stats, draw_times, dtime); processUserInput(dtime); // Update camera before player movement to avoid camera lag of one frame - updateCameraDirection(&cam_view_target, &flags, dtime); + updateCameraDirection(&cam_view_target, dtime); cam_view.camera_yaw += (cam_view_target.camera_yaw - cam_view.camera_yaw) * m_cache_cam_smoothing; cam_view.camera_pitch += (cam_view_target.camera_pitch - @@ -1746,10 +1654,10 @@ void Game::run() updatePlayerControl(cam_view); step(&dtime); processClientEvents(&cam_view_target); - updateCamera(&flags, draw_times.busy_time, dtime); + updateCamera(draw_times.busy_time, dtime); updateSound(dtime); processPlayerInteraction(dtime, flags.show_hud, flags.show_debug); - updateFrame(&graph, &stats, dtime, flags, cam_view); + updateFrame(&graph, &stats, dtime, cam_view); updateProfilerGraphs(&graph); // Update if minimap has been disabled by the server @@ -2130,7 +2038,7 @@ bool Game::connectToServer(const std::string &playername, playername.c_str(), password, *draw_control, texture_src, shader_src, itemdef_manager, nodedef_manager, sound, eventmgr, - connect_address.isIPv6()); + connect_address.isIPv6(), &flags); if (!client) return false; @@ -2535,22 +2443,18 @@ void Game::processKeyInput() openInventory(); } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) { if (!gui_chat_console->isOpenInhibited()) { - show_pause_menu(¤t_formspec, client, - texture_src, device, &input->joystick, - simple_singleplayer_mode); + showPauseMenu(); } } else if (wasKeyDown(KeyType::CHAT)) { openConsole(0.2, L""); } else if (wasKeyDown(KeyType::CMD)) { openConsole(0.2, L"/"); } else if (wasKeyDown(KeyType::CONSOLE)) { - openConsole(core::clamp( - g_settings->getFloat("console_height"), 0.1f, 1.0f)); + openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f)); } else if (wasKeyDown(KeyType::FREEMOVE)) { toggleFreeMove(); } else if (wasKeyDown(KeyType::JUMP)) { toggleFreeMoveAlt(); - runData.reset_jump_timer = true; } else if (wasKeyDown(KeyType::FASTMOVE)) { toggleFast(); } else if (wasKeyDown(KeyType::NOCLIP)) { @@ -2560,21 +2464,19 @@ void Game::processKeyInput() } else if (wasKeyDown(KeyType::SCREENSHOT)) { client->makeScreenshot(device); } else if (wasKeyDown(KeyType::TOGGLE_HUD)) { - toggleHud(&flags.show_hud); + toggleHud(); } else if (wasKeyDown(KeyType::MINIMAP)) { - toggleMinimap(&flags.show_minimap, flags.show_hud, isKeyDown(KeyType::SNEAK)); + toggleMinimap(isKeyDown(KeyType::SNEAK)); } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) { - toggleChat(&flags.show_chat); + toggleChat(); } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) { - toggleFog(&flags.force_fog_off); + toggleFog(); } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) { - toggleUpdateCamera(&flags.disable_camera_update); + toggleUpdateCamera(); } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) { - toggleDebug(&flags.show_debug, &flags.show_profiler_graph, - &draw_control->show_wireframe); + toggleDebug(); } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) { - toggleProfiler(&runData.profiler_current_page, - runData.profiler_max_page); + toggleProfiler(); } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) { increaseViewRange(); } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) { @@ -2605,7 +2507,7 @@ void Game::processKeyInput() } if (quicktune->hasMessage()) { - statustext = utf8_to_wide(quicktune->getMessage()); + m_statustext = utf8_to_wide(quicktune->getMessage()); runData.statustext_time = 0.0f; } } @@ -2731,9 +2633,9 @@ void Game::toggleFreeMove() g_settings->set("free_move", bool_to_cstr(free_move)); runData.statustext_time = 0; - statustext = msg[free_move]; + m_statustext = msg[free_move]; if (free_move && !client->checkPrivilege("fly")) - statustext += L" (note: no 'fly' privilege)"; + m_statustext += L" (note: no 'fly' privilege)"; } @@ -2741,6 +2643,8 @@ void Game::toggleFreeMoveAlt() { if (m_cache_doubletap_jump && runData.jump_timer < 0.2f) toggleFreeMove(); + + runData.reset_jump_timer = true; } @@ -2751,12 +2655,12 @@ void Game::toggleFast() g_settings->set("fast_move", bool_to_cstr(fast_move)); runData.statustext_time = 0; - statustext = msg[fast_move]; + m_statustext = msg[fast_move]; bool has_fast_privs = client->checkPrivilege("fast"); if (fast_move && !has_fast_privs) - statustext += L" (note: no 'fast' privilege)"; + m_statustext += L" (note: no 'fast' privilege)"; #ifdef __ANDROID__ m_cache_hold_aux1 = fast_move && has_fast_privs; @@ -2771,10 +2675,10 @@ void Game::toggleNoClip() g_settings->set("noclip", bool_to_cstr(noclip)); runData.statustext_time = 0; - statustext = msg[noclip]; + m_statustext = msg[noclip]; if (noclip && !client->checkPrivilege("noclip")) - statustext += L" (note: no 'noclip' privilege)"; + m_statustext += L" (note: no 'noclip' privilege)"; } void Game::toggleCinematic() @@ -2784,7 +2688,7 @@ void Game::toggleCinematic() g_settings->set("cinematic", bool_to_cstr(cinematic)); runData.statustext_time = 0; - statustext = msg[cinematic]; + m_statustext = msg[cinematic]; } // Add WoW-style autorun by toggling continuous forward. @@ -2795,32 +2699,31 @@ void Game::toggleAutorun() g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled)); runData.statustext_time = 0; - statustext = msg[autorun_enabled ? 1 : 0]; + m_statustext = msg[autorun_enabled ? 1 : 0]; } -void Game::toggleChat(bool *flag) +void Game::toggleChat() { static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" }; - *flag = !*flag; + flags.show_chat = !flags.show_chat; runData.statustext_time = 0; - statustext = msg[*flag]; + m_statustext = msg[flags.show_chat]; } -void Game::toggleHud(bool *flag) +void Game::toggleHud() { static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" }; - *flag = !*flag; + flags.show_hud = !flags.show_hud; runData.statustext_time = 0; - statustext = msg[*flag]; + m_statustext = msg[flags.show_hud]; } -void Game::toggleMinimap(bool *flag, - bool show_hud, bool shift_pressed) +void Game::toggleMinimap(bool shift_pressed) { - if (!show_hud || !g_settings->getBool("enable_minimap")) + if (!flags.show_hud || !g_settings->getBool("enable_minimap")) return; if (shift_pressed) { @@ -2836,30 +2739,30 @@ void Game::toggleMinimap(bool *flag, mode = (MinimapMode)((int)mode + 1); } - *flag = true; + flags.show_minimap = true; switch (mode) { case MINIMAP_MODE_SURFACEx1: - statustext = L"Minimap in surface mode, Zoom x1"; + m_statustext = L"Minimap in surface mode, Zoom x1"; break; case MINIMAP_MODE_SURFACEx2: - statustext = L"Minimap in surface mode, Zoom x2"; + m_statustext = L"Minimap in surface mode, Zoom x2"; break; case MINIMAP_MODE_SURFACEx4: - statustext = L"Minimap in surface mode, Zoom x4"; + m_statustext = L"Minimap in surface mode, Zoom x4"; break; case MINIMAP_MODE_RADARx1: - statustext = L"Minimap in radar mode, Zoom x1"; + m_statustext = L"Minimap in radar mode, Zoom x1"; break; case MINIMAP_MODE_RADARx2: - statustext = L"Minimap in radar mode, Zoom x2"; + m_statustext = L"Minimap in radar mode, Zoom x2"; break; case MINIMAP_MODE_RADARx4: - statustext = L"Minimap in radar mode, Zoom x4"; + m_statustext = L"Minimap in radar mode, Zoom x4"; break; default: mode = MINIMAP_MODE_OFF; - *flag = false; - statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ? + flags.show_minimap = false; + m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ? L"Minimap hidden" : L"Minimap disabled by server"; } @@ -2867,76 +2770,77 @@ void Game::toggleMinimap(bool *flag, mapper->setMinimapMode(mode); } -void Game::toggleFog(bool *flag) +void Game::toggleFog() { static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" }; - *flag = !*flag; + flags.force_fog_off = !flags.force_fog_off; runData.statustext_time = 0; - statustext = msg[*flag]; + m_statustext = msg[flags.force_fog_off]; } -void Game::toggleDebug(bool *show_debug, bool *show_profiler_graph, bool *show_wireframe) +void Game::toggleDebug() { // Initial / 4x toggle: Chat only // 1x toggle: Debug text with chat // 2x toggle: Debug text with profiler graph // 3x toggle: Debug text and wireframe - if (!*show_debug) { - *show_debug = true; - *show_profiler_graph = false; - *show_wireframe = false; - statustext = L"Debug info shown"; - } else if (!*show_profiler_graph && !*show_wireframe) { - *show_profiler_graph = true; - statustext = L"Profiler graph shown"; - } else if (!*show_wireframe && client->checkPrivilege("debug")) { - *show_profiler_graph = false; - *show_wireframe = true; - statustext = L"Wireframe shown"; + if (!flags.show_debug) { + flags.show_debug = true; + flags.show_profiler_graph = false; + draw_control->show_wireframe = false; + m_statustext = L"Debug info shown"; + } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) { + flags.show_profiler_graph = true; + m_statustext = L"Profiler graph shown"; + } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) { + flags.show_profiler_graph = false; + draw_control->show_wireframe = true; + m_statustext = L"Wireframe shown"; } else { - *show_debug = false; - *show_profiler_graph = false; - *show_wireframe = false; + flags.show_debug = false; + flags.show_profiler_graph = false; + draw_control->show_wireframe = false; if (client->checkPrivilege("debug")) { - statustext = L"Debug info, profiler graph, and wireframe hidden"; + m_statustext = L"Debug info, profiler graph, and wireframe hidden"; } else { - statustext = L"Debug info and profiler graph hidden"; + m_statustext = L"Debug info and profiler graph hidden"; } } runData.statustext_time = 0; } -void Game::toggleUpdateCamera(bool *flag) +void Game::toggleUpdateCamera() { static const wchar_t *msg[] = { L"Camera update enabled", L"Camera update disabled" }; - *flag = !*flag; + flags.disable_camera_update = !flags.disable_camera_update; runData.statustext_time = 0; - statustext = msg[*flag]; + m_statustext = msg[flags.disable_camera_update]; } -void Game::toggleProfiler(u32 *profiler_current_page, u32 profiler_max_page) +void Game::toggleProfiler() { - *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1); + runData.profiler_current_page = + (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1); // FIXME: This updates the profiler with incomplete values - update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page, - profiler_max_page, driver->getScreenSize().Height); + update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page, + runData.profiler_max_page, driver->getScreenSize().Height); - if (*profiler_current_page != 0) { + if (runData.profiler_current_page != 0) { std::wstringstream sstr; - sstr << "Profiler shown (page " << *profiler_current_page - << " of " << profiler_max_page << ")"; - statustext = sstr.str(); + sstr << "Profiler shown (page " << runData.profiler_current_page + << " of " << runData.profiler_max_page << ")"; + m_statustext = sstr.str(); } else { - statustext = L"Profiler hidden"; + m_statustext = L"Profiler hidden"; } runData.statustext_time = 0; } @@ -2949,10 +2853,10 @@ void Game::increaseViewRange() if (range_new > 4000) { range_new = 4000; - statustext = utf8_to_wide("Viewing range is at maximum: " + m_statustext = utf8_to_wide("Viewing range is at maximum: " + itos(range_new)); } else { - statustext = utf8_to_wide("Viewing range changed to " + m_statustext = utf8_to_wide("Viewing range changed to " + itos(range_new)); } g_settings->set("viewing_range", itos(range_new)); @@ -2967,10 +2871,10 @@ void Game::decreaseViewRange() if (range_new < 20) { range_new = 20; - statustext = utf8_to_wide("Viewing range is at minimum: " + m_statustext = utf8_to_wide("Viewing range is at minimum: " + itos(range_new)); } else { - statustext = utf8_to_wide("Viewing range changed to " + m_statustext = utf8_to_wide("Viewing range changed to " + itos(range_new)); } g_settings->set("viewing_range", itos(range_new)); @@ -2987,13 +2891,12 @@ void Game::toggleFullViewRange() draw_control->range_all = !draw_control->range_all; infostream << msg[draw_control->range_all] << std::endl; - statustext = msg[draw_control->range_all]; + m_statustext = msg[draw_control->range_all]; runData.statustext_time = 0; } -void Game::updateCameraDirection(CameraOrientation *cam, - VolatileRunFlags *flags, float dtime) +void Game::updateCameraDirection(CameraOrientation *cam, float dtime) { if ((device->isWindowActive() && noMenuActive()) || random_input) { @@ -3005,10 +2908,10 @@ void Game::updateCameraDirection(CameraOrientation *cam, } #endif - if (flags->first_loop_after_window_activation) - flags->first_loop_after_window_activation = false; + if (m_first_loop_after_window_activation) + m_first_loop_after_window_activation = false; else - updateCameraOrientation(cam, *flags, dtime); + updateCameraOrientation(cam, dtime); input->setMousePos((driver->getScreenSize().Width / 2), (driver->getScreenSize().Height / 2)); @@ -3016,18 +2919,17 @@ void Game::updateCameraDirection(CameraOrientation *cam, #ifndef ANDROID // Mac OSX gets upset if this is set every frame - if (device->getCursorControl()->isVisible() == false) + if (!device->getCursorControl()->isVisible()) device->getCursorControl()->setVisible(true); #endif - if (!flags->first_loop_after_window_activation) - flags->first_loop_after_window_activation = true; + if (!m_first_loop_after_window_activation) + m_first_loop_after_window_activation = true; } } -void Game::updateCameraOrientation(CameraOrientation *cam, - const VolatileRunFlags &flags, float dtime) +void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) { #ifdef HAVE_TOUCHSCREENGUI if (g_touchscreengui) { @@ -3039,8 +2941,7 @@ void Game::updateCameraOrientation(CameraOrientation *cam, s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2); s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2); - if (flags.invert_mouse - || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) { + if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) { dy = -dy; } @@ -3053,10 +2954,8 @@ void Game::updateCameraOrientation(CameraOrientation *cam, if (m_cache_enable_joysticks) { f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime; - cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * - c; - cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * - c; + cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c; + cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c; } cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5); @@ -3355,7 +3254,7 @@ void Game::processClientEvents(CameraOrientation *cam) } -void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime) +void Game::updateCamera(u32 busy_time, f32 dtime) { LocalPlayer *player = client->getEnv().getLocalPlayer(); @@ -3411,13 +3310,13 @@ void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime) f32 camera_fov = camera->getFovMax(); v3s16 camera_offset = camera->getOffset(); - flags->camera_offset_changed = (camera_offset != old_camera_offset); + m_camera_offset_changed = (camera_offset != old_camera_offset); - if (!flags->disable_camera_update) { + if (!flags.disable_camera_update) { client->getEnv().getClientMap().updateCamera(camera_position, camera_direction, camera_fov, camera_offset); - if (flags->camera_offset_changed) { + if (m_camera_offset_changed) { client->updateCameraOffset(camera_offset); client->getEnv().updateCameraOffset(camera_offset); @@ -3511,9 +3410,7 @@ void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug) PointedThing pointed = updatePointedThing(shootline, playeritem_def.liquids_pointable, !runData.ldown_for_dig, - camera_offset, - // output - runData.selected_object); + camera_offset); if (pointed != runData.pointed_old) { infostream << "Pointing at " << pointed.dump() << std::endl; @@ -3604,8 +3501,7 @@ PointedThing Game::updatePointedThing( const core::line3d &shootline, bool liquids_pointable, bool look_for_object, - const v3s16 &camera_offset, - ClientActiveObject *&selected_object) + const v3s16 &camera_offset) { std::vector *selectionboxes = hud->getSelectionBoxes(); selectionboxes->clear(); @@ -3616,21 +3512,21 @@ PointedThing Game::updatePointedThing( ClientMap &map = client->getEnv().getClientMap(); INodeDefManager *nodedef=client->getNodeDefManager(); - selected_object = NULL; + runData.selected_object = NULL; PointedThing result=client->getEnv().getPointedThing( shootline, liquids_pointable, look_for_object); if (result.type == POINTEDTHING_OBJECT) { - selected_object = client->getEnv().getActiveObject(result.object_id); - if (show_entity_selectionbox && selected_object->doShowSelectionBox()) { - aabb3f *selection_box = selected_object->getSelectionBox(); + runData.selected_object = client->getEnv().getActiveObject(result.object_id); + if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox()) { + aabb3f *selection_box = runData.selected_object->getSelectionBox(); // Box should exist because object was // returned in the first place assert(selection_box); - v3f pos = selected_object->getPosition(); + v3f pos = runData.selected_object->getPosition(); selectionboxes->push_back(aabb3f( selection_box->MinEdge, selection_box->MaxEdge)); selectionboxes->push_back( @@ -3981,7 +3877,7 @@ void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos, void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, - const VolatileRunFlags &flags, const CameraOrientation &cam) + const CameraOrientation &cam) { LocalPlayer *player = client->getEnv().getLocalPlayer(); @@ -4015,13 +3911,11 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, / 255.0; } - float time_of_day = runData.time_of_day; float time_of_day_smooth = runData.time_of_day_smooth; + float time_of_day = client->getEnv().getTimeOfDayF(); - time_of_day = client->getEnv().getTimeOfDayF(); - - const float maxsm = 0.05; - const float todsm = 0.05; + static const float maxsm = 0.05; + static const float todsm = 0.05; if (fabs(time_of_day - time_of_day_smooth) > maxsm && fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm && @@ -4138,13 +4032,13 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, v3f camera_direction = camera->getDirection(); if (runData.update_draw_list_timer >= 0.2 || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 - || flags.camera_offset_changed) { + || m_camera_offset_changed) { runData.update_draw_list_timer = 0; client->getEnv().getClientMap().updateDrawList(driver); runData.update_draw_list_last_cam_dir = camera_direction; } - updateGui(*stats, dtime, flags, cam); + updateGui(*stats, dtime, cam); /* make sure menu is on top @@ -4167,11 +4061,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, video::SColor skycolor = sky->getSkyColor(); TimeTaker tt_draw("mainloop: draw"); - { - TimeTaker timer("beginScene"); - driver->beginScene(true, true, skycolor); - stats->beginscenetime = timer.stop(true); - } + driver->beginScene(true, true, skycolor); draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper, guienv, screensize, skycolor, flags.show_hud, @@ -4216,11 +4106,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, /* End scene */ - { - TimeTaker timer("endScene"); - driver->endScene(); - stats->endscenetime = timer.stop(true); - } + driver->endScene(); stats->drawtime = tt_draw.stop(true); g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f); @@ -4238,8 +4124,7 @@ inline static const char *yawToDirectionString(int yaw) } -void Game::updateGui(const RunStats &stats, f32 dtime, const VolatileRunFlags &flags, - const CameraOrientation &cam) +void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam) { v2u32 screensize = driver->getScreenSize(); LocalPlayer *player = client->getEnv().getLocalPlayer(); @@ -4319,19 +4204,19 @@ void Game::updateGui(const RunStats &stats, f32 dtime, const VolatileRunFlags &f float statustext_time_max = 1.5; - if (!statustext.empty()) { + if (!m_statustext.empty()) { runData.statustext_time += dtime; if (runData.statustext_time >= statustext_time_max) { - statustext = L""; + m_statustext = L""; runData.statustext_time = 0; } } - setStaticText(guitext_status, statustext.c_str()); - guitext_status->setVisible(!statustext.empty()); + setStaticText(guitext_status, m_statustext.c_str()); + guitext_status->setVisible(!m_statustext.empty()); - if (!statustext.empty()) { + if (!m_statustext.empty()) { s32 status_width = guitext_status->getTextWidth(); s32 status_height = guitext_status->getTextHeight(); s32 status_y = screensize.Y - 150; @@ -4485,6 +4370,75 @@ void Game::extendedResourceCleanup() << " (note: irrlicht doesn't support removing renderers)" << std::endl; } +void Game::showPauseMenu() +{ +#ifdef __ANDROID__ + static const std::string control_text = strgettext("Default Controls:\n" + "No menu visible:\n" + "- single tap: button activate\n" + "- double tap: place/use\n" + "- slide finger: look around\n" + "Menu/Inventory visible:\n" + "- double tap (outside):\n" + " -->close\n" + "- touch stack, touch slot:\n" + " --> move stack\n" + "- touch&drag, tap 2nd finger\n" + " --> place single item to slot\n" + ); +#else + static const std::string control_text = strgettext("Default Controls:\n" + "- WASD: move\n" + "- Space: jump/climb\n" + "- Shift: sneak/go down\n" + "- Q: drop item\n" + "- I: inventory\n" + "- Mouse: turn/look\n" + "- Mouse left: dig/punch\n" + "- Mouse right: place/use\n" + "- Mouse wheel: select item\n" + "- T: chat\n" + ); +#endif + + float ypos = simple_singleplayer_mode ? 0.5 : 0.1; + std::ostringstream os; + + os << FORMSPEC_VERSION_STRING << SIZE_TAG + << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;" + << strgettext("Continue") << "]"; + + if (!simple_singleplayer_mode) { + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;" + << strgettext("Change Password") << "]"; + } + +#ifndef __ANDROID__ + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;" + << strgettext("Sound Volume") << "]"; + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;" + << strgettext("Change Keys") << "]"; +#endif + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;" + << strgettext("Exit to Menu") << "]"; + os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;" + << strgettext("Exit to OS") << "]" + << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]" + << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n" + << g_build_info << "\n" + << "path_user = " << wrap_rows(porting::path_user, 20) + << "\n;]"; + + /* Create menu */ + /* Note: FormspecFormSource and LocalFormspecHandler * + * are deleted by guiFormSpecMenu */ + FormspecFormSource *fs_src = new FormspecFormSource(os.str()); + LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU"); + + create_formspec_menu(¤t_formspec, client, device, &input->joystick, fs_src, txt_dst); + current_formspec->setFocus("btn_continue"); + current_formspec->doPause = true; +} /****************************************************************************/ /**************************************************************************** diff --git a/src/game.h b/src/game.h index df32e3397..19992ce3d 100644 --- a/src/game.h +++ b/src/game.h @@ -143,6 +143,18 @@ public: class ChatBackend; /* to avoid having to include chat.h */ struct SubgameSpec; +// Flags that can, or may, change during main game loop +struct GameUIFlags +{ + bool show_chat; + bool show_hud; + bool show_minimap; + bool force_fog_off; + bool show_debug; + bool show_profiler_graph; + bool disable_camera_update; +}; + void the_game(bool *kill, bool random_input, InputHandler *input, diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 35365a94b..f4383e987 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -335,7 +335,7 @@ public: void removeChildren(); void setInitialFocus(); - void setFocus(std::string &elementname) + void setFocus(const std::string &elementname) { m_focused_element = elementname; } diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index cb0245576..8e03936a7 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -118,21 +118,31 @@ int LuaMinimap::l_toggle_shape(lua_State *L) int LuaMinimap::l_show(lua_State *L) { + Client *client = getClient(L); + assert(client); + LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); if (m->getMinimapMode() == MINIMAP_MODE_OFF) m->setMinimapMode(MINIMAP_MODE_SURFACEx1); + + client->showMinimap(true); return 1; } int LuaMinimap::l_hide(lua_State *L) { + Client *client = getClient(L); + assert(client); + LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); if (m->getMinimapMode() != MINIMAP_MODE_OFF) m->setMinimapMode(MINIMAP_MODE_OFF); + + client->showMinimap(false); return 1; } -- cgit v1.2.3 From f98bbe193e0093aca8d8957cec82fdbd28639915 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Thu, 20 Apr 2017 00:12:52 +0200 Subject: Fix various copy instead of const ref reported by cppcheck (part 3) (#5616) * Also remove 2 non declared but defined functions * Make some functions around const ref changes const --- src/client/joystick_controller.cpp | 3 +- src/client/joystick_controller.h | 2 +- src/clientiface.h | 20 +++++------ src/genericobject.cpp | 23 +++++++------ src/genericobject.h | 9 +++-- src/guiEngine.cpp | 4 +-- src/guiEngine.h | 6 ++-- src/guiFormSpecMenu.cpp | 69 +++++++++++++++++++------------------- src/guiFormSpecMenu.h | 60 +++++++++++++++++---------------- src/guiTable.h | 9 +++-- src/httpfetch.cpp | 17 +++++----- src/httpfetch.h | 36 ++++++++++---------- src/map.cpp | 5 ++- src/map.h | 10 ++---- src/network/connection.h | 10 +++--- src/nodedef.h | 14 ++++---- src/pathfinder.cpp | 4 +-- src/porting.cpp | 2 +- src/script/cpp_api/s_async.cpp | 8 ++--- src/script/cpp_api/s_async.h | 15 +++++++-- src/script/scripting_mainmenu.cpp | 8 +++-- src/script/scripting_mainmenu.h | 4 +-- src/sound.h | 12 ++++--- src/util/string.h | 2 +- src/util/thread.h | 14 +++----- 25 files changed, 183 insertions(+), 183 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index 3e1442793..cb9d64b9f 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -185,7 +185,8 @@ void JoystickController::onJoystickConnect(const std::vector m_joystick_id = id; } -void JoystickController::setLayoutFromControllerName(std::string name) { +void JoystickController::setLayoutFromControllerName(const std::string &name) +{ if (lowercase(name).find("xbox") != std::string::npos) { m_layout = create_xbox_layout(); } else { diff --git a/src/client/joystick_controller.h b/src/client/joystick_controller.h index 867a0c3f2..2c0e7b90a 100644 --- a/src/client/joystick_controller.h +++ b/src/client/joystick_controller.h @@ -149,7 +149,7 @@ public: f32 doubling_dtime; private: - void setLayoutFromControllerName(std::string name); + void setLayoutFromControllerName(const std::string &name); JoystickLayout m_layout; diff --git a/src/clientiface.h b/src/clientiface.h index 403cd0420..11ebdaab6 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -324,14 +324,11 @@ public: */ std::set m_known_objects; - ClientState getState() - { return m_state; } + ClientState getState() const { return m_state; } - std::string getName() - { return m_name; } + std::string getName() const { return m_name; } - void setName(std::string name) - { m_name = name; } + void setName(const std::string &name) { m_name = name; } /* update internal client state */ void notifyEvent(ClientStateEvent event); @@ -350,7 +347,8 @@ public: u32 uptime(); /* set version information */ - void setVersionInfo(u8 major, u8 minor, u8 patch, std::string full) { + void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full) + { m_version_major = major; m_version_minor = minor; m_version_patch = patch; @@ -358,10 +356,10 @@ public: } /* read version information */ - u8 getMajor() { return m_version_major; } - u8 getMinor() { return m_version_minor; } - u8 getPatch() { return m_version_patch; } - std::string getVersion() { return m_full_version; } + u8 getMajor() const { return m_version_major; } + u8 getMinor() const { return m_version_minor; } + u8 getPatch() const { return m_version_patch; } + std::string getVersion() const { return m_full_version; } private: // Version is stored in here after INIT before INIT2 u8 m_pending_serialization_version; diff --git a/src/genericobject.cpp b/src/genericobject.cpp index 07d2445b4..58f4b997e 100644 --- a/src/genericobject.cpp +++ b/src/genericobject.cpp @@ -68,7 +68,7 @@ std::string gob_cmd_update_position( std::string gob_cmd_set_texture_mod(const std::string &mod) { std::ostringstream os(std::ios::binary); - // command + // command writeU8(os, GENERIC_CMD_SET_TEXTURE_MOD); // parameters os<queueAsync(serialized_func, serialized_params); } diff --git a/src/guiEngine.h b/src/guiEngine.h index a81813d18..98e88574c 100644 --- a/src/guiEngine.h +++ b/src/guiEngine.h @@ -178,7 +178,8 @@ public: } /** pass async callback to scriptengine **/ - unsigned int queueAsync(std::string serialized_fct,std::string serialized_params); + unsigned int queueAsync(const std::string &serialized_fct, + const std::string &serialized_params); private: @@ -188,9 +189,6 @@ private: /** run main menu loop */ void run(); - /** handler to limit frame rate within main menu */ - void limitFrameRate(); - /** update size of topleftext element */ void updateTopLeftTextSize(); diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 3fe3c5cc2..ab93aeca1 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -252,7 +252,7 @@ std::vector* GUIFormSpecMenu::getDropDownValues(const std::string & return NULL; } -void GUIFormSpecMenu::parseSize(parserData* data,std::string element) +void GUIFormSpecMenu::parseSize(parserData* data, const std::string &element) { std::vector parts = split(element,','); @@ -278,7 +278,7 @@ void GUIFormSpecMenu::parseSize(parserData* data,std::string element) errorstream<< "Invalid size element (" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseContainer(parserData* data, std::string element) +void GUIFormSpecMenu::parseContainer(parserData* data, const std::string &element) { std::vector parts = split(element, ','); @@ -304,7 +304,7 @@ void GUIFormSpecMenu::parseContainerEnd(parserData* data) } } -void GUIFormSpecMenu::parseList(parserData* data,std::string element) +void GUIFormSpecMenu::parseList(parserData* data, const std::string &element) { if (m_client == 0) { warningstream<<"invalid use of 'list' with m_client==0"< parts = split(element,';'); @@ -450,7 +450,7 @@ void GUIFormSpecMenu::parseCheckbox(parserData* data,std::string element) errorstream<< "Invalid checkbox element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseScrollBar(parserData* data, std::string element) +void GUIFormSpecMenu::parseScrollBar(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -509,7 +509,7 @@ void GUIFormSpecMenu::parseScrollBar(parserData* data, std::string element) errorstream<< "Invalid scrollbar element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseImage(parserData* data,std::string element) +void GUIFormSpecMenu::parseImage(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -553,7 +553,7 @@ void GUIFormSpecMenu::parseImage(parserData* data,std::string element) errorstream<< "Invalid image element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element) +void GUIFormSpecMenu::parseItemImage(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -583,8 +583,8 @@ void GUIFormSpecMenu::parseItemImage(parserData* data,std::string element) errorstream<< "Invalid ItemImage element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseButton(parserData* data,std::string element, - std::string type) +void GUIFormSpecMenu::parseButton(parserData* data, const std::string &element, + const std::string &type) { std::vector parts = split(element,';'); @@ -638,7 +638,7 @@ void GUIFormSpecMenu::parseButton(parserData* data,std::string element, errorstream<< "Invalid button element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBackground(parserData* data,std::string element) +void GUIFormSpecMenu::parseBackground(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -676,7 +676,7 @@ void GUIFormSpecMenu::parseBackground(parserData* data,std::string element) errorstream<< "Invalid background element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTableOptions(parserData* data,std::string element) +void GUIFormSpecMenu::parseTableOptions(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -688,7 +688,7 @@ void GUIFormSpecMenu::parseTableOptions(parserData* data,std::string element) } } -void GUIFormSpecMenu::parseTableColumns(parserData* data,std::string element) +void GUIFormSpecMenu::parseTableColumns(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -708,7 +708,7 @@ void GUIFormSpecMenu::parseTableColumns(parserData* data,std::string element) } } -void GUIFormSpecMenu::parseTable(parserData* data,std::string element) +void GUIFormSpecMenu::parseTable(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -776,7 +776,7 @@ void GUIFormSpecMenu::parseTable(parserData* data,std::string element) errorstream<< "Invalid table element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTextList(parserData* data,std::string element) +void GUIFormSpecMenu::parseTextList(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -849,7 +849,7 @@ void GUIFormSpecMenu::parseTextList(parserData* data,std::string element) } -void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element) +void GUIFormSpecMenu::parseDropDown(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -913,8 +913,7 @@ void GUIFormSpecMenu::parseDropDown(parserData* data,std::string element) << element << "'" << std::endl; } -void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, - const std::string &element) +void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, const std::string &element) { std::vector parts = split(element,';'); if (parts.size() == 2 || @@ -923,7 +922,7 @@ void GUIFormSpecMenu::parseFieldCloseOnEnter(parserData *data, } } -void GUIFormSpecMenu::parsePwdField(parserData* data,std::string element) +void GUIFormSpecMenu::parsePwdField(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1084,8 +1083,8 @@ void GUIFormSpecMenu::parseSimpleField(parserData* data, m_fields.push_back(spec); } -void GUIFormSpecMenu::parseTextArea(parserData* data, - std::vector& parts,std::string type) +void GUIFormSpecMenu::parseTextArea(parserData* data, std::vector& parts, + const std::string &type) { std::vector v_pos = split(parts[0],','); @@ -1196,8 +1195,8 @@ void GUIFormSpecMenu::parseTextArea(parserData* data, m_fields.push_back(spec); } -void GUIFormSpecMenu::parseField(parserData* data,std::string element, - std::string type) +void GUIFormSpecMenu::parseField(parserData* data, const std::string &element, + const std::string &type) { std::vector parts = split(element,';'); @@ -1215,7 +1214,7 @@ void GUIFormSpecMenu::parseField(parserData* data,std::string element, errorstream<< "Invalid field element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) +void GUIFormSpecMenu::parseLabel(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1271,7 +1270,7 @@ void GUIFormSpecMenu::parseLabel(parserData* data,std::string element) errorstream<< "Invalid label element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) +void GUIFormSpecMenu::parseVertLabel(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1321,8 +1320,8 @@ void GUIFormSpecMenu::parseVertLabel(parserData* data,std::string element) errorstream<< "Invalid vertlabel element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element, - std::string type) +void GUIFormSpecMenu::parseImageButton(parserData* data, const std::string &element, + const std::string &type) { std::vector parts = split(element,';'); @@ -1410,7 +1409,7 @@ void GUIFormSpecMenu::parseImageButton(parserData* data,std::string element, errorstream<< "Invalid imagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element) +void GUIFormSpecMenu::parseTabHeader(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1482,7 +1481,7 @@ void GUIFormSpecMenu::parseTabHeader(parserData* data,std::string element) << element << "'" << std::endl; } -void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element) +void GUIFormSpecMenu::parseItemImageButton(parserData* data, const std::string &element) { if (m_client == 0) { @@ -1556,7 +1555,7 @@ void GUIFormSpecMenu::parseItemImageButton(parserData* data,std::string element) errorstream<< "Invalid ItemImagebutton element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBox(parserData* data,std::string element) +void GUIFormSpecMenu::parseBox(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1592,7 +1591,7 @@ void GUIFormSpecMenu::parseBox(parserData* data,std::string element) errorstream<< "Invalid Box element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element) +void GUIFormSpecMenu::parseBackgroundColor(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1610,7 +1609,7 @@ void GUIFormSpecMenu::parseBackgroundColor(parserData* data,std::string element) errorstream<< "Invalid bgcolor element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseListColors(parserData* data,std::string element) +void GUIFormSpecMenu::parseListColors(parserData* data, const std::string &element) { std::vector parts = split(element,';'); @@ -1638,7 +1637,7 @@ void GUIFormSpecMenu::parseListColors(parserData* data,std::string element) errorstream<< "Invalid listcolors element(" << parts.size() << "): '" << element << "'" << std::endl; } -void GUIFormSpecMenu::parseTooltip(parserData* data, std::string element) +void GUIFormSpecMenu::parseTooltip(parserData* data, const std::string &element) { std::vector parts = split(element,';'); if (parts.size() == 2) { @@ -1658,7 +1657,7 @@ void GUIFormSpecMenu::parseTooltip(parserData* data, std::string element) errorstream<< "Invalid tooltip element(" << parts.size() << "): '" << element << "'" << std::endl; } -bool GUIFormSpecMenu::parseVersionDirect(std::string data) +bool GUIFormSpecMenu::parseVersionDirect(const std::string &data) { //some prechecks if (data == "") @@ -1682,7 +1681,7 @@ bool GUIFormSpecMenu::parseVersionDirect(std::string data) return false; } -bool GUIFormSpecMenu::parseSizeDirect(parserData* data, std::string element) +bool GUIFormSpecMenu::parseSizeDirect(parserData* data, const std::string &element) { if (element == "") return false; diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index f4383e987..4bc2448d8 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -471,39 +471,41 @@ private: void parseElement(parserData* data, std::string element); - void parseSize(parserData* data, std::string element); - void parseContainer(parserData* data, std::string element); + void parseSize(parserData* data, const std::string &element); + void parseContainer(parserData* data, const std::string &element); void parseContainerEnd(parserData* data); - void parseList(parserData* data, std::string element); - void parseListRing(parserData* data, std::string element); - void parseCheckbox(parserData* data, std::string element); - void parseImage(parserData* data, std::string element); - void parseItemImage(parserData* data,std::string element); - void parseButton(parserData* data,std::string element,std::string typ); - void parseBackground(parserData* data,std::string element); - void parseTableOptions(parserData* data,std::string element); - void parseTableColumns(parserData* data,std::string element); - void parseTable(parserData* data,std::string element); - void parseTextList(parserData* data,std::string element); - void parseDropDown(parserData* data,std::string element); + void parseList(parserData* data, const std::string &element); + void parseListRing(parserData* data, const std::string &element); + void parseCheckbox(parserData* data, const std::string &element); + void parseImage(parserData* data, const std::string &element); + void parseItemImage(parserData* data, const std::string &element); + void parseButton(parserData* data, const std::string &element, + const std::string &typ); + void parseBackground(parserData* data, const std::string &element); + void parseTableOptions(parserData* data, const std::string &element); + void parseTableColumns(parserData* data, const std::string &element); + void parseTable(parserData* data, const std::string &element); + void parseTextList(parserData* data, const std::string &element); + void parseDropDown(parserData* data, const std::string &element); void parseFieldCloseOnEnter(parserData *data, const std::string &element); - void parsePwdField(parserData* data,std::string element); - void parseField(parserData* data,std::string element,std::string type); + void parsePwdField(parserData* data, const std::string &element); + void parseField(parserData* data, const std::string &element, const std::string &type); void parseSimpleField(parserData* data,std::vector &parts); void parseTextArea(parserData* data,std::vector& parts, - std::string type); - void parseLabel(parserData* data,std::string element); - void parseVertLabel(parserData* data,std::string element); - void parseImageButton(parserData* data,std::string element,std::string type); - void parseItemImageButton(parserData* data,std::string element); - void parseTabHeader(parserData* data,std::string element); - void parseBox(parserData* data,std::string element); - void parseBackgroundColor(parserData* data,std::string element); - void parseListColors(parserData* data,std::string element); - void parseTooltip(parserData* data,std::string element); - bool parseVersionDirect(std::string data); - bool parseSizeDirect(parserData* data, std::string element); - void parseScrollBar(parserData* data, std::string element); + const std::string &type); + void parseLabel(parserData* data, const std::string &element); + void parseVertLabel(parserData* data, const std::string &element); + void parseImageButton(parserData* data, const std::string &element, + const std::string &type); + void parseItemImageButton(parserData* data, const std::string &element); + void parseTabHeader(parserData* data, const std::string &element); + void parseBox(parserData* data, const std::string &element); + void parseBackgroundColor(parserData* data, const std::string &element); + void parseListColors(parserData* data, const std::string &element); + void parseTooltip(parserData* data, const std::string &element); + bool parseVersionDirect(const std::string &data); + bool parseSizeDirect(parserData* data, const std::string &element); + void parseScrollBar(parserData* data, const std::string &element); bool parsePositionDirect(parserData *data, const std::string &element); void parsePosition(parserData *data, const std::string &element); bool parseAnchorDirect(parserData *data, const std::string &element); diff --git a/src/guiTable.h b/src/guiTable.h index 4d5b39166..9fbe1c9da 100644 --- a/src/guiTable.h +++ b/src/guiTable.h @@ -74,11 +74,10 @@ public: std::string name; std::string value; - Option(const std::string &name_, const std::string &value_) - { - name = name_; - value = value_; - } + Option(const std::string &name_, const std::string &value_) : + name(name_), + value(value_) + {} }; /* diff --git a/src/httpfetch.cpp b/src/httpfetch.cpp index 21400355a..3b3f5d331 100644 --- a/src/httpfetch.cpp +++ b/src/httpfetch.cpp @@ -40,16 +40,15 @@ Mutex g_httpfetch_mutex; std::map > g_httpfetch_results; PcgRandom g_callerid_randomness; -HTTPFetchRequest::HTTPFetchRequest() +HTTPFetchRequest::HTTPFetchRequest() : + url(""), + caller(HTTPFETCH_DISCARD), + request_id(0), + timeout(g_settings->getS32("curl_timeout")), + connect_timeout(timeout), + multipart(false), + useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")") { - url = ""; - caller = HTTPFETCH_DISCARD; - request_id = 0; - timeout = g_settings->getS32("curl_timeout"); - connect_timeout = timeout; - multipart = false; - - useragent = std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")"; } diff --git a/src/httpfetch.h b/src/httpfetch.h index f57ed8789..d64b80b66 100644 --- a/src/httpfetch.h +++ b/src/httpfetch.h @@ -77,25 +77,23 @@ struct HTTPFetchResult unsigned long caller; unsigned long request_id; - HTTPFetchResult() - { - succeeded = false; - timeout = false; - response_code = 0; - data = ""; - caller = HTTPFETCH_DISCARD; - request_id = 0; - } - - HTTPFetchResult(const HTTPFetchRequest &fetch_request) - { - succeeded = false; - timeout = false; - response_code = 0; - data = ""; - caller = fetch_request.caller; - request_id = fetch_request.request_id; - } + HTTPFetchResult() : + succeeded(false), + timeout(false), + response_code(0), + data(""), + caller(HTTPFETCH_DISCARD), + request_id(0) + {} + + HTTPFetchResult(const HTTPFetchRequest &fetch_request) : + succeeded(false), + timeout(false), + response_code(0), + data(""), + caller(fetch_request.caller), + request_id(fetch_request.request_id) + {} }; diff --git a/src/map.cpp b/src/map.cpp index 3da96e77b..f8bbee180 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -2347,16 +2347,15 @@ bool ServerMap::saveBlock(MapBlock *block, Database *db) return ret; } -void ServerMap::loadBlock(std::string sectordir, std::string blockfile, +void ServerMap::loadBlock(const std::string §ordir, const std::string &blockfile, MapSector *sector, bool save_after_load) { DSTACK(FUNCTION_NAME); std::string fullpath = sectordir + DIR_DELIM + blockfile; try { - std::ifstream is(fullpath.c_str(), std::ios_base::binary); - if(is.good() == false) + if (!is.good()) throw FileNotGoodException("Cannot open block file"); v3s16 p3d = getBlockPos(sectordir, blockfile); diff --git a/src/map.h b/src/map.h index 90f97db8b..744a4d1e2 100644 --- a/src/map.h +++ b/src/map.h @@ -456,17 +456,11 @@ public: MapSector* loadSectorMeta(std::string dirname, bool save_after_load); bool loadSectorMeta(v2s16 p2d); - // Full load of a sector including all blocks. - // returns true on success, false on failure. - bool loadSectorFull(v2s16 p2d); - // If sector is not found in memory, try to load it from disk. - // Returns true if sector now resides in memory - //bool deFlushSector(v2s16 p2d); - bool saveBlock(MapBlock *block); static bool saveBlock(MapBlock *block, Database *db); // This will generate a sector with getSector if not found. - void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false); + void loadBlock(const std::string §ordir, const std::string &blockfile, + MapSector *sector, bool save_after_load=false); MapBlock* loadBlock(v3s16 p); // Database version void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false); diff --git a/src/network/connection.h b/src/network/connection.h index 5ee53b9d4..7ba0d086e 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -383,7 +383,7 @@ struct OutgoingPacket bool reliable; bool ack; - OutgoingPacket(u16 peer_id_, u8 channelnum_, SharedBuffer data_, + OutgoingPacket(u16 peer_id_, u8 channelnum_, const SharedBuffer &data_, bool reliable_,bool ack_=false): peer_id(peer_id_), channelnum(channelnum_), @@ -448,7 +448,7 @@ struct ConnectionCommand reliable = reliable_; } - void ack(u16 peer_id_, u8 channelnum_, SharedBuffer data_) + void ack(u16 peer_id_, u8 channelnum_, const SharedBuffer &data_) { type = CONCMD_ACK; peer_id = peer_id_; @@ -457,7 +457,7 @@ struct ConnectionCommand reliable = false; } - void createPeer(u16 peer_id_, SharedBuffer data_) + void createPeer(u16 peer_id_, const SharedBuffer &data_) { type = CONCMD_CREATE_PEER; peer_id = peer_id_; @@ -467,7 +467,7 @@ struct ConnectionCommand raw = true; } - void disableLegacy(u16 peer_id_, SharedBuffer data_) + void disableLegacy(u16 peer_id_, const SharedBuffer &data_) { type = CONCMD_DISABLE_LEGACY; peer_id = peer_id_; @@ -874,7 +874,7 @@ struct ConnectionEvent return "Invalid ConnectionEvent"; } - void dataReceived(u16 peer_id_, SharedBuffer data_) + void dataReceived(u16 peer_id_, const SharedBuffer &data_) { type = CONNEVENT_DATA_RECEIVED; peer_id = peer_id_; diff --git a/src/nodedef.h b/src/nodedef.h index da3345d80..83968ce27 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -218,14 +218,14 @@ struct TileDef struct TileAnimationParams animation; - TileDef() + TileDef() : + name(""), + backface_culling(true), + tileable_horizontal(true), + tileable_vertical(true), + has_color(false), + color(video::SColor(0xFFFFFFFF)) { - name = ""; - backface_culling = true; - tileable_horizontal = true; - tileable_vertical = true; - has_color = false; - color = video::SColor(0xFFFFFFFF); animation.type = TAT_NONE; } diff --git a/src/pathfinder.cpp b/src/pathfinder.cpp index ee06db630..16c5678ee 100644 --- a/src/pathfinder.cpp +++ b/src/pathfinder.cpp @@ -111,7 +111,7 @@ public: * @param dir direction to set cost for * @cost cost to set */ - void setCost(v3s16 dir, PathCost cost); + void setCost(v3s16 dir, const PathCost &cost); bool valid; /**< node is on surface */ bool target; /**< node is target position */ @@ -496,7 +496,7 @@ PathCost PathGridnode::getCost(v3s16 dir) } /******************************************************************************/ -void PathGridnode::setCost(v3s16 dir, PathCost cost) +void PathGridnode::setCost(v3s16 dir, const PathCost &cost) { if (dir.X > 0) { directions[DIR_XP] = cost; diff --git a/src/porting.cpp b/src/porting.cpp index 9d859da7d..8c92a3cba 100644 --- a/src/porting.cpp +++ b/src/porting.cpp @@ -408,7 +408,7 @@ bool setSystemPaths() #endif for (std::list::const_iterator - i = trylist.begin(); i != trylist.end(); i++) { + i = trylist.begin(); i != trylist.end(); ++i) { const std::string &trypath = *i; if (!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")) { diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index 1fb84fab6..a1bec83bf 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -100,7 +100,8 @@ void AsyncEngine::initialize(unsigned int numEngines) } /******************************************************************************/ -unsigned int AsyncEngine::queueAsyncJob(std::string func, std::string params) +unsigned int AsyncEngine::queueAsyncJob(const std::string &func, + const std::string ¶ms) { jobQueueMutex.lock(); LuaJobInfo toAdd; @@ -124,7 +125,6 @@ LuaJobInfo AsyncEngine::getJob() jobQueueMutex.lock(); LuaJobInfo retval; - retval.valid = false; if (!jobQueue.empty()) { retval = jobQueue.front(); @@ -137,7 +137,7 @@ LuaJobInfo AsyncEngine::getJob() } /******************************************************************************/ -void AsyncEngine::putJobResult(LuaJobInfo result) +void AsyncEngine::putJobResult(const LuaJobInfo &result) { resultQueueMutex.lock(); resultQueue.push_back(result); @@ -264,7 +264,7 @@ void* AsyncWorkerThread::run() // Wait for job LuaJobInfo toProcess = jobDispatcher->getJob(); - if (toProcess.valid == false || stopRequested()) { + if (!toProcess.valid || stopRequested()) { continue; } diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index 016381e5f..93e9759b4 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -38,7 +38,16 @@ class AsyncEngine; // Declarations // Data required to queue a job -struct LuaJobInfo { +struct LuaJobInfo +{ + LuaJobInfo() : + serializedFunction(""), + serializedParams(""), + serializedResult(""), + id(0), + valid(false) + {} + // Function to be called in async environment std::string serializedFunction; // Parameter to be passed to function @@ -89,7 +98,7 @@ public: * @param params Serialized parameters * @return jobid The job is queued */ - unsigned int queueAsyncJob(std::string func, std::string params); + unsigned int queueAsyncJob(const std::string &func, const std::string ¶ms); /** * Engine step to process finished jobs @@ -116,7 +125,7 @@ protected: * Put a Job result back to result queue * @param result result of completed job */ - void putJobResult(LuaJobInfo result); + void putJobResult(const LuaJobInfo &result); /** * Initialize environment with current registred functions diff --git a/src/script/scripting_mainmenu.cpp b/src/script/scripting_mainmenu.cpp index 61318735d..d79864a95 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -77,13 +77,15 @@ void MainMenuScripting::initializeModApi(lua_State *L, int top) } /******************************************************************************/ -void MainMenuScripting::step() { +void MainMenuScripting::step() +{ asyncEngine.step(getStack()); } /******************************************************************************/ -unsigned int MainMenuScripting::queueAsync(std::string serialized_func, - std::string serialized_param) { +unsigned int MainMenuScripting::queueAsync(const std::string &serialized_func, + const std::string &serialized_param) +{ return asyncEngine.queueAsyncJob(serialized_func, serialized_param); } diff --git a/src/script/scripting_mainmenu.h b/src/script/scripting_mainmenu.h index 3a0795df4..a1385ba9c 100644 --- a/src/script/scripting_mainmenu.h +++ b/src/script/scripting_mainmenu.h @@ -39,8 +39,8 @@ public: void step(); // Pass async events from engine to async threads - unsigned int queueAsync(std::string serialized_func, - std::string serialized_params); + unsigned int queueAsync(const std::string &serialized_func, + const std::string &serialized_params); private: void initializeModApi(lua_State *L, int top); diff --git a/src/sound.h b/src/sound.h index ba2d629d2..d13799eac 100644 --- a/src/sound.h +++ b/src/sound.h @@ -34,13 +34,15 @@ public: struct SimpleSoundSpec { + SimpleSoundSpec(const std::string &name = "", float gain = 1.0) : + name(name), + gain(gain) + {} + + bool exists() const { return name != ""; } + std::string name; float gain; - SimpleSoundSpec(std::string name = "", float gain = 1.0) : name(name), gain(gain) - { - } - bool exists() { return name != ""; } - // Serialization intentionally left out }; class ISoundManager diff --git a/src/util/string.h b/src/util/string.h index 1a0b9f60d..632dd4d7e 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -232,7 +232,7 @@ inline std::vector > str_split( */ inline std::string lowercase(const std::string &str) { - std::string s2; + std::string s2 = ""; s2.reserve(str.size()); diff --git a/src/util/thread.h b/src/util/thread.h index d43e06e0a..f54b8b48f 100644 --- a/src/util/thread.h +++ b/src/util/thread.h @@ -29,9 +29,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "container.h" template -class MutexedVariable { +class MutexedVariable +{ public: - MutexedVariable(T value): + MutexedVariable(const T &value): m_value(value) {} @@ -41,21 +42,14 @@ public: return m_value; } - void set(T value) + void set(const T &value) { MutexAutoLock lock(m_mutex); m_value = value; } - // You'll want to grab this in a SharedPtr - MutexAutoLock *getLock() - { - return new MutexAutoLock(m_mutex); - } - // You pretty surely want to grab the lock when accessing this T m_value; - private: Mutex m_mutex; }; -- cgit v1.2.3 From 370354cc87937bbfb6f24aa062966af8e039cec0 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Fri, 21 Apr 2017 10:06:08 +0200 Subject: Fix various performance issues reported by cppcheck (#5628) * Also remove 1 non declared but defined functions --- src/clientmedia.cpp | 14 +++++----- src/clientmedia.h | 4 +-- src/guiEngine.cpp | 4 +-- src/guiEngine.h | 7 ++--- src/guiFormSpecMenu.h | 65 +++++++++++++++++++--------------------------- src/network/connection.cpp | 5 ++-- src/network/connection.h | 4 +-- src/settings.h | 33 +++++++++++------------ 8 files changed, 59 insertions(+), 77 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/clientmedia.cpp b/src/clientmedia.cpp index bca3f67c2..14a38ca66 100644 --- a/src/clientmedia.cpp +++ b/src/clientmedia.cpp @@ -42,12 +42,12 @@ static std::string getMediaCacheDir() */ ClientMediaDownloader::ClientMediaDownloader(): - m_media_cache(getMediaCacheDir()) + m_media_cache(getMediaCacheDir()), + m_initial_step_done(false), + m_uncached_count(0), + m_uncached_received_count(0), + m_name_bound("") { - m_initial_step_done = false; - m_name_bound = ""; // works because "" is an invalid file name - m_uncached_count = 0; - m_uncached_received_count = 0; m_httpfetch_caller = HTTPFETCH_DISCARD; m_httpfetch_active = 0; m_httpfetch_active_limit = 0; @@ -69,7 +69,7 @@ ClientMediaDownloader::~ClientMediaDownloader() delete m_remotes[i]; } -void ClientMediaDownloader::addFile(std::string name, std::string sha1) +void ClientMediaDownloader::addFile(const std::string &name, const std::string &sha1) { assert(!m_initial_step_done); // pre-condition @@ -104,7 +104,7 @@ void ClientMediaDownloader::addFile(std::string name, std::string sha1) m_files.insert(std::make_pair(name, filestatus)); } -void ClientMediaDownloader::addRemoteServer(std::string baseurl) +void ClientMediaDownloader::addRemoteServer(const std::string &baseurl) { assert(!m_initial_step_done); // pre-condition diff --git a/src/clientmedia.h b/src/clientmedia.h index 1f0da70d9..e292be5ea 100644 --- a/src/clientmedia.h +++ b/src/clientmedia.h @@ -58,10 +58,10 @@ public: } // Add a file to the list of required file (but don't fetch it yet) - void addFile(std::string name, std::string sha1); + void addFile(const std::string &name, const std::string &sha1); // Add a remote server to the list; ignored if not built with cURL - void addRemoteServer(std::string baseurl); + void addRemoteServer(const std::string &baseurl); // Steps the media downloader: // - May load media into client by calling client->loadMedia() diff --git a/src/guiEngine.cpp b/src/guiEngine.cpp index e0ee00ad6..ebc4aac44 100644 --- a/src/guiEngine.cpp +++ b/src/guiEngine.cpp @@ -60,7 +60,7 @@ void TextDestGuiEngine::gotText(const StringMap &fields) } /******************************************************************************/ -void TextDestGuiEngine::gotText(std::wstring text) +void TextDestGuiEngine::gotText(const std::wstring &text) { m_engine->getScriptIface()->handleMainMenuEvent(wide_to_utf8(text)); } @@ -540,7 +540,7 @@ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath, } /******************************************************************************/ -bool GUIEngine::downloadFile(std::string url, std::string target) +bool GUIEngine::downloadFile(const std::string &url, const std::string &target) { #if USE_CURL std::ofstream target_file(target.c_str(), std::ios::out | std::ios::binary); diff --git a/src/guiEngine.h b/src/guiEngine.h index 98e88574c..e7e5ca05d 100644 --- a/src/guiEngine.h +++ b/src/guiEngine.h @@ -80,7 +80,7 @@ public: * receive text/events transmitted by guiFormSpecMenu * @param text textual representation of event */ - void gotText(std::wstring text); + void gotText(const std::wstring &text); private: /** target to transmit data to */ @@ -260,14 +260,11 @@ private: * @param url url to download * @param target file to store to */ - static bool downloadFile(std::string url,std::string target); + static bool downloadFile(const std::string &url, const std::string &target); /** array containing pointers to current specified texture layers */ image_definition m_textures[TEX_LAYER_MAX]; - /** draw version string in topleft corner */ - void drawVersion(); - /** * specify text to appear as top left string * @param text to set diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 4bc2448d8..ec122b617 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -78,22 +78,19 @@ class GUIFormSpecMenu : public GUIModalMenu { struct ItemSpec { - ItemSpec() - { - i = -1; - } + ItemSpec() : + i(-1) + {} + ItemSpec(const InventoryLocation &a_inventoryloc, const std::string &a_listname, - s32 a_i) - { - inventoryloc = a_inventoryloc; - listname = a_listname; - i = a_i; - } - bool isValid() const - { - return i != -1; - } + s32 a_i) : + inventoryloc(a_inventoryloc), + listname(a_listname), + i(a_i) + {} + + bool isValid() const { return i != -1; } InventoryLocation inventoryloc; std::string listname; @@ -208,14 +205,13 @@ class GUIFormSpecMenu : public GUIModalMenu const std::wstring &default_text, int id) : fname(name), flabel(label), + fdefault(unescape_enriched(default_text)), fid(id), send(false), ftype(f_Unknown), is_exit(false) - { - //flabel = unescape_enriched(label); - fdefault = unescape_enriched(default_text); - } + {} + std::string fname; std::wstring flabel; std::wstring fdefault; @@ -239,17 +235,14 @@ class GUIFormSpecMenu : public GUIModalMenu }; struct TooltipSpec { - TooltipSpec() - { - } + TooltipSpec() {} TooltipSpec(std::string a_tooltip, irr::video::SColor a_bgcolor, irr::video::SColor a_color): + tooltip(utf8_to_wide(a_tooltip)), bgcolor(a_bgcolor), color(a_color) - { - //tooltip = unescape_enriched(utf8_to_wide(a_tooltip)); - tooltip = utf8_to_wide(a_tooltip); - } + {} + std::wstring tooltip; irr::video::SColor bgcolor; irr::video::SColor color; @@ -271,12 +264,11 @@ class GUIFormSpecMenu : public GUIModalMenu StaticTextSpec(const std::wstring &a_text, const core::rect &a_rect, gui::IGUIButton *a_parent_button): + text(a_text), rect(a_rect), parent_button(a_parent_button) - { - //text = unescape_enriched(a_text); - text = a_text; - } + {} + std::wstring text; core::rect rect; gui::IGUIButton *parent_button; @@ -550,22 +542,19 @@ private: class FormspecFormSource: public IFormSource { public: - FormspecFormSource(const std::string &formspec) - { - m_formspec = formspec; - } + FormspecFormSource(const std::string &formspec): + m_formspec(formspec) + {} ~FormspecFormSource() {} - void setForm(const std::string &formspec) { + void setForm(const std::string &formspec) + { m_formspec = FORMSPEC_VERSION_STRING + formspec; } - std::string getForm() - { - return m_formspec; - } + std::string getForm() { return m_formspec; } std::string m_formspec; }; diff --git a/src/network/connection.cpp b/src/network/connection.cpp index e11b4a953..f9a4821a6 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -930,7 +930,7 @@ void Peer::DecUseCount() delete this; } -void Peer::RTTStatistics(float rtt, std::string profiler_id, +void Peer::RTTStatistics(float rtt, const std::string &profiler_id, unsigned int num_samples) { if (m_last_rtt > 0) { @@ -969,8 +969,7 @@ void Peer::RTTStatistics(float rtt, std::string profiler_id, m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) + jitter * (1/num_samples); - if (profiler_id != "") - { + if (profiler_id != "") { g_profiler->graphAdd(profiler_id + "_rtt", rtt); g_profiler->graphAdd(profiler_id + "_jitter", jitter); } diff --git a/src/network/connection.h b/src/network/connection.h index 7ba0d086e..dc86d2293 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -732,8 +732,8 @@ class Peer { virtual void reportRTT(float rtt) {}; void RTTStatistics(float rtt, - std::string profiler_id="", - unsigned int num_samples=1000); + const std::string &profiler_id = "", + unsigned int num_samples = 1000); bool IncUseCount(); void DecUseCount(); diff --git a/src/settings.h b/src/settings.h index 777d0eff5..8c4f6e559 100644 --- a/src/settings.h +++ b/src/settings.h @@ -74,24 +74,21 @@ struct ValueSpec { }; struct SettingsEntry { - SettingsEntry() - { - group = NULL; - is_group = false; - } - - SettingsEntry(const std::string &value_) - { - value = value_; - group = NULL; - is_group = false; - } - - SettingsEntry(Settings *group_) - { - group = group_; - is_group = true; - } + SettingsEntry() : + group(NULL), + is_group(false) + {} + + SettingsEntry(const std::string &value_) : + value(value_), + group(NULL), + is_group(false) + {} + + SettingsEntry(Settings *group_) : + group(group_), + is_group(true) + {} std::string value; Settings *group; -- cgit v1.2.3 From dc0e9097d3144a3dda81039f666ee43ba29cbc36 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Fri, 21 Apr 2017 23:40:48 +0200 Subject: Fix various performance issues reported by cppcheck + code style (CI) (#5635) * Make CI happy with code style on master * guiFileSelectMenu: remove useless includes * some performance fixes pointed by cppcheck * remove some useless casts * TextDest: remove unused setFormSpec function --- src/guiFileSelectMenu.cpp | 22 +++++++---------- src/guiFileSelectMenu.h | 7 ++---- src/guiFormSpecMenu.cpp | 5 ++-- src/guiFormSpecMenu.h | 60 +++++++++++++++++++++++++++++------------------ src/mesh.cpp | 10 ++++---- src/sound.h | 8 +++---- src/wieldmesh.h | 25 +++++++++----------- 7 files changed, 70 insertions(+), 67 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/guiFileSelectMenu.cpp b/src/guiFileSelectMenu.cpp index 0bb02f8a6..89d34a307 100644 --- a/src/guiFileSelectMenu.cpp +++ b/src/guiFileSelectMenu.cpp @@ -18,19 +18,17 @@ */ #include "guiFileSelectMenu.h" -#include "util/string.h" -#include GUIFileSelectMenu::GUIFileSelectMenu(gui::IGUIEnvironment* env, - gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, - std::string title, std::string formname) : -GUIModalMenu(env, parent, id, menumgr) + gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, + const std::string &title, const std::string &formname) : + GUIModalMenu(env, parent, id, menumgr), + m_title(utf8_to_wide(title)), + m_accepted(false), + m_parent(parent), + m_text_dst(NULL), + m_formname(formname) { - m_title = utf8_to_wide(title); - m_parent = parent; - m_formname = formname; - m_text_dst = 0; - m_accepted = false; } GUIFileSelectMenu::~GUIFileSelectMenu() @@ -107,16 +105,12 @@ bool GUIFileSelectMenu::OnEvent(const SEvent& event) acceptInput(); quitMenu(); return true; - break; - case gui::EGET_DIRECTORY_SELECTED: case gui::EGET_FILE_SELECTED: m_accepted=true; acceptInput(); quitMenu(); return true; - break; - default: //ignore this event break; diff --git a/src/guiFileSelectMenu.h b/src/guiFileSelectMenu.h index e37d3d8df..a266cb399 100644 --- a/src/guiFileSelectMenu.h +++ b/src/guiFileSelectMenu.h @@ -32,8 +32,7 @@ class GUIFileSelectMenu: public GUIModalMenu public: GUIFileSelectMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, - std::string title, - std::string formid); + const std::string &title, const std::string &formid); ~GUIFileSelectMenu(); void removeChildren(); @@ -47,9 +46,7 @@ public: bool OnEvent(const SEvent& event); - bool isRunning() { - return m_running; - } + bool isRunning() const { return m_running; } void setTextDest(TextDest * dest) { m_text_dst = dest; diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index ab93aeca1..5861e9a81 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -1770,10 +1770,11 @@ void GUIFormSpecMenu::parseAnchor(parserData *data, const std::string &element) return; } - errorstream << "Invalid anchor element (" << parts.size() << "): '" << element << "'" << std::endl; + errorstream << "Invalid anchor element (" << parts.size() << "): '" << element + << "'" << std::endl; } -void GUIFormSpecMenu::parseElement(parserData* data, std::string element) +void GUIFormSpecMenu::parseElement(parserData* data, const std::string &element) { //some prechecks if (element == "") diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index ec122b617..d70c3a582 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -55,12 +55,10 @@ typedef enum { struct TextDest { - virtual ~TextDest() {}; + virtual ~TextDest() {} // This is deprecated I guess? -celeron55 virtual void gotText(std::wstring text){} virtual void gotText(const StringMap &fields) = 0; - virtual void setFormName(std::string formname) - { m_formname = formname;}; std::string m_formname; }; @@ -80,7 +78,8 @@ class GUIFormSpecMenu : public GUIModalMenu { ItemSpec() : i(-1) - {} + { + } ItemSpec(const InventoryLocation &a_inventoryloc, const std::string &a_listname, @@ -88,7 +87,8 @@ class GUIFormSpecMenu : public GUIModalMenu inventoryloc(a_inventoryloc), listname(a_listname), i(a_i) - {} + { + } bool isValid() const { return i != -1; } @@ -141,7 +141,8 @@ class GUIFormSpecMenu : public GUIModalMenu ImageDrawSpec(): parent_button(NULL), clip(false) - {} + { + } ImageDrawSpec(const std::string &a_name, const std::string &a_item_name, @@ -154,7 +155,8 @@ class GUIFormSpecMenu : public GUIModalMenu geom(a_geom), scale(true), clip(false) - {} + { + } ImageDrawSpec(const std::string &a_name, const std::string &a_item_name, @@ -166,7 +168,8 @@ class GUIFormSpecMenu : public GUIModalMenu geom(a_geom), scale(true), clip(false) - {} + { + } ImageDrawSpec(const std::string &a_name, const v2s32 &a_pos, const v2s32 &a_geom, bool clip=false): @@ -176,7 +179,8 @@ class GUIFormSpecMenu : public GUIModalMenu geom(a_geom), scale(true), clip(clip) - {} + { + } ImageDrawSpec(const std::string &a_name, const v2s32 &a_pos): @@ -185,7 +189,8 @@ class GUIFormSpecMenu : public GUIModalMenu pos(a_pos), scale(false), clip(false) - {} + { + } std::string name; std::string item_name; @@ -210,7 +215,8 @@ class GUIFormSpecMenu : public GUIModalMenu send(false), ftype(f_Unknown), is_exit(false) - {} + { + } std::string fname; std::wstring flabel; @@ -222,7 +228,8 @@ class GUIFormSpecMenu : public GUIModalMenu core::rect rect; }; - struct BoxDrawSpec { + struct BoxDrawSpec + { BoxDrawSpec(v2s32 a_pos, v2s32 a_geom,irr::video::SColor a_color): pos(a_pos), geom(a_geom), @@ -234,40 +241,45 @@ class GUIFormSpecMenu : public GUIModalMenu irr::video::SColor color; }; - struct TooltipSpec { + struct TooltipSpec + { TooltipSpec() {} - TooltipSpec(std::string a_tooltip, irr::video::SColor a_bgcolor, + TooltipSpec(const std::string &a_tooltip, irr::video::SColor a_bgcolor, irr::video::SColor a_color): tooltip(utf8_to_wide(a_tooltip)), bgcolor(a_bgcolor), color(a_color) - {} + { + } std::wstring tooltip; irr::video::SColor bgcolor; irr::video::SColor color; }; - struct StaticTextSpec { + struct StaticTextSpec + { StaticTextSpec(): parent_button(NULL) { } + StaticTextSpec(const std::wstring &a_text, const core::rect &a_rect): + text(a_text), rect(a_rect), parent_button(NULL) { - //text = unescape_enriched(a_text); - text = a_text; } + StaticTextSpec(const std::wstring &a_text, const core::rect &a_rect, gui::IGUIButton *a_parent_button): text(a_text), rect(a_rect), parent_button(a_parent_button) - {} + { + } std::wstring text; core::rect rect; @@ -288,7 +300,7 @@ public: ~GUIFormSpecMenu(); void setFormSpec(const std::string &formspec_string, - InventoryLocation current_inventory_location) + const InventoryLocation ¤t_inventory_location) { m_formspec_string = formspec_string; m_current_inventory_location = current_inventory_location; @@ -461,7 +473,7 @@ private: fs_key_pendig current_keys_pending; std::string current_field_enter_pending; - void parseElement(parserData* data, std::string element); + void parseElement(parserData* data, const std::string &element); void parseSize(parserData* data, const std::string &element); void parseContainer(parserData* data, const std::string &element); @@ -544,10 +556,12 @@ class FormspecFormSource: public IFormSource public: FormspecFormSource(const std::string &formspec): m_formspec(formspec) - {} + { + } ~FormspecFormSource() - {} + { + } void setForm(const std::string &formspec) { diff --git a/src/mesh.cpp b/src/mesh.cpp index d776f6185..0a5b7fb6c 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -391,7 +391,7 @@ scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) switch (mesh_buffer->getVertexType()) { case video::EVT_STANDARD: { video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices(); - u16 *indices = (u16*) mesh_buffer->getIndices(); + u16 *indices = mesh_buffer->getIndices(); scene::SMeshBuffer *temp_buf = new scene::SMeshBuffer(); temp_buf->append(v, mesh_buffer->getVertexCount(), indices, mesh_buffer->getIndexCount()); @@ -401,7 +401,7 @@ scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) case video::EVT_2TCOORDS: { video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mesh_buffer->getVertices(); - u16 *indices = (u16*) mesh_buffer->getIndices(); + u16 *indices = mesh_buffer->getIndices(); scene::SMeshBufferTangents *temp_buf = new scene::SMeshBufferTangents(); temp_buf->append(v, mesh_buffer->getVertexCount(), indices, mesh_buffer->getIndexCount()); @@ -410,7 +410,7 @@ scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer) case video::EVT_TANGENTS: { video::S3DVertexTangents *v = (video::S3DVertexTangents *) mesh_buffer->getVertices(); - u16 *indices = (u16*) mesh_buffer->getIndices(); + u16 *indices = mesh_buffer->getIndices(); scene::SMeshBufferTangents *temp_buf = new scene::SMeshBufferTangents(); temp_buf->append(v, mesh_buffer->getVertexCount(), indices, mesh_buffer->getIndexCount()); @@ -447,7 +447,7 @@ scene::IMesh* convertNodeboxesToMesh(const std::vector &boxes, buf->drop(); } - video::SColor c(255,255,255,255); + video::SColor c(255,255,255,255); for (std::vector::const_iterator i = boxes.begin(); @@ -534,7 +534,7 @@ scene::IMesh* convertNodeboxesToMesh(const std::vector &boxes, buf->append(vertices + j, 4, indices, 6); } } - return dst_mesh; + return dst_mesh; } struct vcache diff --git a/src/sound.h b/src/sound.h index d13799eac..98f7692d5 100644 --- a/src/sound.h +++ b/src/sound.h @@ -34,10 +34,10 @@ public: struct SimpleSoundSpec { - SimpleSoundSpec(const std::string &name = "", float gain = 1.0) : - name(name), - gain(gain) - {} + SimpleSoundSpec(const std::string &name = "", float gain = 1.0) + : name(name), gain(gain) + { + } bool exists() const { return name != ""; } diff --git a/src/wieldmesh.h b/src/wieldmesh.h index c98b469d9..ef164c11f 100644 --- a/src/wieldmesh.h +++ b/src/wieldmesh.h @@ -31,7 +31,8 @@ struct ContentFeatures; /*! * Holds color information of an item mesh's buffer. */ -struct ItemPartColor { +struct ItemPartColor +{ /*! * If this is false, the global base color of the item * will be used instead of the specific color of the @@ -43,15 +44,12 @@ struct ItemPartColor { */ video::SColor color; - ItemPartColor(): - override_base(false), - color(0) - {} + ItemPartColor() : override_base(false), color(0) {} - ItemPartColor(bool override, video::SColor color): - override_base(override), - color(color) - {} + ItemPartColor(bool override, video::SColor color) + : override_base(override), color(color) + { + } }; struct ItemMesh @@ -75,8 +73,7 @@ public: s32 id = -1, bool lighting = false); virtual ~WieldMeshSceneNode(); - void setCube(const ContentFeatures &f, v3f wield_scale, - ITextureSource *tsrc); + void setCube(const ContentFeatures &f, v3f wield_scale, ITextureSource *tsrc); void setExtruded(const std::string &imagename, v3f wield_scale, ITextureSource *tsrc, u8 num_frames); void setItem(const ItemStack &item, Client *client); @@ -133,7 +130,7 @@ scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename * be NULL to leave the original material. * \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, - std::vector *colors); +void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders, + bool set_material, video::E_MATERIAL_TYPE *mattype, + std::vector *colors); #endif -- cgit v1.2.3 From 3e71c8f482131da59642b0175160eb2bc714d439 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Sat, 22 Apr 2017 00:51:13 +0200 Subject: Fixing warning pointed by @sfan5 and clang and cleanup guiFileSelectMenu * Also pass clang-format on guiFileSelectMenu.h and remove it from whitelist --- src/guiFileSelectMenu.cpp | 1 - src/guiFileSelectMenu.h | 26 +++++++------------------- src/guiFormSpecMenu.h | 2 +- src/modalMenu.h | 10 +++++----- util/travis/clang-format-whitelist.txt | 1 - 5 files changed, 13 insertions(+), 27 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/guiFileSelectMenu.cpp b/src/guiFileSelectMenu.cpp index 89d34a307..65a07be39 100644 --- a/src/guiFileSelectMenu.cpp +++ b/src/guiFileSelectMenu.cpp @@ -25,7 +25,6 @@ GUIFileSelectMenu::GUIFileSelectMenu(gui::IGUIEnvironment* env, GUIModalMenu(env, parent, id, menumgr), m_title(utf8_to_wide(title)), m_accepted(false), - m_parent(parent), m_text_dst(NULL), m_formname(formname) { diff --git a/src/guiFileSelectMenu.h b/src/guiFileSelectMenu.h index a266cb399..034823740 100644 --- a/src/guiFileSelectMenu.h +++ b/src/guiFileSelectMenu.h @@ -26,13 +26,12 @@ #include "IGUIFileOpenDialog.h" #include "guiFormSpecMenu.h" //required because of TextDest only !!! - -class GUIFileSelectMenu: public GUIModalMenu +class GUIFileSelectMenu : public GUIModalMenu { public: - GUIFileSelectMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, - s32 id, IMenuManager *menumgr, - const std::string &title, const std::string &formid); + GUIFileSelectMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, + IMenuManager *menumgr, const std::string &title, + const std::string &formid); ~GUIFileSelectMenu(); void removeChildren(); @@ -44,32 +43,21 @@ public: void drawMenu(); - bool OnEvent(const SEvent& event); - - bool isRunning() const { return m_running; } + bool OnEvent(const SEvent &event); - void setTextDest(TextDest * dest) { - m_text_dst = dest; - } + void setTextDest(TextDest *dest) { m_text_dst = dest; } private: void acceptInput(); std::wstring m_title; bool m_accepted; - gui::IGUIElement* m_parent; - - std::string m_selectedPath; - gui::IGUIFileOpenDialog* m_fileOpenDialog; - - bool m_running; + gui::IGUIFileOpenDialog *m_fileOpenDialog; TextDest *m_text_dst; std::string m_formname; }; - - #endif /* GUIFILESELECTMENU_H_ */ diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index d70c3a582..e30565be8 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -57,7 +57,7 @@ struct TextDest { virtual ~TextDest() {} // This is deprecated I guess? -celeron55 - virtual void gotText(std::wstring text){} + virtual void gotText(const std::wstring &text) {} virtual void gotText(const StringMap &fields) = 0; std::string m_formname; diff --git a/src/modalMenu.h b/src/modalMenu.h index 43bb8e1b8..38a26535e 100644 --- a/src/modalMenu.h +++ b/src/modalMenu.h @@ -43,14 +43,13 @@ public: class GUIModalMenu : public gui::IGUIElement { public: - GUIModalMenu(gui::IGUIEnvironment* env, - gui::IGUIElement* parent, s32 id, + GUIModalMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, IMenuManager *menumgr): IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, core::rect(0,0,100,100)) { //m_force_regenerate_gui = false; - + m_menumgr = menumgr; m_allow_focus_removal = false; m_screensize_old = v2u32(0,0); @@ -59,6 +58,7 @@ public: Environment->setFocus(this); m_menumgr->createdMenu(this); } + virtual ~GUIModalMenu() { m_menumgr->deletingMenu(this); @@ -78,7 +78,7 @@ public: { if(!IsVisible) return; - + video::IVideoDriver* driver = Environment->getVideoDriver(); v2u32 screensize = driver->getScreenSize(); if(screensize != m_screensize_old /*|| m_force_regenerate_gui*/) @@ -90,7 +90,7 @@ public: drawMenu(); } - + /* This should be called when the menu wants to quit. diff --git a/util/travis/clang-format-whitelist.txt b/util/travis/clang-format-whitelist.txt index 42ce6d781..3e746e289 100644 --- a/util/travis/clang-format-whitelist.txt +++ b/util/travis/clang-format-whitelist.txt @@ -94,7 +94,6 @@ src/guiChatConsole.h src/guiEngine.cpp src/guiEngine.h src/guiFileSelectMenu.cpp -src/guiFileSelectMenu.h src/guiFormSpecMenu.cpp src/guiFormSpecMenu.h src/guiKeyChangeMenu.cpp -- cgit v1.2.3 From a7e131f53e211ffbe38d34d23b33e13cc401f013 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Tue, 25 Apr 2017 10:17:53 +0200 Subject: Fix various points reported by cppcheck (#5656) * Fix various performance issues reported by cppcheck + code style (CI) * Make CI happy with code style on master * guiFileSelectMenu: remove useless includes * some performance fixes pointed by cppcheck * remove some useless casts * TextDest: remove unused setFormSpec function * Fix various iterator post-increment reported by cppcheck --- src/game.cpp | 3 ++- src/guiFormSpecMenu.h | 2 +- src/map_settings_manager.cpp | 13 ++++++------- src/nodedef.cpp | 7 +++---- src/script/cpp_api/s_async.cpp | 10 +++++----- src/script/cpp_api/s_node.cpp | 2 +- src/script/lua_api/l_client.cpp | 2 +- src/script/lua_api/l_craft.cpp | 2 +- src/script/lua_api/l_env.cpp | 5 ++--- src/script/lua_api/l_mainmenu.cpp | 2 +- src/script/lua_api/l_nodemeta.cpp | 2 +- src/script/lua_api/l_server.cpp | 4 ++-- src/util/thread.h | 6 +++--- 13 files changed, 29 insertions(+), 31 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/game.cpp b/src/game.cpp index fbc0cf35f..31a48531c 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -202,7 +202,8 @@ public: return meta->getString("formspec"); } - std::string resolveText(std::string str) + + virtual std::string resolveText(const std::string &str) { NodeMetadata *meta = m_map->getNodeMetadata(m_p); diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index e30565be8..af2d3f45e 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -69,7 +69,7 @@ public: virtual ~IFormSource(){} virtual std::string getForm() = 0; // Fill in variables in field text - virtual std::string resolveText(std::string str){ return str; } + virtual std::string resolveText(const std::string &str) { return str; } }; class GUIFormSpecMenu : public GUIModalMenu diff --git a/src/map_settings_manager.cpp b/src/map_settings_manager.cpp index 53d17125c..52f88778c 100644 --- a/src/map_settings_manager.cpp +++ b/src/map_settings_manager.cpp @@ -25,14 +25,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "map_settings_manager.h" -MapSettingsManager::MapSettingsManager( - Settings *user_settings, const std::string &map_meta_path) +MapSettingsManager::MapSettingsManager(Settings *user_settings, + const std::string &map_meta_path): + mapgen_params(NULL), + m_map_meta_path(map_meta_path), + m_map_settings(new Settings()), + m_user_settings(user_settings) { - m_map_meta_path = map_meta_path; - m_user_settings = user_settings; - m_map_settings = new Settings; - mapgen_params = NULL; - assert(m_user_settings != NULL); } diff --git a/src/nodedef.cpp b/src/nodedef.cpp index db28325aa..ce2834c91 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -1318,22 +1318,21 @@ void CNodeDefManager::removeNode(const std::string &name) // Erase node content from all groups it belongs to for (UNORDERED_MAP::iterator iter_groups = - m_group_to_items.begin(); - iter_groups != m_group_to_items.end();) { + m_group_to_items.begin(); iter_groups != m_group_to_items.end();) { GroupItems &items = iter_groups->second; for (GroupItems::iterator iter_groupitems = items.begin(); iter_groupitems != items.end();) { if (iter_groupitems->first == id) items.erase(iter_groupitems++); else - iter_groupitems++; + ++iter_groupitems; } // Check if group is empty if (items.size() == 0) m_group_to_items.erase(iter_groups++); else - iter_groups++; + ++iter_groups; } } diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index a1bec83bf..080ae887c 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -46,26 +46,26 @@ AsyncEngine::~AsyncEngine() // Request all threads to stop for (std::vector::iterator it = workerThreads.begin(); - it != workerThreads.end(); it++) { + it != workerThreads.end(); ++it) { (*it)->stop(); } // Wake up all threads for (std::vector::iterator it = workerThreads.begin(); - it != workerThreads.end(); it++) { + it != workerThreads.end(); ++it) { jobQueueCounter.post(); } // Wait for threads to finish for (std::vector::iterator it = workerThreads.begin(); - it != workerThreads.end(); it++) { + it != workerThreads.end(); ++it) { (*it)->wait(); } // Force kill all threads for (std::vector::iterator it = workerThreads.begin(); - it != workerThreads.end(); it++) { + it != workerThreads.end(); ++it) { delete *it; } @@ -205,7 +205,7 @@ void AsyncEngine::pushFinishedJobs(lua_State* L) { void AsyncEngine::prepareEnvironment(lua_State* L, int top) { for (UNORDERED_MAP::iterator it = functionList.begin(); - it != functionList.end(); it++) { + it != functionList.end(); ++it) { lua_pushstring(L, it->first.c_str()); lua_pushcfunction(L, it->second); lua_settable(L, top); diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index 2723f84e1..1ae8f58a5 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -263,7 +263,7 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, lua_pushstring(L, formname.c_str()); // formname lua_newtable(L); // fields StringMap::const_iterator it; - for (it = fields.begin(); it != fields.end(); it++) { + for (it = fields.begin(); it != fields.end(); ++it) { const std::string &name = it->first; const std::string &value = it->second; lua_pushstring(L, name.c_str()); diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index be3a749de..09ea5506b 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -83,7 +83,7 @@ int ModApiClient::l_get_player_names(lua_State *L) int newTable = lua_gettop(L); int index = 1; std::list::const_iterator iter; - for (iter = plist.begin(); iter != plist.end(); iter++) { + for (iter = plist.begin(); iter != plist.end(); ++iter) { lua_pushstring(L, (*iter).c_str()); lua_rawseti(L, newTable, index); index++; diff --git a/src/script/lua_api/l_craft.cpp b/src/script/lua_api/l_craft.cpp index 2236566de..315391856 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -414,7 +414,7 @@ static void push_craft_recipe(lua_State *L, IGameDef *gdef, lua_newtable(L); // items std::vector::const_iterator iter = input.items.begin(); - for (u16 j = 1; iter != input.items.end(); iter++, j++) { + for (u16 j = 1; iter != input.items.end(); ++iter, j++) { if (iter->empty()) continue; lua_pushstring(L, iter->name.c_str()); diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 1fa7845b5..75b07fa37 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -534,7 +534,7 @@ int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) ScriptApiBase *script = getScriptApiBase(L); lua_createtable(L, ids.size(), 0); std::vector::const_iterator iter = ids.begin(); - for(u32 i = 0; iter != ids.end(); iter++) { + for(u32 i = 0; iter != ids.end(); ++iter) { ServerActiveObject *obj = env->getActiveObject(*iter); // Insert object reference into table script->objectrefGetOrCreate(L, obj); @@ -985,8 +985,7 @@ int ModApiEnvMod::l_find_path(lua_State *L) lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; - for (std::vector::iterator i = path.begin(); i != path.end();i++) - { + for (std::vector::iterator i = path.begin(); i != path.end(); ++i) { lua_pushnumber(L,index); push_v3s16(L, *i); lua_settable(L, top); diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 3d204db98..4d0be257c 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -297,7 +297,7 @@ int ModApiMainMenu::l_get_games(lua_State *L) int table2 = lua_gettop(L); int internal_index=1; for (std::set::iterator iter = games[i].addon_mods_paths.begin(); - iter != games[i].addon_mods_paths.end(); iter++) { + iter != games[i].addon_mods_paths.end(); ++iter) { lua_pushnumber(L,internal_index); lua_pushstring(L,(*iter).c_str()); lua_settable(L, table2); diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index c65d56f14..6232112c5 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -107,7 +107,7 @@ void NodeMetaRef::handleToTable(lua_State *L, Metadata *_meta) if (inv) { std::vector lists = inv->getLists(); for(std::vector::const_iterator - i = lists.begin(); i != lists.end(); i++) { + i = lists.begin(); i != lists.end(); ++i) { push_inventory_list(L, inv, (*i)->getName().c_str()); lua_setfield(L, -2, (*i)->getName().c_str()); } diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index d94f3e31d..813d5a945 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -103,7 +103,7 @@ int ModApiServer::l_get_player_privs(lua_State *L) int table = lua_gettop(L); std::set privs_s = server->getPlayerEffectivePrivs(name); for(std::set::const_iterator - i = privs_s.begin(); i != privs_s.end(); i++){ + i = privs_s.begin(); i != privs_s.end(); ++i){ lua_pushboolean(L, true); lua_setfield(L, table, i->c_str()); } @@ -417,7 +417,7 @@ int ModApiServer::l_get_modnames(lua_State *L) // Package them up for Lua lua_createtable(L, modlist.size(), 0); std::vector::iterator iter = modlist.begin(); - for (u16 i = 0; iter != modlist.end(); iter++) { + for (u16 i = 0; iter != modlist.end(); ++iter) { lua_pushstring(L, iter->c_str()); lua_rawseti(L, -2, ++i); } diff --git a/src/util/thread.h b/src/util/thread.h index f54b8b48f..b96f302f6 100644 --- a/src/util/thread.h +++ b/src/util/thread.h @@ -83,8 +83,8 @@ public: GetRequest() {} ~GetRequest() {} - GetRequest(Key a_key) { - key = a_key; + GetRequest(const Key &a_key): key(a_key) + { } Key key; @@ -106,7 +106,7 @@ public: return m_queue.empty(); } - void add(Key key, Caller caller, CallerData callerdata, + void add(const Key &key, Caller caller, CallerData callerdata, ResultQueue *dest) { typename std::deque >::iterator i; -- cgit v1.2.3 From b662a4577d692329b9ca83525e6039f2ddcd1ac1 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Sun, 6 Mar 2016 14:31:16 -0500 Subject: Clean up getTime helpers This increases size of the getTime return values to 64 bits. It also removes the TimeGetter classes since the getTime functions are now very precise. --- src/client.cpp | 6 +- src/client/clientlauncher.cpp | 19 ----- src/client/clientlauncher.h | 36 -------- src/client/joystick_controller.cpp | 3 +- src/clientiface.cpp | 2 +- src/clientiface.h | 3 +- src/database-sqlite3.cpp | 2 +- src/gettime.h | 21 +---- src/guiChatConsole.cpp | 8 +- src/guiChatConsole.h | 2 +- src/guiFormSpecMenu.cpp | 8 +- src/guiFormSpecMenu.h | 4 +- src/guiTable.cpp | 2 +- src/guiTable.h | 2 +- src/hud.cpp | 6 +- src/main.cpp | 18 ---- src/map.cpp | 2 +- src/porting.cpp | 13 +++ src/porting.h | 163 ++++++++++++++++--------------------- src/touchscreengui.cpp | 2 +- src/touchscreengui.h | 2 +- src/util/timetaker.cpp | 8 +- 22 files changed, 116 insertions(+), 216 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/client.cpp b/src/client.cpp index 019693f1d..43b58d819 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -1618,7 +1618,7 @@ float Client::mediaReceiveProgress() typedef struct TextureUpdateArgs { IrrlichtDevice *device; gui::IGUIEnvironment *guienv; - u32 last_time_ms; + u64 last_time_ms; u16 last_percent; const wchar_t* text_base; ITextureSource *tsrc; @@ -1634,7 +1634,7 @@ void texture_update_progress(void *args, u32 progress, u32 max_progress) u32 time_ms = targs->last_time_ms; if (cur_percent != targs->last_percent) { targs->last_percent = cur_percent; - time_ms = getTimeMs(); + time_ms = porting::getTimeMs(); // only draw when the user will notice something: do_draw = (time_ms - targs->last_time_ms > 100); } @@ -1692,7 +1692,7 @@ void Client::afterContentReceived(IrrlichtDevice *device) TextureUpdateArgs tu_args; tu_args.device = device; tu_args.guienv = guienv; - tu_args.last_time_ms = getTimeMs(); + tu_args.last_time_ms = porting::getTimeMs(); tu_args.last_percent = 0; tu_args.text_base = wgettext("Initializing nodes"); tu_args.tsrc = m_tsrc; diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 249f6727a..be4e82134 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -51,22 +51,6 @@ bool noMenuActive() MainGameCallback *g_gamecallback = NULL; -// Instance of the time getter -static TimeGetter *g_timegetter = NULL; - -u32 getTimeMs() -{ - if (g_timegetter == NULL) - return 0; - return g_timegetter->getTime(PRECISION_MILLI); -} - -u32 getTime(TimePrecision prec) { - if (g_timegetter == NULL) - return 0; - return g_timegetter->getTime(prec); -} - ClientLauncher::~ClientLauncher() { if (receiver) @@ -96,9 +80,6 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args) return false; } - // Create time getter - g_timegetter = new IrrlichtTimeGetter(device); - // Speed tests (done after irrlicht is loaded to get timer) if (cmd_args.getFlag("speedtests")) { dstream << "Running speed tests" << std::endl; diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index ab22d7aaa..4ff77bc03 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -24,42 +24,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/inputhandler.h" #include "gameparams.h" -// A small helper class -class TimeGetter -{ -public: - virtual u32 getTime(TimePrecision prec) = 0; -}; - -// A precise irrlicht one -class IrrlichtTimeGetter: public TimeGetter -{ -public: - IrrlichtTimeGetter(IrrlichtDevice *device): - m_device(device) - {} - u32 getTime(TimePrecision prec) - { - if (prec == PRECISION_MILLI) { - if (m_device == NULL) - return 0; - return m_device->getTimer()->getRealTime(); - } else { - return porting::getTime(prec); - } - } -private: - IrrlichtDevice *m_device; -}; -// Not so precise one which works without irrlicht -class SimpleTimeGetter: public TimeGetter -{ -public: - u32 getTime(TimePrecision prec) - { - return porting::getTime(prec); - } -}; class ClientLauncher { diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index cb9d64b9f..905ca6420 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "keys.h" #include "settings.h" #include "gettime.h" +#include "porting.h" #include "../util/string.h" bool JoystickButtonCmb::isTriggered(const irr::SEvent::SJoystickEvent &ev) const @@ -199,7 +200,7 @@ bool JoystickController::handleEvent(const irr::SEvent::SJoystickEvent &ev) if (ev.Joystick != m_joystick_id) return false; - m_internal_time = getTimeMs() / 1000.f; + m_internal_time = porting::getTimeMs() / 1000.f; std::bitset keys_pressed; diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 64fa1c6b7..7f476f0ea 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -592,7 +592,7 @@ void RemoteClient::notifyEvent(ClientStateEvent event) u32 RemoteClient::uptime() { - return getTime(PRECISION_SECONDS) - m_connection_time; + return porting::getTime(PRECISION_SECONDS) - m_connection_time; } ClientInterface::ClientInterface(con::Connection* con) diff --git a/src/clientiface.h b/src/clientiface.h index 11ebdaab6..49101fbc1 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "threading/mutex.h" #include "network/networkpacket.h" #include "util/cpp11_container.h" +#include "porting.h" #include #include @@ -265,7 +266,7 @@ public: m_version_patch(0), m_full_version("unknown"), m_deployed_compression(0), - m_connection_time(getTime(PRECISION_SECONDS)) + m_connection_time(porting::getTime(PRECISION_SECONDS)) { } ~RemoteClient() diff --git a/src/database-sqlite3.cpp b/src/database-sqlite3.cpp index 714f56c39..7bc87a7d0 100644 --- a/src/database-sqlite3.cpp +++ b/src/database-sqlite3.cpp @@ -71,7 +71,7 @@ int Database_SQLite3::busyHandler(void *data, int count) { s64 &first_time = reinterpret_cast(data)[0]; s64 &prev_time = reinterpret_cast(data)[1]; - s64 cur_time = getTimeMs(); + s64 cur_time = porting::getTimeMs(); if (count == 0) { first_time = cur_time; diff --git a/src/gettime.h b/src/gettime.h index b2f09a7bb..a93eee387 100644 --- a/src/gettime.h +++ b/src/gettime.h @@ -21,33 +21,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #define GETTIME_HEADER #include "irrlichttypes.h" +#include +#include -/* - Get a millisecond counter value. - Precision depends on implementation. - Overflows at any value above 10000000. - Implementation of this is done in: - Normal build: main.cpp - Server build: servermain.cpp -*/ enum TimePrecision { - PRECISION_SECONDS = 0, + PRECISION_SECONDS, PRECISION_MILLI, PRECISION_MICRO, PRECISION_NANO }; -extern u32 getTimeMs(); -extern u32 getTime(TimePrecision prec); - -/* - Timestamp stuff -*/ - -#include -#include inline std::string getTimestamp() { diff --git a/src/guiChatConsole.cpp b/src/guiChatConsole.cpp index bea5571f4..b3c119555 100644 --- a/src/guiChatConsole.cpp +++ b/src/guiChatConsole.cpp @@ -55,7 +55,7 @@ GUIChatConsole::GUIChatConsole( m_client(client), m_menumgr(menumgr), m_screensize(v2u32(0,0)), - m_animate_time_old(0), + m_animate_time_old(porting::getTimeMs()), m_open(false), m_close_on_enter(false), m_height(0), @@ -71,8 +71,6 @@ GUIChatConsole::GUIChatConsole( m_font(NULL), m_fontsize(0, 0) { - m_animate_time_old = getTimeMs(); - // load background settings s32 console_alpha = g_settings->getS32("console_alpha"); m_background_color.setAlpha(clamp_u8(console_alpha)); @@ -124,7 +122,7 @@ void GUIChatConsole::openConsole(f32 scale) m_desired_height_fraction = scale; m_desired_height = scale * m_screensize.Y; reformatConsole(); - m_animate_time_old = getTimeMs(); + m_animate_time_old = porting::getTimeMs(); IGUIElement::setVisible(true); Environment->setFocus(this); m_menumgr->createdMenu(this); @@ -212,7 +210,7 @@ void GUIChatConsole::draw() } // Animation - u32 now = getTimeMs(); + u64 now = porting::getTimeMs(); animate(now - m_animate_time_old); m_animate_time_old = now; diff --git a/src/guiChatConsole.h b/src/guiChatConsole.h index 4e3cae13f..0332678c7 100644 --- a/src/guiChatConsole.h +++ b/src/guiChatConsole.h @@ -98,7 +98,7 @@ private: v2u32 m_screensize; // used to compute how much time passed since last animate() - u32 m_animate_time_old; + u64 m_animate_time_old; // should the console be opened or closed? bool m_open; diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 14d576f8f..64642cf1f 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2664,9 +2664,9 @@ void GUIFormSpecMenu::drawMenu() m_old_tooltip = L""; } else { if (id == m_old_tooltip_id) { - delta = porting::getDeltaMs(m_hovered_time, getTimeMs()); + delta = porting::getDeltaMs(m_hovered_time, porting::getTimeMs()); } else { - m_hovered_time = getTimeMs(); + m_hovered_time = porting::getTimeMs(); m_old_tooltip_id = id; } } @@ -3244,10 +3244,10 @@ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) m_doubleclickdetect[0].time = m_doubleclickdetect[1].time; m_doubleclickdetect[1].pos = m_pointer; - m_doubleclickdetect[1].time = getTimeMs(); + m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { - u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, getTimeMs()); + u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index af2d3f45e..18ccf1c3a 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -421,7 +421,7 @@ protected: gui::IGUIStaticText *m_tooltip_element; u32 m_tooltip_show_delay; - s32 m_hovered_time; + s64 m_hovered_time; s32 m_old_tooltip_id; std::wstring m_old_tooltip; @@ -527,7 +527,7 @@ private: struct clickpos { v2s32 pos; - s32 time; + s64 time; }; clickpos m_doubleclickdetect[2]; diff --git a/src/guiTable.cpp b/src/guiTable.cpp index 6b33b8266..d223e3069 100644 --- a/src/guiTable.cpp +++ b/src/guiTable.cpp @@ -828,7 +828,7 @@ bool GUITable::OnEvent(const SEvent &event) } else if (event.KeyInput.PressedDown && event.KeyInput.Char) { // change selection based on text as it is typed - s32 now = getTimeMs(); + u64 now = porting::getTimeMs(); if (now - m_keynav_time >= 500) m_keynav_buffer = L""; m_keynav_time = now; diff --git a/src/guiTable.h b/src/guiTable.h index 9fbe1c9da..02e8af00b 100644 --- a/src/guiTable.h +++ b/src/guiTable.h @@ -196,7 +196,7 @@ protected: bool m_sel_doubleclick; // Keyboard navigation stuff - s32 m_keynav_time; + u64 m_keynav_time; core::stringw m_keynav_buffer; // Drawing and geometry information diff --git a/src/hud.cpp b/src/hud.cpp index c482912e9..9729013ee 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -619,7 +619,7 @@ void Hud::resizeHotbar() { } struct MeshTimeInfo { - s32 time; + s64 time; scene::IMesh *mesh; }; @@ -653,9 +653,9 @@ void drawItemStack(video::IVideoDriver *driver, MeshTimeInfo &ti = rotation_time_infos[rotation_kind]; if (mesh != ti.mesh) { ti.mesh = mesh; - ti.time = getTimeMs(); + ti.time = porting::getTimeMs(); } else { - delta = porting::getDeltaMs(ti.time, getTimeMs()) % 100000; + delta = porting::getDeltaMs(ti.time, porting::getTimeMs()) % 100000; } } core::rect oldViewPort = driver->getViewPort(); diff --git a/src/main.cpp b/src/main.cpp index 2ad4e2780..6a2e89f7a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -107,24 +107,6 @@ static bool migrate_map_database(const GameParams &game_params, const Settings & /**********************************************************************/ -/* - gettime.h implementation -*/ - -#ifdef SERVER - -u32 getTimeMs() -{ - /* Use imprecise system calls directly (from porting.h) */ - return porting::getTime(PRECISION_MILLI); -} - -u32 getTime(TimePrecision prec) -{ - return porting::getTime(prec); -} - -#endif FileLogOutput file_log_output; diff --git a/src/map.cpp b/src/map.cpp index 9e8823f84..63e1e4ccd 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -981,7 +981,7 @@ void Map::transformLiquids(std::map &modified_blocks, time_until_purge *= 1000; // seconds -> milliseconds - u32 curr_time = getTime(PRECISION_MILLI); + u32 curr_time = porting::getTime(PRECISION_MILLI); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); diff --git a/src/porting.cpp b/src/porting.cpp index 8c92a3cba..10b6fc940 100644 --- a/src/porting.cpp +++ b/src/porting.cpp @@ -942,5 +942,18 @@ void attachOrCreateConsole(void) #endif } +// Load performance counter frequency only once at startup +#ifdef _WIN32 + +inline double get_perf_freq() +{ + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + return freq.QuadPart; +} + +double perf_freq = get_perf_freq(); + +#endif } //namespace porting diff --git a/src/porting.h b/src/porting.h index aa389d02c..7034d956b 100644 --- a/src/porting.h +++ b/src/porting.h @@ -181,124 +181,99 @@ std::string get_sysinfo(); void initIrrlicht(irr::IrrlichtDevice * ); -/* - Resolution is 10-20ms. - Remember to check for overflows. - Overflow can occur at any value higher than 10000000. -*/ -#ifdef _WIN32 // Windows - inline u32 getTimeS() - { - return GetTickCount() / 1000; - } +// Monotonic counter getters. - inline u32 getTimeMs() - { - return GetTickCount(); - } +#ifdef _WIN32 // Windows - inline u32 getTimeUs() - { - LARGE_INTEGER freq, t; - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&t); - return (double)(t.QuadPart) / ((double)(freq.QuadPart) / 1000000.0); - } +extern double perf_freq; - inline u32 getTimeNs() - { - LARGE_INTEGER freq, t; - QueryPerformanceFrequency(&freq); - QueryPerformanceCounter(&t); - return (double)(t.QuadPart) / ((double)(freq.QuadPart) / 1000000000.0); - } +inline u64 os_get_time(double mult) +{ + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return static_cast(t.QuadPart) / (perf_freq / mult); +} + +// Resolution is <1us. +inline u64 getTimeS() { return os_get_time(1); } +inline u64 getTimeMs() { return os_get_time(1000); } +inline u64 getTimeUs() { return os_get_time(1000*1000); } +inline u64 getTimeNs() { return os_get_time(1000*1000*1000); } #else // Posix - inline void _os_get_clock(struct timespec *ts) - { + +inline void os_get_clock(struct timespec *ts) +{ #if defined(__MACH__) && defined(__APPLE__) - // from http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x - // OS X does not have clock_gettime, use clock_get_time - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - ts->tv_sec = mts.tv_sec; - ts->tv_nsec = mts.tv_nsec; +// From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x +// OS X does not have clock_gettime, use clock_get_time + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + ts->tv_sec = mts.tv_sec; + ts->tv_nsec = mts.tv_nsec; #elif defined(CLOCK_MONOTONIC_RAW) - clock_gettime(CLOCK_MONOTONIC_RAW, ts); + clock_gettime(CLOCK_MONOTONIC_RAW, ts); #elif defined(_POSIX_MONOTONIC_CLOCK) - clock_gettime(CLOCK_MONOTONIC, ts); + clock_gettime(CLOCK_MONOTONIC, ts); #else - struct timeval tv; - gettimeofday(&tv, NULL); - TIMEVAL_TO_TIMESPEC(&tv, ts); -#endif // defined(__MACH__) && defined(__APPLE__) - } + struct timeval tv; + gettimeofday(&tv, NULL); + TIMEVAL_TO_TIMESPEC(&tv, ts); +#endif +} - // Note: these clock functions do not return wall time, but - // generally a clock that starts at 0 when the process starts. - inline u32 getTimeS() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec; - } +inline u64 getTimeS() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec; +} - inline u32 getTimeMs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; - } +inline u64 getTimeMs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} - inline u32 getTimeUs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; - } +inline u64 getTimeUs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; +} - inline u32 getTimeNs() - { - struct timespec ts; - _os_get_clock(&ts); - return ts.tv_sec * 1000000000 + ts.tv_nsec; - } +inline u64 getTimeNs() +{ + struct timespec ts; + os_get_clock(&ts); + return ts.tv_sec * 1000000000 + ts.tv_nsec; +} - /*#include - inline u32 getTimeMs() - { - struct timeb tb; - ftime(&tb); - return tb.time * 1000 + tb.millitm; - }*/ #endif -inline u32 getTime(TimePrecision prec) +inline u64 getTime(TimePrecision prec) { switch (prec) { - case PRECISION_SECONDS: - return getTimeS(); - case PRECISION_MILLI: - return getTimeMs(); - case PRECISION_MICRO: - return getTimeUs(); - case PRECISION_NANO: - return getTimeNs(); + case PRECISION_SECONDS: return getTimeS(); + case PRECISION_MILLI: return getTimeMs(); + case PRECISION_MICRO: return getTimeUs(); + case PRECISION_NANO: return getTimeNs(); } - return 0; + FATAL_ERROR("Called getTime with invalid time precision"); } /** - * Delta calculation function taking two 32bit arguments. - * @param old_time_ms old time for delta calculation (order is relevant!) - * @param new_time_ms new time for delta calculation (order is relevant!) - * @return positive 32bit delta value + * Delta calculation function arguments. + * @param old_time_ms old time for delta calculation + * @param new_time_ms new time for delta calculation + * @return positive delta value */ -inline u32 getDeltaMs(u32 old_time_ms, u32 new_time_ms) +inline u64 getDeltaMs(u64 old_time_ms, u64 new_time_ms) { if (new_time_ms >= old_time_ms) { return (new_time_ms - old_time_ms); diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index 8d210c63a..1f80da691 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -794,7 +794,7 @@ void TouchScreenGUI::translateEvent(const SEvent &event) if (m_move_id == -1) { m_move_id = event.TouchInput.ID; m_move_has_really_moved = false; - m_move_downtime = getTimeMs(); + m_move_downtime = porting::getTimeMs(); m_move_downlocation = v2s32(event.TouchInput.X, event.TouchInput.Y); m_move_sent_as_mouse_event = false; } diff --git a/src/touchscreengui.h b/src/touchscreengui.h index 1308d78ae..f4f1766c9 100644 --- a/src/touchscreengui.h +++ b/src/touchscreengui.h @@ -186,7 +186,7 @@ private: int m_move_id; bool m_move_has_really_moved; - s32 m_move_downtime; + s64 m_move_downtime; bool m_move_sent_as_mouse_event; v2s32 m_move_downlocation; diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index dcf07dc0d..0e92696ac 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "timetaker.h" -#include "../gettime.h" +#include "../porting.h" #include "../log.h" #include @@ -29,14 +29,14 @@ TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) m_result = result; m_running = true; m_precision = prec; - m_time1 = getTime(prec); + m_time1 = porting::getTime(prec); } u32 TimeTaker::stop(bool quiet) { if(m_running) { - u32 time2 = getTime(m_precision); + u32 time2 = porting::getTime(m_precision); u32 dtime = time2 - m_time1; if(m_result != NULL) { @@ -64,7 +64,7 @@ u32 TimeTaker::stop(bool quiet) u32 TimeTaker::getTimerTime() { - u32 time2 = getTime(m_precision); + u32 time2 = porting::getTime(m_precision); u32 dtime = time2 - m_time1; return dtime; } -- cgit v1.2.3 From d99b6fed5517797bfafe4bbb307963967f0ca749 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Fri, 26 May 2017 14:03:36 +0200 Subject: Time: Change old `u32` timestamps to 64-bit (#5818) MacOSX build fix + cleanups --- src/clientiface.cpp | 4 ++-- src/clientiface.h | 6 +++--- src/guiFormSpecMenu.cpp | 4 ++-- src/guiFormSpecMenu.h | 4 ++-- src/hud.cpp | 2 +- src/intlGUIEditBox.h | 2 +- src/map.cpp | 2 +- src/map.h | 2 +- src/network/connection.h | 2 +- src/profiler.cpp | 30 ++++++++++++++++++++++++++++++ src/profiler.h | 44 ++------------------------------------------ src/touchscreengui.cpp | 4 ++-- src/unittest/test.cpp | 8 ++++---- src/unittest/test.h | 4 ++-- src/util/timetaker.cpp | 23 ++++++++--------------- src/util/timetaker.h | 14 +++++++------- src/voxel.cpp | 12 ++++-------- src/voxel.h | 4 ++-- 18 files changed, 75 insertions(+), 96 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 356281ca6..68bd4afe7 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -590,9 +590,9 @@ void RemoteClient::notifyEvent(ClientStateEvent event) } } -u32 RemoteClient::uptime() const +u64 RemoteClient::uptime() const { - return porting::getTime(PRECISION_SECONDS) - m_connection_time; + return porting::getTimeS() - m_connection_time; } ClientInterface::ClientInterface(con::Connection* con) diff --git a/src/clientiface.h b/src/clientiface.h index a219ed5fc..d2299c879 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -266,7 +266,7 @@ public: m_version_patch(0), m_full_version("unknown"), m_deployed_compression(0), - m_connection_time(porting::getTime(PRECISION_SECONDS)) + m_connection_time(porting::getTimeS()) { } ~RemoteClient() @@ -345,7 +345,7 @@ public: { serialization_version = m_pending_serialization_version; } /* get uptime */ - u32 uptime() const; + u64 uptime() const; /* set version information */ void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full) @@ -432,7 +432,7 @@ private: /* time this client was created */ - const u32 m_connection_time; + const u64 m_connection_time; }; class ClientInterface { diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 64642cf1f..971d505fd 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2658,7 +2658,7 @@ void GUIFormSpecMenu::drawMenu() if (hovered != NULL) { s32 id = hovered->getID(); - u32 delta = 0; + u64 delta = 0; if (id == -1) { m_old_tooltip_id = id; m_old_tooltip = L""; @@ -3247,7 +3247,7 @@ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { - u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 18ccf1c3a..557a1cc9f 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -420,8 +420,8 @@ protected: v2s32 m_old_pointer; // Mouse position after previous mouse event gui::IGUIStaticText *m_tooltip_element; - u32 m_tooltip_show_delay; - s64 m_hovered_time; + u64 m_tooltip_show_delay; + u64 m_hovered_time; s32 m_old_tooltip_id; std::wstring m_old_tooltip; diff --git a/src/hud.cpp b/src/hud.cpp index 3e4162b64..72145b4da 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -626,7 +626,7 @@ void Hud::resizeHotbar() { } struct MeshTimeInfo { - s64 time; + u64 time; scene::IMesh *mesh; }; diff --git a/src/intlGUIEditBox.h b/src/intlGUIEditBox.h index e3ee15a30..bb617476c 100644 --- a/src/intlGUIEditBox.h +++ b/src/intlGUIEditBox.h @@ -155,7 +155,7 @@ namespace gui gui::IGUIFont *OverrideFont, *LastBreakFont; IOSOperator* Operator; - u32 BlinkStartTime; + u64 BlinkStartTime; s32 CursorPos; s32 HScrollPos, VScrollPos; // scroll position in characters u32 Max; diff --git a/src/map.cpp b/src/map.cpp index 63e1e4ccd..641b7d2dd 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -981,7 +981,7 @@ void Map::transformLiquids(std::map &modified_blocks, time_until_purge *= 1000; // seconds -> milliseconds - u32 curr_time = porting::getTime(PRECISION_MILLI); + u64 curr_time = porting::getTimeMs(); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); diff --git a/src/map.h b/src/map.h index 7e597bef6..41a1a246b 100644 --- a/src/map.h +++ b/src/map.h @@ -343,7 +343,7 @@ protected: private: f32 m_transforming_liquid_loop_count_multiplier; u32 m_unprocessed_count; - u32 m_inc_trending_up_start_time; // milliseconds + u64 m_inc_trending_up_start_time; // milliseconds bool m_queue_size_timer_started; DISABLE_CLASS_COPY(Map); diff --git a/src/network/connection.h b/src/network/connection.h index 3a8388522..8b7ed9773 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -769,7 +769,7 @@ class Peer { // Seconds from last receive float m_timeout_counter; - u32 m_last_timeout_check; + u64 m_last_timeout_check; }; class UDPPeer : public Peer diff --git a/src/profiler.cpp b/src/profiler.cpp index 197e094f6..8e997442c 100644 --- a/src/profiler.cpp +++ b/src/profiler.cpp @@ -21,3 +21,33 @@ with this program; if not, write to the Free Software Foundation, Inc., static Profiler main_profiler; Profiler *g_profiler = &main_profiler; +ScopeProfiler::ScopeProfiler( + Profiler *profiler, const std::string &name, ScopeProfilerType type) + : m_profiler(profiler), m_name(name), m_timer(NULL), m_type(type) +{ + if (m_profiler) + m_timer = new TimeTaker(m_name); +} + +ScopeProfiler::~ScopeProfiler() +{ + if (!m_timer) + return; + + float duration_ms = m_timer->stop(true); + float duration = duration_ms / 1000.0; + if (m_profiler) { + switch (m_type) { + case SPT_ADD: + m_profiler->add(m_name, duration); + break; + case SPT_AVG: + m_profiler->avg(m_name, duration); + break; + case SPT_GRAPH_ADD: + m_profiler->graphAdd(m_name, duration); + break; + } + } + delete m_timer; +} diff --git a/src/profiler.h b/src/profiler.h index 6da115972..ce60c6262 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -193,48 +193,8 @@ class ScopeProfiler { public: ScopeProfiler(Profiler *profiler, const std::string &name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - // name is copied - ScopeProfiler(Profiler *profiler, const char *name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - ~ScopeProfiler() - { - if(m_timer) - { - float duration_ms = m_timer->stop(true); - float duration = duration_ms / 1000.0; - if(m_profiler){ - switch(m_type){ - case SPT_ADD: - m_profiler->add(m_name, duration); - break; - case SPT_AVG: - m_profiler->avg(m_name, duration); - break; - case SPT_GRAPH_ADD: - m_profiler->graphAdd(m_name, duration); - break; - } - } - delete m_timer; - } - } + ScopeProfilerType type = SPT_ADD); + ~ScopeProfiler(); private: Profiler *m_profiler; std::string m_name; diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index f32679ca4..0139b8c4f 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -922,7 +922,7 @@ bool TouchScreenGUI::doubleTapDetection() m_key_events[1].x = m_move_downlocation.X; m_key_events[1].y = m_move_downlocation.Y; - u32 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); if (delta > 400) return false; @@ -1006,7 +1006,7 @@ void TouchScreenGUI::step(float dtime) (!m_move_has_really_moved) && (!m_move_sent_as_mouse_event)) { - u32 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); if (delta > MIN_DIG_TIME_MS) { m_shootline = m_device diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 9d223b82d..570807ba7 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -229,7 +229,7 @@ bool run_tests() { DSTACK(FUNCTION_NAME); - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); TestGameDef gamedef; g_logger.setLevelSilenced(LL_ERROR, true); @@ -246,7 +246,7 @@ bool run_tests() num_total_tests_run += testmods[i]->num_tests_run; } - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; g_logger.setLevelSilenced(LL_ERROR, false); @@ -273,12 +273,12 @@ bool run_tests() bool TestBase::testModule(IGameDef *gamedef) { rawstream << "======== Testing module " << getName() << std::endl; - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); runTests(gamedef); - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; rawstream << "======== Module " << getName() << " " << (num_tests_failed ? "failed" : "passed") << " (" << num_tests_failed << " failures / " << num_tests_run << " tests) - " << tdiff diff --git a/src/unittest/test.h b/src/unittest/test.h index e60e657cc..bf76e8bb2 100644 --- a/src/unittest/test.h +++ b/src/unittest/test.h @@ -33,7 +33,7 @@ class TestFailedException : public std::exception { // Runs a unit test and reports results #define TEST(fxn, ...) do { \ - u32 t1 = porting::getTime(PRECISION_MILLI); \ + u64 t1 = porting::getTimeMs(); \ try { \ fxn(__VA_ARGS__); \ rawstream << "[PASS] "; \ @@ -46,7 +46,7 @@ class TestFailedException : public std::exception { num_tests_failed++; \ } \ num_tests_run++; \ - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; \ + u64 tdiff = porting::getTimeMs() - t1; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ } while (0) diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index 0e92696ac..ac686c3a3 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../log.h" #include -TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) +TimeTaker::TimeTaker(const std::string &name, u64 *result, TimePrecision prec) { m_name = name; m_result = result; @@ -32,18 +32,13 @@ TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) m_time1 = porting::getTime(prec); } -u32 TimeTaker::stop(bool quiet) +u64 TimeTaker::stop(bool quiet) { - if(m_running) - { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - if(m_result != NULL) - { + if (m_running) { + u64 dtime = porting::getTime(m_precision) - m_time1; + if (m_result != NULL) { (*m_result) += dtime; - } - else - { + } else { if (!quiet) { static const char* const units[] = { "s" /* PRECISION_SECONDS */, @@ -62,10 +57,8 @@ u32 TimeTaker::stop(bool quiet) return 0; } -u32 TimeTaker::getTimerTime() +u64 TimeTaker::getTimerTime() { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - return dtime; + return porting::getTime(m_precision) - m_time1; } diff --git a/src/util/timetaker.h b/src/util/timetaker.h index 5512c205f..c10f4f535 100644 --- a/src/util/timetaker.h +++ b/src/util/timetaker.h @@ -30,24 +30,24 @@ with this program; if not, write to the Free Software Foundation, Inc., class TimeTaker { public: - TimeTaker(const char *name, u32 *result=NULL, - TimePrecision=PRECISION_MILLI); + TimeTaker(const std::string &name, u64 *result=NULL, + TimePrecision prec=PRECISION_MILLI); ~TimeTaker() { stop(); } - u32 stop(bool quiet=false); + u64 stop(bool quiet=false); - u32 getTimerTime(); + u64 getTimerTime(); private: - const char *m_name; - u32 m_time1; + std::string m_name; + u64 m_time1; bool m_running; TimePrecision m_precision; - u32 *m_result; + u64 *m_result; }; #endif diff --git a/src/voxel.cpp b/src/voxel.cpp index 87773b240..78efde5bb 100644 --- a/src/voxel.cpp +++ b/src/voxel.cpp @@ -27,14 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Debug stuff */ -u32 addarea_time = 0; -u32 emerge_time = 0; -u32 emerge_load_time = 0; -u32 clearflag_time = 0; -//u32 getwaterpressure_time = 0; -//u32 spreadwaterpressure_time = 0; -u32 updateareawaterpressure_time = 0; -u32 flowwater_pre_time = 0; +u64 addarea_time = 0; +u64 emerge_time = 0; +u64 emerge_load_time = 0; +u64 clearflag_time = 0; VoxelManipulator::VoxelManipulator(): diff --git a/src/voxel.h b/src/voxel.h index 58ad39be4..3a64ccc79 100644 --- a/src/voxel.h +++ b/src/voxel.h @@ -49,8 +49,8 @@ class INodeDefManager; /* Debug stuff */ -extern u32 emerge_time; -extern u32 emerge_load_time; +extern u64 emerge_time; +extern u64 emerge_load_time; /* This class resembles aabbox3d a lot, but has inclusive -- cgit v1.2.3 From 7a2b9df970568e705ced3256e0a921ffa56faa9d Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Sat, 3 Jun 2017 08:55:26 +0200 Subject: Tooltips: Unify the tooltip[] and list[] description tooltip display functions (#5848) * Tooltips: Unify the tooltip[] and list[] description tooltip display functions --- src/guiFormSpecMenu.cpp | 125 ++++++++++++++++++++++++------------------------ src/guiFormSpecMenu.h | 3 ++ 2 files changed, 65 insertions(+), 63 deletions(-) (limited to 'src/guiFormSpecMenu.h') diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 22852b5e4..19fd9f1f0 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2399,37 +2399,9 @@ void GUIFormSpecMenu::drawList(const ListDrawSpec &s, int phase, if (!item.name.empty() && tooltip_text.empty()) tooltip_text = utf8_to_wide(item.name); } - if (tooltip_text != L"") { - std::vector tt_rows = str_split(tooltip_text, L'\n'); - m_tooltip_element->setBackgroundColor(m_default_tooltip_bgcolor); - m_tooltip_element->setOverrideColor(m_default_tooltip_color); - m_tooltip_element->setVisible(true); - this->bringToFront(m_tooltip_element); - setStaticText(m_tooltip_element, tooltip_text.c_str()); - s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; -#if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1 - s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5; -#else - s32 tooltip_height = m_tooltip_element->getTextHeight() + 5; -#endif - v2u32 screenSize = driver->getScreenSize(); - int tooltip_offset_x = m_btn_height; - int tooltip_offset_y = m_btn_height; -#ifdef __ANDROID__ - tooltip_offset_x *= 3; - tooltip_offset_y = 0; - if (m_pointer.X > (s32)screenSize.X / 2) - tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1; -#endif - s32 tooltip_x = m_pointer.X + tooltip_offset_x; - s32 tooltip_y = m_pointer.Y + tooltip_offset_y; - if (tooltip_x + tooltip_width > (s32)screenSize.X) - tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; - if (tooltip_y + tooltip_height > (s32)screenSize.Y) - tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height; - m_tooltip_element->setRelativePosition(core::rect( - core::position2d(tooltip_x, tooltip_y), - core::dimension2d(tooltip_width, tooltip_height))); + if (!tooltip_text.empty()) { + showTooltip(tooltip_text, m_default_tooltip_color, + m_default_tooltip_bgcolor); } } } @@ -2672,40 +2644,20 @@ void GUIFormSpecMenu::drawMenu() } } + // Find and update the current tooltip if (id != -1 && delta >= m_tooltip_show_delay) { - for(std::vector::iterator iter = m_fields.begin(); + for (std::vector::iterator iter = m_fields.begin(); iter != m_fields.end(); ++iter) { - if (iter->fid == id && m_tooltips[iter->fname].tooltip != L"") { - if (m_old_tooltip != m_tooltips[iter->fname].tooltip) { - m_tooltip_element->setBackgroundColor(m_tooltips[iter->fname].bgcolor); - m_tooltip_element->setOverrideColor(m_tooltips[iter->fname].color); - m_old_tooltip = m_tooltips[iter->fname].tooltip; - setStaticText(m_tooltip_element, m_tooltips[iter->fname].tooltip.c_str()); - std::vector tt_rows = str_split(m_tooltips[iter->fname].tooltip, L'\n'); - s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; - s32 tooltip_height = m_tooltip_element->getTextHeight() * tt_rows.size() + 5; - int tooltip_offset_x = m_btn_height; - int tooltip_offset_y = m_btn_height; -#ifdef __ANDROID__ - tooltip_offset_x *= 3; - tooltip_offset_y = 0; - if (m_pointer.X > (s32)screenSize.X / 2) - tooltip_offset_x = (tooltip_offset_x + tooltip_width) * -1; -#endif - s32 tooltip_x = m_pointer.X + tooltip_offset_x; - s32 tooltip_y = m_pointer.Y + tooltip_offset_y; - if (tooltip_x + tooltip_width > (s32)screenSize.X) - tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; - if (tooltip_y + tooltip_height > (s32)screenSize.Y) - tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height; - m_tooltip_element->setRelativePosition(core::rect( - core::position2d(tooltip_x, tooltip_y), - core::dimension2d(tooltip_width, tooltip_height))); - } - m_tooltip_element->setVisible(true); - this->bringToFront(m_tooltip_element); - break; - } + + if (iter->fid != id) + continue; + + const std::wstring &text = m_tooltips[iter->fname].tooltip; + if (!text.empty()) + showTooltip(text, m_tooltips[iter->fname].color, + m_tooltips[iter->fname].bgcolor); + + break; } } } @@ -2720,6 +2672,53 @@ void GUIFormSpecMenu::drawMenu() skin->setFont(old_font); } + +void GUIFormSpecMenu::showTooltip(const std::wstring &text, + const irr::video::SColor &color, const irr::video::SColor &bgcolor) +{ + m_tooltip_element->setOverrideColor(color); + m_tooltip_element->setBackgroundColor(bgcolor); + m_old_tooltip = text; + setStaticText(m_tooltip_element, text.c_str()); + + // Tooltip size and offset + s32 tooltip_width = m_tooltip_element->getTextWidth() + m_btn_height; +#if (IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 8 && IRRLICHT_VERSION_REVISION < 2) || USE_FREETYPE == 1 + std::vector text_rows = str_split(text, L'\n'); + s32 tooltip_height = m_tooltip_element->getTextHeight() * text_rows.size() + 5; +#else + s32 tooltip_height = m_tooltip_element->getTextHeight() + 5; +#endif + v2u32 screenSize = Environment->getVideoDriver()->getScreenSize(); + int tooltip_offset_x = m_btn_height; + int tooltip_offset_y = m_btn_height; +#ifdef __ANDROID__ + tooltip_offset_x *= 3; + tooltip_offset_y = 0; + if (m_pointer.X > (s32)screenSize.X / 2) + tooltip_offset_x = -(tooltip_offset_x + tooltip_width); +#endif + + // Calculate and set the tooltip position + s32 tooltip_x = m_pointer.X + tooltip_offset_x; + s32 tooltip_y = m_pointer.Y + tooltip_offset_y; + if (tooltip_x + tooltip_width > (s32)screenSize.X) + tooltip_x = (s32)screenSize.X - tooltip_width - m_btn_height; + if (tooltip_y + tooltip_height > (s32)screenSize.Y) + tooltip_y = (s32)screenSize.Y - tooltip_height - m_btn_height; + + m_tooltip_element->setRelativePosition( + core::rect( + core::position2d(tooltip_x, tooltip_y), + core::dimension2d(tooltip_width, tooltip_height) + ) + ); + + // Display the tooltip + m_tooltip_element->setVisible(true); + bringToFront(m_tooltip_element); +} + void GUIFormSpecMenu::updateSelectedItem() { // If the selected stack has become empty for some reason, deselect it. diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 557a1cc9f..9eaf60ac6 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -517,6 +517,9 @@ private: void tryClose(); + void showTooltip(const std::wstring &text, const irr::video::SColor &color, + const irr::video::SColor &bgcolor); + /** * check if event is part of a double click * @param event event to evaluate -- cgit v1.2.3