diff --git a/.vscode/settings.json b/.vscode/settings.json index aa2ab46b3..ef68ef2a5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -44,7 +44,7 @@ }, "Lua.diagnostics.disable": [ "lowercase-global", - "undefined-field" + "deprecated" ], "files.associations": { "stdbool.h": "c", diff --git a/CHANGELOG.md b/CHANGELOG.md index 10c16ab52..cfb454292 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [v4.1.0-alpha+1195](https://github.com/Ismoh/NoitaMP/tree/v4.1.0-alpha+1195) (05.03.2023) + +[Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.1.0-alpha+1184...v4.1.0-alpha+1195) + +## [v4.1.0-alpha+1184](https://github.com/Ismoh/NoitaMP/tree/v4.1.0-alpha+1184) (05.03.2023) + +[Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.0.1-alpha+792...v4.1.0-alpha+1184) + +**Implemented enhancements:** + +- Developer want to sync children and components [\#107](https://github.com/Ismoh/NoitaMP/issues/107) [[enhancement](https://github.com/Ismoh/NoitaMP/labels/enhancement)] + +**Closed issues:** + +- Update CHANGELOG.md [\#112](https://github.com/Ismoh/NoitaMP/issues/112) [[documentation](https://github.com/Ismoh/NoitaMP/labels/documentation)] [[github_actions](https://github.com/Ismoh/NoitaMP/labels/github_actions)] + ## [v4.0.1-alpha+792](https://github.com/Ismoh/NoitaMP/tree/v4.0.1-alpha+792) (17.02.2023) [Full Changelog](https://github.com/Ismoh/NoitaMP/compare/v4.0.0-alpha+1302...v4.0.1-alpha+792) diff --git a/mods/noita-mp/.version b/mods/noita-mp/.version index ee77ebac6..6f6bee8b7 100644 --- a/mods/noita-mp/.version +++ b/mods/noita-mp/.version @@ -1 +1 @@ -{"version":"v4.0.1-alpha+792"} +{"version":"v4.0.1-alpha+1195"} diff --git a/mods/noita-mp/config.lua b/mods/noita-mp/config.lua index 003259143..0869e597d 100644 --- a/mods/noita-mp/config.lua +++ b/mods/noita-mp/config.lua @@ -48,13 +48,13 @@ local NoitaApiModSettingGet = ModSettingGet local NoitaApiModSettingSetNextValue = ModSettingSetNextValue local NoitaApiModSettingGetNextValue = ModSettingGetNextValue -if not util then +if not Utils then if require then - util = require("util") + Utils = require("Utils") else -- when NoitaComponents with their own restricted LuaContext load this file, -- util isn't available! - util = dofile_once("mods/noita-mp/files/scripts/util/util.lua") + Utils = dofile_once("mods/noita-mp/files/scripts/util/Utils.lua") if not MinaUtils and not require then MinaUtils = dofile_once("mods/noita-mp/files/scripts/util/MinaUtils.lua") end @@ -74,7 +74,7 @@ end ModSettingGet = function(id) if id == "noita-mp.name" then local name = MinaUtils.getLocalMinaName() - if not util.IsEmpty(name) then + if not Utils.IsEmpty(name) then return name else name = NoitaApiModSettingGet(id) @@ -84,7 +84,7 @@ ModSettingGet = function(id) end if id == "noita-mp.guid" then local guid = MinaUtils.getLocalMinaGuid() - if not util.IsEmpty(guid) then + if not Utils.IsEmpty(guid) then return guid else guid = NoitaApiModSettingGet(id) @@ -108,13 +108,13 @@ end ModSettingGetNextValue = function(id) if id == "noita-mp.name" and name then local name = MinaUtils.getLocalMinaName() - if not util.IsEmpty(name) then + if not Utils.IsEmpty(name) then return name end end if id == "noita-mp.guid" and guid then local guid = MinaUtils.getLocalMinaGuid() - if not util.IsEmpty(guid) then + if not Utils.IsEmpty(guid) then return guid end end diff --git a/mods/noita-mp/files/scripts/NoitaMpSettings.lua b/mods/noita-mp/files/scripts/NoitaMpSettings.lua index 2d81139f3..df9765657 100644 --- a/mods/noita-mp/files/scripts/NoitaMpSettings.lua +++ b/mods/noita-mp/files/scripts/NoitaMpSettings.lua @@ -10,11 +10,11 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local fu = require("file_util") +local fu = require("FileUtils") local lfs = require("lfs") local winapi = require("winapi") local json = require("json") -local util = require("util") +local Utils = require("Utils") ------------------------------------------------------------------------------------------------------------------------ --- NoitaMpSettings @@ -23,9 +23,9 @@ NoitaMpSettings = {} function NoitaMpSettings.clearAndCreateSettings() local cpc = CustomProfiler.start("NoitaMpSettings.clearAndCreateSettings") - local settingsDir = fu.getAbsolutePathOfNoitaMpSettingsDirectory() - if fu.exists(settingsDir) then - fu.removeContentOfDirectory(settingsDir) + local settingsDir = fu.GetAbsolutePathOfNoitaMpSettingsDirectory() + if fu.Exists(settingsDir) then + fu.RemoveContentOfDirectory(settingsDir) Logger.info(Logger.channels.initialize, ("Removed old settings in '%s'!"):format(settingsDir)) else lfs.mkdir(settingsDir) @@ -36,11 +36,11 @@ end function NoitaMpSettings.writeSettings(key, value) local cpc = CustomProfiler.start("NoitaMpSettings.writeSettings") - if util.IsEmpty(key) or type(key) ~= "string" then + if Utils.IsEmpty(key) or type(key) ~= "string" then error(("'key' must not be nil or is not type of string!"):format(key), 2) end - if util.IsEmpty(value) or type(value) ~= "string" then + if Utils.IsEmpty(value) or type(value) ~= "string" then error(("'value' must not be nil or is not type of string!"):format(value), 2) end @@ -51,9 +51,9 @@ function NoitaMpSettings.writeSettings(key, value) who = whoAmI() end local settingsFile = ("%s%s%s%s.json") - :format(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, who) + :format(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, who) - if not fu.exists(settingsFile) then + if not fu.Exists(settingsFile) then fu.WriteFile(settingsFile, "{}") end @@ -75,16 +75,16 @@ function NoitaMpSettings.getSetting(key) local pid = winapi.get_current_pid() local settingsFile = ("%s%s%s%s.json") - :format(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, whoAmI()) + :format(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), pathSeparator, pid, whoAmI()) - if not fu.exists(settingsFile) then + if not fu.Exists(settingsFile) then fu.WriteFile(settingsFile, "{}") end local contentString = fu.ReadFile(settingsFile) local contentJson = json.decode(contentString) - if util.IsEmpty(contentJson[key]) then + if Utils.IsEmpty(contentJson[key]) then error(("Unable to find '%s' in NoitaMpSettings: %s"):format(key, contentString), 2) end local value = contentJson[key] diff --git a/mods/noita-mp/files/scripts/Ui.lua b/mods/noita-mp/files/scripts/Ui.lua index 86608c5d9..968c699f8 100644 --- a/mods/noita-mp/files/scripts/Ui.lua +++ b/mods/noita-mp/files/scripts/Ui.lua @@ -6,15 +6,16 @@ ---------------------------------------- -- 'Imports' ---------------------------------------- -local renderEzgui = dofile_once("mods/noita-mp/lua_modules/share/lua/5.1/ezgui/EZGUI.lua").init("mods/noita-mp/lua_modules/share/lua/5.1/ezgui") -local fu = require("file_util") +local renderEzgui = dofile_once("mods/noita-mp/lua_modules/share/lua/5.1/ezgui/EZGUI.lua").init( + "mods/noita-mp/lua_modules/share/lua/5.1/ezgui") +local fu = require("FileUtils") ---------------------------------------------------------------------------------------------------- --- Ui --- @see PlayerList.xml --- @see FoldingMenu.xml ---------------------------------------------------------------------------------------------------- -Ui = {} +Ui = {} ---------------------------------------- -- Global private variables: @@ -50,7 +51,7 @@ end --- Ui constructor ---------------------------------------------------------------------------------------------------- function Ui.new() - local self = {} + local self = {} ------------------------------------ -- Private variables: @@ -87,31 +88,31 @@ function Ui.new() cellWidth = 50, }, methods = { - toggleAddress = function() + toggleAddress = function() showAddress = not showAddress end, - copyAddress = function() - util.copyToClipboard(("%s:%s"):format(_G.Server:getAddress(), _G.Server:getPort())) + copyAddress = function() + Utils.copyToClipboard(("%s:%s"):format(_G.Server:getAddress(), _G.Server:getPort())) end, - kick = function(data, element, arg1) + kick = function(data, element, arg1) _G.Server.kick(arg1) end, - ban = function(data, element, arg1) + ban = function(data, element, arg1) _G.Server.ban(arg1) end, - start = function() + start = function() _G.Server.start(nil, nil) end, - stop = function() + stop = function() _G.Server.stop() end, - connect = function() + connect = function() _G.Client.connect() end, - disconnect = function() + disconnect = function() _G.Client.disconnect() end, - toggleDebug = function() + toggleDebug = function() debug = not debug end, reportCustomProfiler = function() @@ -150,12 +151,12 @@ function Ui.new() local text = "" if foldingOpen then self.ezguiFoldingData.data.text = ("[- NoitaMP] %s eCache:%s pCache:%s nCache:%s %s") - :format(fu.getVersionByFile(), EntityCache.size(), CustomProfiler.getSize(), - NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) + :format(fu.GetVersionByFile(), EntityCache.size(), CustomProfiler.getSize(), + NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) else self.ezguiFoldingData.data.text = ("[+ NoitaMP] eCache:%s pCache:%s nCache:%s %s") - :format(EntityCache.size(), CustomProfiler.getSize(), - NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) + :format(EntityCache.size(), CustomProfiler.getSize(), + NetworkUtils.getClientOrServer().getAckCacheSize(), GameGetFrameNum()) end renderEzgui(0, height - 10, "mods/noita-mp/files/data/ezgui/FoldingMenu.xml", self.ezguiFoldingData) @@ -181,9 +182,6 @@ function Ui.new() }) table.insertAllButNotDuplicates(player, _G.Server.clients) for i = 2, #player do - --player[i].name = string.ExtendOrCutStringToLength(player[i].name, 12, ".", true) - --player[i].health = { current = i, max = 2 } - --player[i].transform = { x = 123, y = 12334 } player[i].rtt = player[i]:getRoundTripTime() end else @@ -271,7 +269,7 @@ function Ui.new() if clicked then missingModGuiDismissed = true Client:send(NetworkUtils.events.needModContent.name, - { NetworkUtils.getNextNetworkMessageId(), Client.missingMods }) + { NetworkUtils.getNextNetworkMessageId(), Client.missingMods }) end if hovered then missingModGuiButton1Hovered = true @@ -318,7 +316,6 @@ function Ui.new() GuiZSetForNextWidget(gui, 110) GuiImageNinePiece(gui, npID, 73, 73, w + 3, y - 71) end - end ------------------------------------ @@ -328,7 +325,6 @@ function Ui.new() drawFolding() drawMenu() drawModConflictWarning() - if EntityCache.size() >= EntityUtils.maxPoolSize then gui = gui or GuiCreate() GuiStartFrame(gui) diff --git a/mods/noita-mp/files/scripts/extensions/ffi_extensions.lua b/mods/noita-mp/files/scripts/extensions/ffiExtensions.lua similarity index 66% rename from mods/noita-mp/files/scripts/extensions/ffi_extensions.lua rename to mods/noita-mp/files/scripts/extensions/ffiExtensions.lua index 85534ed9f..a239d8112 100644 --- a/mods/noita-mp/files/scripts/extensions/ffi_extensions.lua +++ b/mods/noita-mp/files/scripts/extensions/ffiExtensions.lua @@ -6,9 +6,9 @@ end local ffi = require("ffi") -local C = ffi.C +local C = ffi.C -ffi.cdef[[ +ffi.cdef [[ typedef bool BOOL; typedef uint16_t WORD; typedef uint32_t DWORD; @@ -95,37 +95,37 @@ BOOL ReadFile( DWORD GetLastError(); ]] -local EXIT_FAILURE = 1 +local EXIT_FAILURE = 1 local STARTF_USESHOWWINDOW = 1 local STARTF_USESTDHANDLES = 0x100 -local SW_HIDE = 0 -local CREATE_NO_WINDOW = 0x8000000 -local INFINITE = -1 -local HANDLE_FLAG_INHERIT = 1 -local STD_INPUT_HANDLE = -10 -local STD_ERROR_HANDLE = -12 -local ERROR_BROKEN_PIPE = 109 +local SW_HIDE = 0 +local CREATE_NO_WINDOW = 0x8000000 +local INFINITE = -1 +local HANDLE_FLAG_INHERIT = 1 +local STD_INPUT_HANDLE = -10 +local STD_ERROR_HANDLE = -12 +local ERROR_BROKEN_PIPE = 109 function os.execute(commandLine) - local si = ffi.new("STARTUPINFOA") - si.cb = ffi.sizeof(si) - si.dwFlags = STARTF_USESHOWWINDOW + local si = ffi.new("STARTUPINFOA") + si.cb = ffi.sizeof(si) + si.dwFlags = STARTF_USESHOWWINDOW si.wShowWindow = SW_HIDE - local pi = ffi.new("PROCESS_INFORMATION") + local pi = ffi.new("PROCESS_INFORMATION") if not C.CreateProcessA(nil, "cmd /C " .. commandLine, nil, nil, 0, CREATE_NO_WINDOW, nil, nil, si, pi) then return EXIT_FAILURE end C.WaitForSingleObject(pi.hProcess, INFINITE) local exitcode = ffi.new("DWORD[1]") - local ok = C.GetExitCodeProcess(pi.hProcess, exitcode) + local ok = C.GetExitCodeProcess(pi.hProcess, exitcode) C.CloseHandle(pi.hProcess) C.CloseHandle(pi.hThread) return ok and exitcode[0] or EXIT_FAILURE end -local pfile = {} -local pfile_mt = {__index = pfile} +local pfile = {} +local pfile_mt = { __index = pfile } local function checkclosed(pfile) if pfile.pi == nil then @@ -152,33 +152,39 @@ function pfile:read(n) end if type(n) == "number" then - if not fetch(function() return #self.buffer < n end) then + if not fetch(function() + return #self.buffer < n + end) then return nil end - local out = self.buffer:sub(1, n) + local out = self.buffer:sub(1, n) self.buffer = self.buffer:sub(n + 1) if out == "" then out = nil end return out elseif n == "*a" then - if not fetch(function() return true end) then + if not fetch(function() + return true + end) then return nil end - local out = self.buffer + local out = self.buffer self.buffer = "" return out elseif n == "*l" then - if not fetch(function() return not self.buffer:find("\n", nil, true) end) then + if not fetch(function() + return not self.buffer:find("\n", nil, true) + end) then return nil end local out local npos = self.buffer:find("\n", nil, true) if npos then - out = self.buffer:sub(1, npos-1) - self.buffer = self.buffer:sub(npos+1) + out = self.buffer:sub(1, npos - 1) + self.buffer = self.buffer:sub(npos + 1) else - out = self.buffer + out = self.buffer self.buffer = "" if out == "" then out = nil @@ -192,7 +198,9 @@ end function pfile:lines() checkclosed(self) - return function() return self:read("*l") end + return function() + return self:read("*l") + end end function pfile:close() @@ -201,27 +209,28 @@ function pfile:close() C.CloseHandle(self.pipe_outRd[0]) C.WaitForSingleObject(pi.hProcess, INFINITE) local res = C.CloseHandle(pi.hProcess) and C.CloseHandle(pi.hThread) - self.pi = nil + self.pi = nil return res end function io.popen(commandLine) - local sa = ffi.new("SECURITY_ATTRIBUTES", ffi.sizeof("SECURITY_ATTRIBUTES"), nil, true) + local sa = ffi.new("SECURITY_ATTRIBUTES", ffi.sizeof("SECURITY_ATTRIBUTES"), nil, true) - local pipe_outRd, pipe_outWr=ffi.new("HANDLE[1]"), ffi.new("HANDLE[1]") - if not C.CreatePipe(pipe_outRd, pipe_outWr, sa, 0) or not C.SetHandleInformation(pipe_outRd[0], HANDLE_FLAG_INHERIT, 0) then + local pipe_outRd, pipe_outWr = ffi.new("HANDLE[1]"), ffi.new("HANDLE[1]") + if not C.CreatePipe(pipe_outRd, pipe_outWr, sa, 0) or not C.SetHandleInformation(pipe_outRd[0], HANDLE_FLAG_INHERIT, + 0) then return end - local si = ffi.new("STARTUPINFOA") - si.cb = ffi.sizeof(si) - si.dwFlags = STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES + local si = ffi.new("STARTUPINFOA") + si.cb = ffi.sizeof(si) + si.dwFlags = STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES si.wShowWindow = SW_HIDE - si.hStdInput = C.GetStdHandle(STD_INPUT_HANDLE) - si.hStdOutput = pipe_outWr[0] - si.hStdError = C.GetStdHandle(STD_ERROR_HANDLE) + si.hStdInput = C.GetStdHandle(STD_INPUT_HANDLE) + si.hStdOutput = pipe_outWr[0] + si.hStdError = C.GetStdHandle(STD_ERROR_HANDLE) - local pi = ffi.new("PROCESS_INFORMATION") + local pi = ffi.new("PROCESS_INFORMATION") if not C.CreateProcessA(nil, "cmd /C " .. commandLine, nil, nil, 1, CREATE_NO_WINDOW, nil, nil, si, pi) then return end @@ -229,11 +238,11 @@ function io.popen(commandLine) local size = 4096 return setmetatable({ - pi = pi, - pipe_outRd = pipe_outRd, - size = size, - byteBuf = ffi.new("char[?]", size), - bytesRead = ffi.new("DWORD[1]"), - buffer = "" - }, pfile_mt) + pi = pi, + pipe_outRd = pipe_outRd, + size = size, + byteBuf = ffi.new("char[?]", size), + bytesRead = ffi.new("DWORD[1]"), + buffer = "" + }, pfile_mt) end diff --git a/mods/noita-mp/files/scripts/extensions/string_extensions.lua b/mods/noita-mp/files/scripts/extensions/stringExtensions.lua similarity index 100% rename from mods/noita-mp/files/scripts/extensions/string_extensions.lua rename to mods/noita-mp/files/scripts/extensions/stringExtensions.lua diff --git a/mods/noita-mp/files/scripts/extensions/table_extensions.lua b/mods/noita-mp/files/scripts/extensions/tableExtensions.lua similarity index 99% rename from mods/noita-mp/files/scripts/extensions/table_extensions.lua rename to mods/noita-mp/files/scripts/extensions/tableExtensions.lua index d3d2b0f5f..eb3ee52b9 100644 --- a/mods/noita-mp/files/scripts/extensions/table_extensions.lua +++ b/mods/noita-mp/files/scripts/extensions/tableExtensions.lua @@ -210,8 +210,8 @@ function table.contentToString(tbl) if not tbl or type(tbl) ~= "table" then error("'tbl' must not be nil and type of table!", 2) end - if not util then - util = require("util") + if not Utils then + Utils = require("Utils") end --Logger.trace(Logger.channels.testing, ("tbl = %s"):format(util.pformat(tbl))) diff --git a/mods/noita-mp/files/scripts/init/init_.lua b/mods/noita-mp/files/scripts/init/init_.lua index cc6cf24fb..da885eb3a 100644 --- a/mods/noita-mp/files/scripts/init/init_.lua +++ b/mods/noita-mp/files/scripts/init/init_.lua @@ -1,7 +1,6 @@ -- Init lua scripts to set necessary defaults, like lua paths, logger init and extensions print("Initialise paths, globals and extensions..") local varargs = { ... } - if varargs and #varargs > 0 then if require then print("ERROR: Do not add any arguments when running this script in-game!") @@ -13,17 +12,13 @@ else print("no 'varargs' set.") end -dofile("mods/noita-mp/files/scripts/extensions/table_extensions.lua") -dofile("mods/noita-mp/files/scripts/extensions/string_extensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/tableExtensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/stringExtensions.lua") dofile("mods/noita-mp/files/scripts/extensions/mathExtensions.lua") -dofile("mods/noita-mp/files/scripts/extensions/ffi_extensions.lua") +dofile("mods/noita-mp/files/scripts/extensions/ffiExtensions.lua") dofile("mods/noita-mp/files/scripts/extensions/globalExtensions.lua") - dofile("mods/noita-mp/files/scripts/init/init_package_loading.lua") dofile("mods/noita-mp/files/scripts/init/init_logger.lua") - --- We simply want to load all dependencies, when inGame and in init.lua-Context, --- and when in NoitaComponents or in unit testing!Ø require("MinaUtils") require("luaExtensions") require("NetworkCacheUtils") @@ -47,4 +42,4 @@ _G.whoAmI = function() return Client.iAm end return "UNKNOWN" -end \ No newline at end of file +end diff --git a/mods/noita-mp/files/scripts/init/init_logger.lua b/mods/noita-mp/files/scripts/init/init_logger.lua index 5d9b59463..95ed342e1 100644 --- a/mods/noita-mp/files/scripts/init/init_logger.lua +++ b/mods/noita-mp/files/scripts/init/init_logger.lua @@ -6,5 +6,5 @@ if not _G.Logger then end Logger.info(Logger.channels.initialize, "_G.Logger initialised!") else - error("ERROR: Unable to init Logger! _G.Logger is nil.", 2) + Logger.info(Logger.channels.initialize, "_G.Logger was already initialised!") end diff --git a/mods/noita-mp/files/scripts/init/init_package_loading.lua b/mods/noita-mp/files/scripts/init/init_package_loading.lua index 48c5a921b..0c2b9e5e6 100644 --- a/mods/noita-mp/files/scripts/init/init_package_loading.lua +++ b/mods/noita-mp/files/scripts/init/init_package_loading.lua @@ -7,7 +7,7 @@ function getNoitaMpRootDirectory() -- Check if we are inside of noita-mp directory. Don't forget to escape the dash! local startsAtI, endsAtI = string.find(currentDirectory, - "noita%-mp") -- https://stackoverflow.com/a/20223010/3493998 + "noita%-mp") -- https://stackoverflow.com/a/20223010/3493998 local noitaMpRootDirectory = nil if not startsAtI then error("The current directory is not inside the noita-mp directory. Please run it again somewhere inside the noita-mp directory.") @@ -35,15 +35,15 @@ package.path = package.path .. "mods\\noita-mp\\files\\scripts\\util\\?.lua;" print("package.path = " .. package.path) package.cpath = package.cpath .. ";" .. - -- [[ LuaRocks libraries ]]-- - noitaMpRootDirectory .. "\\lua_modules\\lib\\lua\\5.1\\?.dll;" .. - "mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\?.dll;" + -- [[ LuaRocks libraries ]]-- + noitaMpRootDirectory .. "\\lua_modules\\lib\\lua\\5.1\\?.dll;" .. + "mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\?.dll;" print("package.cpath = " .. package.cpath) -local fu = require("file_util") +local fu = require("FileUtils") --[[ NoitaMP additions ]] -- A list of paths to lua script modules -local paths = { +local paths = { -- [[ LuaRocks modules, running outside of noita.exe ]]-- noitaMpRootDirectory .. "/lua_modules/share/lua/5.1/{module}", noitaMpRootDirectory .. "/lua_modules/lib/lua/5.1/{module}", @@ -68,14 +68,14 @@ local paths = { } -- A list of paths to binary Lua modules -local module_paths = { +local module_paths = { "?.{extension}", "?/init.{extension}", "?/core.{extension}", } -- List of supported OS paired with binary file extension name -local extensions = { +local extensions = { Windows = "dll", Linux = "so", Mac = "dylib" @@ -83,34 +83,36 @@ local extensions = { -- os_name is a supplemental module for -- OS and CPU architecture detection -local os_name = require("os_name") +local os_name = require("os_name") --[[ NoitaMP additions ]] -package.path = default_package_path +package.path = default_package_path --[[ NoitaMP additions ]] -- A dot character represent current working directory local root_dir = "." -local current_platform, current_architecture = os_name.getOS() - -local cpaths, lpaths = {}, {} -local current_clib_extension = extensions[current_platform] --[[ NoitaMP additions ]] -_G.os_name = current_platform -_G.os_arch = current_architecture - --- https://stackoverflow.com/a/14425862/3493998 -_G.pathSeparator = tostring(package.config:sub(1, 1)) - -if _G.os_name == "Windows" then +_G.is_windows = true +_G.is_linux = false +_G.pathSeparator = tostring(package.config:sub(1, 1)) +local current_platform, current_architecture = os_name.getOS() +if current_platform == "Windows" then _G.is_windows = true -end -if _G.os_name == "Linux" then + _G.is_linux = false + _G.pathSeparator = "\\" +else + _G.is_windows = false _G.is_linux = true + _G.pathSeparator = "/" end +_G.os_name = current_platform +_G.os_arch = current_architecture + +local cpaths, lpaths = {}, {} +local current_clib_extension = extensions[current_platform] print("init_package_loading.lua | Detected OS " .. _G.os_name .. - "(" .. _G.os_arch .. ") with path separator '" .. _G.pathSeparator .. "'.") +"(" .. _G.os_arch .. ") with path separator '" .. _G.pathSeparator .. "'.") --[[ NoitaMP additions ]] if current_clib_extension then @@ -122,30 +124,30 @@ if current_clib_extension then -- make a substitution for each module file path. for _, raw_module_path in ipairs(module_paths) do local module_path = path:gsub( - "{(%w+)}", - { - module = raw_module_path - } + "{(%w+)}", + { + module = raw_module_path + } ) -- add path for binary module cpaths[#cpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = current_clib_extension - } + "{(%w+)}", + { + extension = current_clib_extension + } ) -- add paths for platform independent lua and luac modules lpaths[#lpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = "lua" - } + "{(%w+)}", + { + extension = "lua" + } ) lpaths[#lpaths + 1] = module_path:gsub( - "{(%w+)}", - { - extension = "luac" - } + "{(%w+)}", + { + extension = "luac" + } ) end end @@ -161,20 +163,22 @@ if current_clib_extension then if destination_path then print("destination_path was set to export LPATH and CPATH!") - local lua_path_file = fu.RemoveTrailingPathSeparator(destination_path) .. _G.pathSeparator .. "lua_path.txt" + local lua_path_file = fu.RemoveTrailingPathSeparator(destination_path) .. + _G.pathSeparator .. "lua_path.txt" local lua_path_file_content = ";" .. package.path - local lua_cpath_file = fu.RemoveTrailingPathSeparator(destination_path) .. _G.pathSeparator .. "lua_cpath.txt" + local lua_cpath_file = fu.RemoveTrailingPathSeparator(destination_path) .. + _G.pathSeparator .. "lua_cpath.txt" local lua_cpath_file_content = ";" .. package.cpath fu.WriteFile(lua_path_file, lua_path_file_content) print("init_package_loading.lua | File (" .. lua_path_file .. - ") created with content: " .. lua_path_file_content) + ") created with content: " .. lua_path_file_content) fu.WriteFile(lua_cpath_file, lua_cpath_file_content) print("init_package_loading.lua | File (" .. lua_cpath_file .. - ") created with content: " .. lua_cpath_file_content) + ") created with content: " .. lua_cpath_file_content) else print("destination_path was not set. Export LPATH and CPATH will be skipped!") end diff --git a/mods/noita-mp/files/scripts/net/Client.lua b/mods/noita-mp/files/scripts/net/Client.lua index e208c7e12..c493f03da 100644 --- a/mods/noita-mp/files/scripts/net/Client.lua +++ b/mods/noita-mp/files/scripts/net/Client.lua @@ -7,10 +7,10 @@ --- 'Imports' ---------------------------------------- local sock = require("sock") -local util = require("util") +local Utils = require("Utils") local zstandard = require("zstd") local messagePack = require("MessagePack") -local fu = require("file_util") +local fu = require("FileUtils") ---------------------------------------------------------------------------------------------------- --- Client @@ -147,7 +147,7 @@ function Client.new(sockClient) end local data = { networkMessageId, event, NetworkUtils.events.acknowledgement.ack, os.clock() } self:send(NetworkUtils.events.acknowledgement.name, data) - Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(Utils.pformat(data))) CustomProfiler.stop("Client.sendAck", cpc2) end @@ -156,26 +156,26 @@ function Client.new(sockClient) ------------------------------------------------------------------------------------------------ local function onAcknowledgement(data) local cpc3 = CustomProfiler.start("Client.onAcknowledgement") - Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onAcknowledgement data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end if not data.networkMessageId then error(("Unable to get acknowledgement with networkMessageId = %s, data = %s, peer = %s") - :format(networkMessageId, util.pformat(data), util.pformat(self)), 2) + :format(networkMessageId, Utils.pformat(data), Utils.pformat(self)), 2) end - if util.IsEmpty(data.event) then + if Utils.IsEmpty(data.event) then error(("onAcknowledgement data.event is empty: %s"):format(data.event), 2) end - if util.IsEmpty(data.status) then + if Utils.IsEmpty(data.status) then error(("onAcknowledgement data.status is empty: %s"):format(data.status), 2) end - if util.IsEmpty(data.ackedAt) then + if Utils.IsEmpty(data.ackedAt) then error(("onAcknowledgement data.ackedAt is empty: %s"):format(data.ackedAt), 2) end @@ -201,9 +201,9 @@ function Client.new(sockClient) --- @param data number not in use atm local function onConnect(data) local cpc4 = CustomProfiler.start("Client.onConnect") - Logger.debug(Logger.channels.network, "Connected to server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Connected to server!", Utils.pformat(data)) - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onConnect data is empty: %s"):format(data), 3) end @@ -213,7 +213,7 @@ function Client.new(sockClient) local nuid = localPlayerInfo.nuid -- Could be nil. Timing issue. Will be set after this. self:send(NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) self:send(NetworkUtils.events.needModList.name, { NetworkUtils.getNextNetworkMessageId(), nil, nil}) @@ -229,17 +229,17 @@ function Client.new(sockClient) --- @param data table data = { "name", "guid" } @see NetworkUtils.events.connect2.schema local function onConnect2(data) local cpc5 = CustomProfiler.start("Client.onConnect2") - Logger.debug(Logger.channels.network, "Another client connected.", util.pformat(data)) + Logger.debug(Logger.channels.network, "Another client connected.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onConnect2 data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onConnect2 data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onConnect2 data.guid is empty: %s"):format(data.guid), 3) end @@ -256,9 +256,9 @@ function Client.new(sockClient) --- @param data number data(.code) = 0 local function onDisconnect(data) local cpc6 = CustomProfiler.start("Client.onDisconnect") - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onDisconnect data is empty: %s"):format(data), 3) end @@ -285,17 +285,17 @@ function Client.new(sockClient) --- @param data table data { "name", "guid" } @see NetworkUtils.events.disconnect2.schema local function onDisconnect2(data) local cpc7 = CustomProfiler.start("Client.onDisconnect2") - Logger.debug(Logger.channels.network, "onDisconnect2: Another client disconnected.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onDisconnect2: Another client disconnected.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onDisconnect2 data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onDisconnect2 data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onDisconnect2 data.guid is empty: %s"):format(data.guid), 3) end @@ -314,25 +314,25 @@ function Client.new(sockClient) --- @param data table data { networkMessageId, name, guid } local function onPlayerInfo(data) local cpc8 = CustomProfiler.start("Client.onPlayerInfo") - Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onPlayerInfo data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onPlayerInfo data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onPlayerInfo data.guid is empty: %s"):format(data.guid), 3) end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onPlayerInfo data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.version) then + if Utils.IsEmpty(data.version) then error(("onPlayerInfo data.version is empty: %s"):format(data.version), 3) end @@ -341,9 +341,9 @@ function Client.new(sockClient) ("onPlayerInfo: Clients GUID %s isn't unique! Server will fix this!"):format(self.guid)) end - if fu.getVersionByFile() ~= tostring(data.version) then + if fu.GetVersionByFile() ~= tostring(data.version) then error(("Version mismatch: NoitaMP version of Server: %s and your version: %s") - :format(data.version, fu.getVersionByFile()), 3) + :format(data.version, fu.GetVersionByFile()), 3) self:disconnect() end @@ -362,23 +362,23 @@ function Client.new(sockClient) --- @param data table data { "networkMessageId", "oldGuid", "newGuid" } local function onNewGuid(data) local cpc9 = CustomProfiler.start("Client.onNewGuid") - Logger.debug(Logger.channels.network, ("onNewGuid: New GUID from server received."):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("onNewGuid: New GUID from server received."):format(Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewGuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end - if util.IsEmpty(data.oldGuid) then + if Utils.IsEmpty(data.oldGuid) then error(("onNewGuid data.oldGuid is empty: %s"):format(data.oldGuid), 2) end - if util.IsEmpty(data.newGuid) then + if Utils.IsEmpty(data.newGuid) then error(("onNewGuid data.newGuid is empty: %s"):format(data.newGuid), 2) end if data.oldGuid == self.guid then local entityId = MinaUtils.getLocalMinaInformation().entityId - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) self.guid = data.newGuid local cpc27 = CustomProfiler.start("ModSettingSet") @@ -407,13 +407,13 @@ function Client.new(sockClient) --- @param data table data { networkMessageId, seed } local function onSeed(data) local cpc10 = CustomProfiler.start("Client.onSeed") - Logger.debug(Logger.channels.network, "onSeed: Seed from server received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onSeed: Seed from server received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onSeed data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.seed) then + if Utils.IsEmpty(data.seed) then error(("onSeed data.seed is empty: %s"):format(data.seed), 3) end @@ -424,7 +424,7 @@ function Client.new(sockClient) local localSeed = tonumber(StatsGetValue("world_seed")) if localSeed ~= serversSeed then - --util.reloadMap(serversSeed) TODO enable again, when custom map/biome isn't used anymore + --Utils.reloadMap(serversSeed) TODO enable again, when custom map/biome isn't used anymore end local localPlayerInfo = MinaUtils.getLocalMinaInformation() @@ -434,7 +434,7 @@ function Client.new(sockClient) local entityId = localPlayerInfo.entityId self:send(NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) if not NetworkVscUtils.hasNetworkLuaComponents(entityId) then NetworkVscUtils.addOrUpdateAllVscs(entityId, name, guid, nil) @@ -456,49 +456,49 @@ function Client.new(sockClient) --- velocity { x, y }, filename } local function onNewNuid(data) local cpc11 = CustomProfiler.start("Client.onNewNuid") - Logger.debug(Logger.channels.network, ("Received a new nuid! data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Received a new nuid! data = %s"):format(Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - if util.IsEmpty(data.localEntityId) then + if Utils.IsEmpty(data.localEntityId) then error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) end - if util.IsEmpty(data.newNuid) then + if Utils.IsEmpty(data.newNuid) then error(("onNewNuid data.newNuid is empty: %s"):format(data.newNuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.filename) then + if Utils.IsEmpty(data.filename) then error(("onNewNuid data.filename is empty: %s"):format(data.filename), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end - if util.IsEmpty(data.isPolymorphed) then + if Utils.IsEmpty(data.isPolymorphed) then error(("onNewNuid data.isPolymorphed is empty: %s"):format(data.isPolymorphed), 3) end @@ -529,41 +529,41 @@ function Client.new(sockClient) local function onEntityData(data) local cpc12 = CustomProfiler.start("Client.onEntityData") Logger.debug(Logger.channels.network, ("Received entityData for nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - --if util.IsEmpty(data.localEntityId) then + --if Utils.IsEmpty(data.localEntityId) then -- error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) --end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onNewNuid data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end @@ -580,7 +580,7 @@ function Client.new(sockClient) NoitaComponentUtils.setEntityData(localEntityId, x, y, rotation, velocity, health) else Logger.warn(Logger.channels.network, ("Received entityData for self.nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) end -- sendAck(data.networkMessageId) do not send ACK for position data, network will explode @@ -592,7 +592,7 @@ function Client.new(sockClient) local deadNuids = data.deadNuids or data or {} for i = 1, #deadNuids do local deadNuid = deadNuids[i] - if util.IsEmpty(deadNuid) or deadNuid == "nil" then + if Utils.IsEmpty(deadNuid) or deadNuid == "nil" then error(("onDeadNuids deadNuid is empty: %s"):format(deadNuid), 2) else EntityUtils.destroyByNuid(self, deadNuid) @@ -638,8 +638,6 @@ function Client.new(sockClient) end local function onNeedModContent(data) - ---@module "file_util" - local fu = dofile_once("mods/noita-mp/files/scripts/util/file_util.lua") local cpc = CustomProfiler.start("Client.onNeedModContent") for _, v in ipairs(data.items) do local modName = v.name @@ -669,7 +667,7 @@ function Client.new(sockClient) -- self:on( -- "entityAlive", -- function(data) - -- logger:debug(util.pformat(data)) + -- logger:debug(Utils.pformat(data)) -- em:DespawnEntity(data.owner, data.localEntityId, data.nuid, data.isAlive) -- end @@ -678,7 +676,7 @@ function Client.new(sockClient) -- self:on( -- "entityState", -- function(data) - -- logger:debug(util.pformat(data)) + -- logger:debug(Utils.pformat(data)) -- local nc = em:GetNetworkComponent(data.owner, data.localEntityId, data.nuid) -- if nc then @@ -895,7 +893,7 @@ function Client.new(sockClient) if NetworkUtils.alreadySent(self, event, data) then Logger.debug(Logger.channels.network, ("Network message for %s for data %s already was acknowledged.") - :format(event, util.pformat(data))) + :format(event, Utils.pformat(data))) CustomProfiler.stop("Client.send", cpc19) return false end @@ -936,7 +934,7 @@ function Client.new(sockClient) } if isTestLuaContext then - print(("Sending need nuid for entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Sending need nuid for entity %s with data %s"):format(entityId, Utils.pformat(data))) end self:send(NetworkUtils.events.needNuid.name, data) @@ -957,13 +955,13 @@ function Client.new(sockClient) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local data = { NetworkUtils.getNextNetworkMessageId(), { compOwnerName, compOwnerGuid }, compNuid, x, y, rotation, velocity, health } - if util.IsEmpty(compNuid) then + if Utils.IsEmpty(compNuid) then -- this can happen, when entity spawned on client and network is slow Logger.debug(Logger.channels.network, "Unable to send entity data, because nuid is empty.") self.sendNeedNuid(compOwnerName, compOwnerGuid, entityId) diff --git a/mods/noita-mp/files/scripts/net/Server.lua b/mods/noita-mp/files/scripts/net/Server.lua index 31129f9e6..7110fa43b 100644 --- a/mods/noita-mp/files/scripts/net/Server.lua +++ b/mods/noita-mp/files/scripts/net/Server.lua @@ -7,8 +7,8 @@ --- 'Imports' ---------------------------------------- local sock = require("sock") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") local zstandard = require("zstd") local messagePack = require("MessagePack") @@ -143,7 +143,7 @@ function Server.new(sockServer) end local data = { networkMessageId, event, NetworkUtils.events.acknowledgement.ack, os.clock() } self:sendToPeer(peer, NetworkUtils.events.acknowledgement.name, data) - Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(util.pformat(data))) + Logger.debug(Logger.channels.network, ("Sent ack with data = %s"):format(Utils.pformat(data))) CustomProfiler.stop("Server.sendAck", cpc02) end @@ -152,9 +152,9 @@ function Server.new(sockServer) ------------------------------------------------------------------------------------------------ local function onAcknowledgement(data, peer) local cpc03 = CustomProfiler.start("Server.onAcknowledgement") - Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onAcknowledgement: Acknowledgement received.", Utils.pformat(data)) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onAcknowledgement data.networkMessageId is empty: %s"):format(data.networkMessageId), 2) end @@ -163,15 +163,15 @@ function Server.new(sockServer) :format(networkMessageId, data, peer), 2) end - if util.IsEmpty(data.event) then + if Utils.IsEmpty(data.event) then error(("onAcknowledgement data.event is empty: %s"):format(data.event), 2) end - if util.IsEmpty(data.status) then + if Utils.IsEmpty(data.status) then error(("onAcknowledgement data.status is empty: %s"):format(data.status), 2) end - if util.IsEmpty(data.ackedAt) then + if Utils.IsEmpty(data.ackedAt) then error(("onAcknowledgement data.ackedAt is empty: %s"):format(data.ackedAt), 2) end @@ -199,13 +199,13 @@ function Server.new(sockServer) local function onConnect(data, peer) local cpc04 = CustomProfiler.start("Server.onConnect") Logger.debug(Logger.channels.network, ("Peer %s connected! data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onConnect data is empty: %s"):format(data), 3) end @@ -214,7 +214,7 @@ function Server.new(sockServer) local guid = localPlayerInfo.guid local entityId = localPlayerInfo.entityId local isPolymorphed = EntityUtils.isEntityPolymorphed(entityId) - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) if not nuid then nuid = NuidUtils.getNextNuid() @@ -228,7 +228,7 @@ function Server.new(sockServer) end self:send(peer, NetworkUtils.events.playerInfo.name, - { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.getVersionByFile(), nuid }) + { NetworkUtils.getNextNetworkMessageId(), name, guid, fu.GetVersionByFile(), nuid }) self:send(peer, NetworkUtils.events.seed.name, { NetworkUtils.getNextNetworkMessageId(), StatsGetValue("world_seed") }) @@ -251,17 +251,17 @@ function Server.new(sockServer) --- @param peer table local function onDisconnect(data, peer) local cpc05 = CustomProfiler.start("Server.onDisconnect") - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data) then + if Utils.IsEmpty(data) then error(("onDisconnect data is empty: %s"):format(data), 3) end - Logger.debug(Logger.channels.network, "Disconnected from server!", util.pformat(data)) + Logger.debug(Logger.channels.network, "Disconnected from server!", Utils.pformat(data)) -- Let the other clients know, that one client disconnected self:sendToAllBut(peer, NetworkUtils.events.disconnect2.name, { NetworkUtils.getNextNetworkMessageId(), peer.name, peer.guid, peer.nuid }) @@ -286,35 +286,35 @@ function Server.new(sockServer) --- @param data table data { networkMessageId, name, guid } local function onPlayerInfo(data, peer) local cpc06 = CustomProfiler.start("Server.onPlayerInfo") - Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", util.pformat(data)) + Logger.debug(Logger.channels.network, "onPlayerInfo: Player info received.", Utils.pformat(data)) - if util.IsEmpty(peer) then + if Utils.IsEmpty(peer) then error(("onConnect peer is empty: %s"):format(peer), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onPlayerInfo data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.name) then + if Utils.IsEmpty(data.name) then error(("onPlayerInfo data.name is empty: %s"):format(data.name), 3) end - if util.IsEmpty(data.guid) then + if Utils.IsEmpty(data.guid) then error(("onPlayerInfo data.guid is empty: %s"):format(data.guid), 3) end - --if util.IsEmpty(data.nuid) then + --if Utils.IsEmpty(data.nuid) then -- error(("onPlayerInfo data.nuid is empty: %s"):format(data.nuid), 3) --end - if util.IsEmpty(data.version) then + if Utils.IsEmpty(data.version) then error(("onPlayerInfo data.version is empty: %s"):format(data.version), 3) end - if fu.getVersionByFile() ~= tostring(data.version) then + if fu.GetVersionByFile() ~= tostring(data.version) then error(("Version mismatch: NoitaMP version of Client: %s and your version: %s") - :format(data.version, fu.getVersionByFile()), 3) + :format(data.version, fu.GetVersionByFile()), 3) peer:disconnect() end @@ -349,49 +349,49 @@ function Server.new(sockServer) local function onNeedNuid(data, peer) local cpc07 = CustomProfiler.start("Server.onNeedNuid") Logger.debug(Logger.channels.network, ("Peer %s needs a new nuid. data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then - error(("onNeedNuid peer is empty: %s"):format(util.pformat(peer)), 3) + if Utils.IsEmpty(peer) then + error(("onNeedNuid peer is empty: %s"):format(Utils.pformat(peer)), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - if util.IsEmpty(data.localEntityId) then + if Utils.IsEmpty(data.localEntityId) then error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.filename) then + if Utils.IsEmpty(data.filename) then error(("onNewNuid data.filename is empty: %s"):format(data.filename), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end - if util.IsEmpty(data.isPolymorphed) then + if Utils.IsEmpty(data.isPolymorphed) then error(("onNewNuid data.isPolymorphed is empty: %s"):format(data.isPolymorphed), 3) end @@ -420,18 +420,18 @@ function Server.new(sockServer) local function onLostNuid(data, peer) local cpc08 = CustomProfiler.start("Server.onLostNuid") Logger.debug(Logger.channels.network, ("Peer %s lost a nuid and ask for the entity to spawn. data = %s") - :format(util.pformat(peer), util.pformat(data))) + :format(Utils.pformat(peer), Utils.pformat(data))) - if util.IsEmpty(peer) then - error(("onLostNuid peer is empty: %s"):format(util.pformat(peer)), 3) + if Utils.IsEmpty(peer) then + error(("onLostNuid peer is empty: %s"):format(Utils.pformat(peer)), 3) end - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onLostNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.nuid) then - error(("onLostNuid data.nuid is empty: %s"):format(util.pformat(data.nuid)), 3) + if Utils.IsEmpty(data.nuid) then + error(("onLostNuid data.nuid is empty: %s"):format(Utils.pformat(data.nuid)), 3) end local nuid, entityId = GlobalsUtils.getNuidEntityPair(data.nuid) @@ -444,7 +444,7 @@ function Server.new(sockServer) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local isPolymorphed = EntityUtils.isEntityPolymorphed(entityId) @@ -459,41 +459,41 @@ function Server.new(sockServer) local function onEntityData(data, peer) local cpc09 = CustomProfiler.start("Server.onEntityData") Logger.debug(Logger.channels.network, ("Received entityData for nuid = %s! data = %s") - :format(data.nuid, util.pformat(data))) + :format(data.nuid, Utils.pformat(data))) - if util.IsEmpty(data.networkMessageId) then + if Utils.IsEmpty(data.networkMessageId) then error(("onNewNuid data.networkMessageId is empty: %s"):format(data.networkMessageId), 3) end - if util.IsEmpty(data.owner) then - error(("onNewNuid data.owner is empty: %s"):format(util.pformat(data.owner)), 3) + if Utils.IsEmpty(data.owner) then + error(("onNewNuid data.owner is empty: %s"):format(Utils.pformat(data.owner)), 3) end - --if util.IsEmpty(data.localEntityId) then + --if Utils.IsEmpty(data.localEntityId) then -- error(("onNewNuid data.localEntityId is empty: %s"):format(data.localEntityId), 3) --end - if util.IsEmpty(data.nuid) then + if Utils.IsEmpty(data.nuid) then error(("onNewNuid data.nuid is empty: %s"):format(data.nuid), 3) end - if util.IsEmpty(data.x) then + if Utils.IsEmpty(data.x) then error(("onNewNuid data.x is empty: %s"):format(data.x), 3) end - if util.IsEmpty(data.y) then + if Utils.IsEmpty(data.y) then error(("onNewNuid data.y is empty: %s"):format(data.y), 3) end - if util.IsEmpty(data.rotation) then + if Utils.IsEmpty(data.rotation) then error(("onNewNuid data.rotation is empty: %s"):format(data.rotation), 3) end - if util.IsEmpty(data.velocity) then - error(("onNewNuid data.velocity is empty: %s"):format(util.pformat(data.velocity)), 3) + if Utils.IsEmpty(data.velocity) then + error(("onNewNuid data.velocity is empty: %s"):format(Utils.pformat(data.velocity)), 3) end - if util.IsEmpty(data.health) then + if Utils.IsEmpty(data.health) then error(("onNewNuid data.health is empty: %s"):format(data.health), 3) end @@ -519,7 +519,7 @@ function Server.new(sockServer) local deadNuids = data.deadNuids or data or {} for i = 1, #deadNuids do local deadNuid = deadNuids[i] - if util.IsEmpty(deadNuid) or deadNuid == "nil" then + if Utils.IsEmpty(deadNuid) or deadNuid == "nil" then error(("onDeadNuids deadNuid is empty: %s"):format(deadNuid), 2) else if peer then @@ -631,7 +631,7 @@ function Server.new(sockServer) -- Called when someone connects to the server -- self:on("connect", function(data, peer) - -- logger:debug(logger.channels.network, "Someone connected to the server:", util.pformat(data)) + -- logger:debug(logger.channels.network, "Someone connected to the server:", Utils.pformat(data)) -- local local_player_id = MinaUtils.getLocalMinaEntityId() -- local x, y, rot, scale_x, scale_y = EntityGetTransform(local_player_id) @@ -644,8 +644,8 @@ function Server.new(sockServer) -- self:on( -- "clientInfo", -- function(data, peer) - -- logger:debug(logger.channels.network, "on_clientInfo: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_clientInfo: peer =", util.pformat(peer)) + -- logger:debug(logger.channels.network, "on_clientInfo: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_clientInfo: peer =", Utils.pformat(peer)) -- setClientInfo(data, peer) -- end -- ) @@ -653,8 +653,8 @@ function Server.new(sockServer) -- self:on( -- "worldFilesFinished", -- function(data, peer) - -- logger:debug(logger.channels.network, "on_worldFilesFinished: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_worldFilesFinished: peer =", util.pformat(peer)) + -- logger:debug(logger.channels.network, "on_worldFilesFinished: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_worldFilesFinished: peer =", Utils.pformat(peer)) -- -- Send restart command -- peer:send("restart", { "Restart now!" }) -- end @@ -664,7 +664,7 @@ function Server.new(sockServer) -- self:on( -- "disconnect", -- function(data) - -- logger:debug(logger.channels.network, "on_disconnect: data =", util.pformat(data)) + -- logger:debug(logger.channels.network, "on_disconnect: data =", Utils.pformat(data)) -- end -- ) @@ -672,16 +672,16 @@ function Server.new(sockServer) -- self:on( -- "receive", -- function(data, channel, client) - -- logger:debug(logger.channels.network, "on_receive: data =", util.pformat(data)) - -- logger:debug(logger.channels.network, "on_receive: channel =", util.pformat(channel)) - -- logger:debug(logger.channels.network, "on_receive: client =", util.pformat(client)) + -- logger:debug(logger.channels.network, "on_receive: data =", Utils.pformat(data)) + -- logger:debug(logger.channels.network, "on_receive: channel =", Utils.pformat(channel)) + -- logger:debug(logger.channels.network, "on_receive: client =", Utils.pformat(client)) -- end -- ) -- self:on( -- "needNuid", -- function(data) - -- logger:debug(logger.channels.network, "%s (%s) needs a new nuid.", data.owner.name, data.owner.guid, util.pformat(data)) + -- logger:debug(logger.channels.network, "%s (%s) needs a new nuid.", data.owner.name, data.owner.guid, Utils.pformat(data)) -- local new_nuid = NuidUtils.getNextNuid() -- -- tell the clients that there is a new entity, they have to spawn, besides the client, who sent the request @@ -694,7 +694,7 @@ function Server.new(sockServer) -- self:on( -- "newNuid", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- if self.guid == data.owner.guid then -- logger:debug(logger.channels.network, @@ -711,7 +711,7 @@ function Server.new(sockServer) -- self:on( -- "entityAlive", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- self:sendToAll2("entityAlive", data) -- em:DespawnEntity(data.owner, data.localEntityId, data.nuid, data.isAlive) @@ -721,7 +721,7 @@ function Server.new(sockServer) -- self:on( -- "entityState", -- function(data) - -- logger:debug(logger.channels.network, util.pformat(data)) + -- logger:debug(logger.channels.network, Utils.pformat(data)) -- local nc = em:GetNetworkComponent(data.owner, data.localEntityId, data.nuid) -- if nc then @@ -842,7 +842,7 @@ function Server.new(sockServer) if NetworkUtils.alreadySent(peer, event, data) then Logger.debug(Logger.channels.network, ("Network message for %s for data %s already was acknowledged.") - :format(event, util.pformat(data))) + :format(event, Utils.pformat(data))) CustomProfiler.stop("Server.send", cpc022) return false end @@ -862,14 +862,14 @@ function Server.new(sockServer) function self:sendToAll(event, data) local cpc023 = CustomProfiler.start("Server.sendToAll") local sent = false - if util.IsEmpty(self.clients) then + if Utils.IsEmpty(self.clients) then Logger.trace(Logger.channels.testing, - ("Unable to send anything, when there are no clients %s!"):format(util.pformat(self.clients))) + ("Unable to send anything, when there are no clients %s!"):format(Utils.pformat(self.clients))) return sent end for i = 1, #self.clients do Logger.trace(Logger.channels.testing, - ("Sending event '%s' with data '%s' to client.name '%s'!"):format(event, util.pformat(data), + ("Sending event '%s' with data '%s' to client.name '%s'!"):format(event, Utils.pformat(data), self.clients[i].name)) sent = self:send(self.clients[i], event, data) end @@ -1020,13 +1020,13 @@ function Server.new(sockServer) return end - --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + --local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) local data = { NetworkUtils.getNextNetworkMessageId(), { compOwnerName, compOwnerGuid }, compNuid, x, y, rotation, velocity, health } - if util.IsEmpty(compNuid) then + if Utils.IsEmpty(compNuid) then ---- nuid must not be empty, when Server! --logger:error(logger.channels.network, "Unable to send entity data, because nuid is empty.") --return diff --git a/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua b/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua index dd88e19e4..295ce6dd6 100644 --- a/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua +++ b/mods/noita-mp/files/scripts/noita-components/lua_component_enabler.lua @@ -2,14 +2,9 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") - function enabled_changed(entityId, isEnabled) - if not EntityUtils.isEntityAlive(entityId) then - return - end - + if not EntityUtils.isEntityAlive(entityId) then return end if isEnabled == true then - if NetworkVscUtils.isNetworkEntityByNuidVsc(entityId) then NetworkVscUtils.enableComponents(entityId) end diff --git a/mods/noita-mp/files/scripts/noita-components/name_tags.lua b/mods/noita-mp/files/scripts/noita-components/name_tags.lua index 1488e205e..4684f0890 100644 --- a/mods/noita-mp/files/scripts/noita-components/name_tags.lua +++ b/mods/noita-mp/files/scripts/noita-components/name_tags.lua @@ -6,35 +6,20 @@ function PlayerNameFunction(entity_id, playerName) GuiStartFrame(gui) local screenWidth, screenHeight = GuiGetScreenDimensions(gui) screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 + local x, y = EntityGetTransform(entity_id) + local camX, camY = GameGetCameraPos() - local x, y = EntityGetTransform(entity_id) - - local function getEntityPositionOnScreen() - local camX, camY = GameGetCameraPos() - return screenWidth + ((x - camX) * 1.5), screenHeight + ((y - camY) * 1.5) - end - - local entityX, entityY = getEntityPositionOnScreen() - local playerNameLength = string.len(playerName) - local playerNameMid = entityX - (playerNameLength * 2) - - GuiText(gui, playerNameMid, entityY, playerName) + GuiText(gui, ((screenWidth + ((x - camX) * 1.5)) - (string.len(playerName) * 2)), + (screenHeight + ((y - camY) * 1.5)), playerName) end local entityId = GetUpdatedEntityID() - -if not EntityUtils.isEntityAlive(entityId) then - return -end - +if not EntityUtils.isEntityAlive(entityId) then return end name = name or nil - if not name then local vsc = EntityGetComponentIncludingDisabled(entityId, "VariableStorageComponent") or {} for i = 1, #vsc do - local variable_storage_component_name = ComponentGetValue2(vsc[i], "name") or nil - if variable_storage_component_name == "noita-mp.nc_owner.name" then - -- see NetworkComponent.component_name_owner_username = "noita-mp.nc_owner.username" + if ComponentGetValue2(vsc[i], "name") == "noita-mp.nc_owner.name" then name = ComponentGetValue2(vsc[i], "value_string") end end @@ -42,4 +27,4 @@ end if name then PlayerNameFunction(entityId, name) -end +end \ No newline at end of file diff --git a/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua b/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua index 5979f7c60..2f0c39cb9 100644 --- a/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua +++ b/mods/noita-mp/files/scripts/noita-components/nuid_debug.lua @@ -1,34 +1,19 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") -dofile_once("mods/noita-mp/files/scripts/extensions/table_extensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/tableExtensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/mathExtensions.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") NoitaComponentUtils = dofile_once("mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua") - -function math.sign(v) - return (v >= 0 and 1) or -1 -end - -function math.round(v, bracket) - bracket = bracket or 1 - return math.floor(v / bracket + math.sign(v) * 0.5) * bracket -end - if ModSettingGet("noita-mp.toggle_debug") then - local entityId = GetUpdatedEntityID() - - if not EntityUtils.isEntityAlive(entityId) then - return - end + if not EntityUtils.isEntityAlive(entityId) then return end gui = gui or GuiCreate() GuiStartFrame(gui) - - local screenWidth, screenHeight = GuiGetScreenDimensions(gui) - screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 + local screenWidth, screenHeight = GuiGetScreenDimensions(gui) + screenWidth, screenHeight = screenWidth / 2, screenHeight / 2 local compOwnerName, compOwnerGuid, compNuid, filename, health, rotation, velocity, x, y = NoitaComponentUtils.getEntityData(entityId) - local function getEntityPositionOnScreen() local camX, camY = GameGetCameraPos() return screenWidth + ((x - camX) * 1.5), screenHeight + ((y - camY) * 1.5) @@ -36,20 +21,21 @@ if ModSettingGet("noita-mp.toggle_debug") then local data = { owner = compOwnerName, - --guid = compOwnerGuid, + --guid = compOwnerGuid, nuid = compNuid, filename = filename, healthCurrent = health.current, healthMax = health.max, - --rotation = rotation, + --rotation = rotation, vX = velocity.x, vY = velocity.y, x = x, y = y } - table.setNoitaMpDefaultMetaMethods(data, "kv") + table.setNoitaMpDefaultMetaMethods(data, "kv") local i = 0 + for name, value in pairs(data) do local entityX, entityY = getEntityPositionOnScreen() local text = ("%s: %s"):format(name, value) @@ -58,6 +44,5 @@ if ModSettingGet("noita-mp.toggle_debug") then GuiText(gui, textMid, entityY + (i * 6), text) i = i + 1 end - data = nil end diff --git a/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua b/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua index 3e017a0db..d6d1db74a 100644 --- a/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua +++ b/mods/noita-mp/files/scripts/noita-components/nuid_updater.lua @@ -1,37 +1,28 @@ dofile_once("mods/noita-mp/files/scripts/init/init_logger.lua") -dofile_once("mods/noita-mp/files/scripts/extensions/string_extensions.lua") +dofile_once("mods/noita-mp/files/scripts/extensions/stringExtensions.lua") EntityUtils = dofile_once("mods/noita-mp/files/scripts/util/EntityUtils.lua") NetworkVscUtils = dofile_once("mods/noita-mp/files/scripts/util/NetworkVscUtils.lua") GlobalsUtils = dofile_once("mods/noita-mp/files/scripts/util/GlobalsUtils.lua") +local executeOnAdded = GetValueBool("executeOnAdded", 1) -local executeOnAdded = GetValueBool("executeOnAdded", true) - ---#region local functions - ---#endregion - ---#region executeOnAdded = added() and executeOnRemove = remove() - -local function added() +if executeOnAdded then Logger.debug(Logger.channels.nuid, "nuid_updater.lua added..") local currentEntityId = GetUpdatedEntityID() - if not EntityUtils.isEntityAlive(currentEntityId) then - return - end - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(currentEntityId) + if not EntityUtils.isEntityAlive(currentEntityId) then return end + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(currentEntityId) local globalsNuid, globalsEntityId = GlobalsUtils.getNuidEntityPair(nuid) - if currentEntityId ~= globalsEntityId then GlobalsUtils.setNuid(nuid, currentEntityId) Logger.debug(Logger.channels.nuid, ("nuid in noitas global storage was set: nuid = %s and entity_id = %s") - :format(nuid, currentEntityId)) + :format(nuid, currentEntityId)) end + SetValueBool("executeOnAdded", 0) end -local function remove() +if not executeOnAdded then Logger.debug(Logger.channels.nuid, "nuid_updater.lua remove..") local currentEntityId = GetUpdatedEntityID() - local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(currentEntityId) + local ownerName, ownerGuid, nuid = NetworkVscUtils.getAllVscValuesByEntityId(currentEntityId) local globalsNuid, globalsEntityId = GlobalsUtils.getNuidEntityPair(nuid) if not globalsEntityId then @@ -41,24 +32,6 @@ local function remove() GlobalsUtils.setNuid(nuid, tonumber(currentEntityId * -1)) GlobalsUtils.setDeadNuid(nuid) Logger.debug(Logger.channels.nuid, - ("Entity (%s) was killed and nuid (%s) in noitas global storage was updated: old=%s and new=-%s") - :format(currentEntityId, nuid, globalsEntityId, tonumber(globalsEntityId * -1))) -end - ---#endregion - - ---#region Decision maker if executed on added or remove - -if executeOnAdded then - -- this was executed on added - added() - SetValueBool("executeOnAdded", false) + ("Entity (%s) was killed and nuid (%s) in noitas global storage was updated: old=%s and new=-%s") + :format(currentEntityId, nuid, globalsEntityId, tonumber(globalsEntityId * -1))) end - -if not executeOnAdded then - -- this was executed on remove - remove() -end - ---#endregion diff --git a/mods/noita-mp/files/scripts/util/CustomProfiler.lua b/mods/noita-mp/files/scripts/util/CustomProfiler.lua index 7e6f36788..2dfea10aa 100644 --- a/mods/noita-mp/files/scripts/util/CustomProfiler.lua +++ b/mods/noita-mp/files/scripts/util/CustomProfiler.lua @@ -9,8 +9,8 @@ local json = require("dkjson") local plotly = require("plotly") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") ---@class CustomProfiler CustomProfiler = {} @@ -20,7 +20,7 @@ CustomProfiler.threshold = 16.5 --ms = 60.60 fps CustomProfiler.ceiling = 1001 -- ms CustomProfiler.maxEntries = 25 -- entries per trace CustomProfiler.reportDirectory = ("%s%sNoitaMP-Reports%s%s") - :format(fu.getDesktopDirectory(), pathSeparator, pathSeparator, os.date("%Y-%m-%d_%H-%M-%S", os.time())) + :format(fu.GetDesktopDirectory(), pathSeparator, pathSeparator, os.date("%Y-%m-%d_%H-%M-%S", os.time())) CustomProfiler.reportFilename = "report.html" CustomProfiler.reportJsonFilenamePattern = "%s.json" @@ -83,7 +83,7 @@ function CustomProfiler.stop(functionName, customProfilerCounter) return 0 end - if util.IsEmpty(CustomProfiler.reportCache) then + if Utils.IsEmpty(CustomProfiler.reportCache) then return end @@ -147,7 +147,7 @@ function CustomProfiler.stop(functionName, customProfilerCounter) CustomProfiler.reportCache[functionName]["size"] and CustomProfiler.reportCache[functionName]["size"] >= CustomProfiler.maxEntries then - if not fu.exists(CustomProfiler.reportDirectory) then + if not fu.Exists(CustomProfiler.reportDirectory) then fu.MkDir(CustomProfiler.reportDirectory) end diff --git a/mods/noita-mp/files/scripts/util/EntityUtils.lua b/mods/noita-mp/files/scripts/util/EntityUtils.lua index b4e50ed9b..cb6664201 100644 --- a/mods/noita-mp/files/scripts/util/EntityUtils.lua +++ b/mods/noita-mp/files/scripts/util/EntityUtils.lua @@ -14,11 +14,11 @@ dofile("mods/noita-mp/config.lua") --- This is done by the following code: ------------------------------------------------------------------------------------------------------------------------ if require then - util = require("util") + Utils = require("Utils") else -- Fix stupid Noita sandbox issue. Noita Components does not have access to require. - if not util then - util = dofile("mods/noita-mp/files/scripts/util/util.lua") + if not Utils then + Utils = dofile("mods/noita-mp/files/scripts/util/Utils.lua") end if not EntityCache then @@ -198,7 +198,7 @@ function EntityUtils.isRemoteMinae(entityId) local client = clients[i] local clientsNuid = client.nuid local nuidRemote, entityIdRemote = GlobalsUtils.getNuidEntityPair(clientsNuid) - if not util.IsEmpty(entityIdRemote) and entityIdRemote == entityId then + if not Utils.IsEmpty(entityIdRemote) and entityIdRemote == entityId then CustomProfiler.stop("EntityUtils.isRemoteMinae", cpc) return true end @@ -213,7 +213,7 @@ function EntityUtils.isRemoteMinae(entityId) local client = Client.otherClients[i] local clientsNuid = client.nuid local nuidRemote, entityIdRemote = GlobalsUtils.getNuidEntityPair(clientsNuid) - if not util.IsEmpty(entityIdRemote) and entityIdRemote == entityId then + if not Utils.IsEmpty(entityIdRemote) and entityIdRemote == entityId then CustomProfiler.stop("EntityUtils.isRemoteMinae", cpc) return true end @@ -260,7 +260,7 @@ function EntityUtils.processAndSyncEntityNetworking() otherwise nuid isn't set when extracting parents. ]]-- for i = 1, #entityIds do local childEntityIds = EntityGetAllChildren(entityIds[i]) - if not util.IsEmpty(childEntityIds) then + if not Utils.IsEmpty(childEntityIds) then table.insertAllButNotDuplicates(entityIds, childEntityIds) end end @@ -479,7 +479,7 @@ function EntityUtils.spawnEntity(owner, nuid, x, y, rotation, velocity, filename -- double check, if there is already an entity with this NUID and return the entity_id if EntityUtils.isEntityAlive(localEntityId) and NetworkVscUtils.hasNetworkLuaComponents(localEntityId) then - local ownerNameByVsc, ownerGuidByVsc, nuidByVsc = NetworkVscUtils.getAllVcsValuesByEntityId(localEntityId) + local ownerNameByVsc, ownerGuidByVsc, nuidByVsc = NetworkVscUtils.getAllVscValuesByEntityId(localEntityId) -- if guid is not equal, but nuid is the same, then something is broken for sure! if ownerGuidByVsc ~= remoteGuid and nuidByVsc == nuid then error(("Trying to spawn entity(%s) locally, but owner does not match: remoteOwner(%s) ~= localOwner(%s). remoteNuid(%s) ~= localNuid(%s)") @@ -536,11 +536,11 @@ function EntityUtils.destroyByNuid(peer, nuid) local cpc = CustomProfiler.start("EntityUtils.destroyByNuid") if not peer or type(peer) ~= "table" then - error(("EntityUtils.destroyByNuid: peer is not a table: %s"):format(util.pformat(peer)), 2) + error(("EntityUtils.destroyByNuid: peer is not a table: %s"):format(Utils.pformat(peer)), 2) end if not nuid then - error(("EntityUtils.destroyByNuid: nuid must not be nil: %s"):format(util.pformat(nuid)), 2) + error(("EntityUtils.destroyByNuid: nuid must not be nil: %s"):format(Utils.pformat(nuid)), 2) end if type(nuid) ~= "number" then diff --git a/mods/noita-mp/files/scripts/util/file_util.lua b/mods/noita-mp/files/scripts/util/FileUtils.lua similarity index 64% rename from mods/noita-mp/files/scripts/util/file_util.lua rename to mods/noita-mp/files/scripts/util/FileUtils.lua index 850d456f8..e3555c51d 100644 --- a/mods/noita-mp/files/scripts/util/file_util.lua +++ b/mods/noita-mp/files/scripts/util/FileUtils.lua @@ -1,23 +1,21 @@ -local fu = {} -local ffi = require("ffi") -local watcher = require("watcher") -local lfs = require("lfs") -local json = require("json") -local util = require("util") - ------------------------------------------------------------------------------------------------------------------------ ---- Version ------------------------------------------------------------------------------------------------------------------------ -function fu.getVersionByFile() - local modsPath = fu.GetAbsoluteDirectoryPathOfNoitaMP() +---@class FileUtils +local FileUtils = {} +local ffi = require("ffi") +local watcher = require("watcher") +local lfs = require("lfs") +local json = require("json") +local Utils = require("Utils") + +--- @return string +function FileUtils.GetVersionByFile() + local modsPath = FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() local versionAbsFilePath = ("%s%s.version"):format(modsPath, pathSeparator) - local content = fu.ReadFile(versionAbsFilePath, "*l") - if not content or util.IsEmpty(content) then + local content = FileUtils.ReadFile(versionAbsFilePath, "*l") + if not content or Utils.IsEmpty(content) then error(("Unable to read NoitaMP version. Check if '%s' exists!") - :format(fu.GetAbsolutePathOfNoitaRootDirectory() + "/.version"), 2) + :format(FileUtils.GetAbsolutePathOfNoitaRootDirectory() + "/.version"), 2) end - local jsonTable = json.decode(content) - local version = jsonTable.version + local version = json.decode(content).version Logger.info(Logger.channels.initialize, ("NoitaMP %s"):format(version)) return version end @@ -30,33 +28,27 @@ end --- Error if path is not a string. --- @param path string --- @return string path -function fu.ReplacePathSeparator(path) - if type(path) ~= "string" then - error("path is not a string") - end - if _G.is_windows then - --logger:debug("file_util.lua | windows detected replace / with \\") - path = string.gsub(path, "/", "\\") - elseif _G.is_linux then - --logger:debug("file_util.lua | unix detected replace \\ with /") - path = string.gsub(path, "\\", "/") - else +function FileUtils.ReplacePathSeparator(path) + if type(path) == "string" then + if (_G.is_windows) then + ---@diagnostic disable-next-line: redundant-return-value + return path:gsub("/", "\\") + elseif (_G.is_linux) then + ---@diagnostic disable-next-line: redundant-return-value + return path:gsub("\\", "/") + end error( - ("file_util.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format( - _G.os_name, - _G.os_arch - ), - 2 - ) + ("Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format(_G.os_name, _G.os_arch), + 2) end - return path + error("path is not a string", 2) end --- Removes trailing path separator in a string: \persistent\flags\ -> \persistent\flags. --- Error if path is not a string. --- @param path string any string, i.e. \persistent\flags\ --- @return string path \persistent\flags -function fu.RemoveTrailingPathSeparator(path) +function FileUtils.RemoveTrailingPathSeparator(path) if type(path) ~= "string" then error("path is not a string") end @@ -69,12 +61,8 @@ end ----------------------------------------------------------------------------------------------------------------------- --- eNet specific commands ----------------------------------------------------------------------------------------------------------------------- -function fu.getPidOfRunningEnetHostByPort() - --if _G.whoAmI() == _G.Client.iAm then - -- error("Makes no sense to get PID of eNet, when client!", 2) - -- return - --end - +--- @return number? +function FileUtils.GetPidOfRunningEnetHostByPort() local command = nil if _G.is_windows then command = ('netstat -abon | find /i "%s"'):format(_G.Server:getPort()) @@ -91,7 +79,7 @@ function fu.getPidOfRunningEnetHostByPort() return tonumber(pid) end -function fu.killProcess(pid) +function FileUtils.KillProcess(pid) local command = nil if _G.is_windows then command = ('taskkill /PID %s /F'):format(pid) @@ -107,40 +95,34 @@ end ---------------------------------------------------------------------------------------------------- local noitaRootDirectory = nil --- Sets root directory of noita.exe, i.e. C:\Program Files (x86)\Steam\steamapps\common\Noita -function fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.SetAbsolutePathOfNoitaRootDirectory() if _G.is_windows then noitaRootDirectory = assert(io.popen("cd"):read("*l"), - "Unable to run windows command 'cd' to get Noitas root directory!") + "Unable to run windows command 'cd' to get Noitas root directory!") elseif _G.is_linux then noitaRootDirectory = assert(io.popen("pwd"):read("*l"), - "Unable to run ubuntu command 'pwd' to get Noitas root directory!") + "Unable to run ubuntu command 'pwd' to get Noitas root directory!") else - error( - ("file_util.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!"):format( - _G.os_name, - _G.os_arch - ), - 2 - ) + error(("FileUtils.lua | Unable to detect OS(%s[%s]), therefore not able to replace path separator!") + :format(_G.os_name, _G.os_arch), 2) end - - noitaRootDirectory = fu.ReplacePathSeparator(noitaRootDirectory) - + noitaRootDirectory = FileUtils.ReplacePathSeparator(noitaRootDirectory) if isTestLuaContext then Logger.trace(Logger.channels.testing, - ("Absolute path of Noitas root directory set to %s, but we need to fix path! Removing \\mods\\noita-mp.") - :format(noitaRootDirectory)) + ("Absolute path of Noitas root directory set to %s, but we need to fix path! Removing \\mods\\noita-mp.") + :format(noitaRootDirectory)) local i, _ = string.find(noitaRootDirectory, "mods") noitaRootDirectory = string.sub(noitaRootDirectory, 0, i - 1) Logger.trace(Logger.channels.testing, - ("NEW absolute path of Noitas root directory set to %s.") - :format(noitaRootDirectory)) + ("NEW absolute path of Noitas root directory set to %s.") + :format(noitaRootDirectory)) end end -function fu.GetAbsolutePathOfNoitaRootDirectory() +---@return string +function FileUtils.GetAbsolutePathOfNoitaRootDirectory() if not noitaRootDirectory then - fu.SetAbsolutePathOfNoitaRootDirectory() + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end return noitaRootDirectory end @@ -153,7 +135,7 @@ end --- If DebugGetIsDevBuild() then Noitas installation path is returned: 'C:\Program Files (x86)\Steam\steamapps\common\Noita' --- otherwise it will return: '%appdata%\..\LocalLow\Nolla_Games_Noita' on windows --- @return string save06_parent_directory_path string of absolute path to '..\Noita' or '..\Nolla_Games_Noita' -function fu.GetAbsoluteDirectoryPathOfParentSave() +function FileUtils.GetAbsoluteDirectoryPathOfParentSave() local file = nil local command = nil local find_directory_name = nil @@ -178,7 +160,7 @@ function fu.GetAbsoluteDirectoryPathOfParentSave() local line = "" while line ~= nil do line = file:read("*l") - --logger:debug("file_util.lua | GetAbsoluteDirectoryPathOfParentSave line = " .. line) + --logger:debug("FileUtils.lua | GetAbsoluteDirectoryPathOfParentSave line = " .. line) if string.find(line, find_directory_name) then save06_parent_directory_path = line break @@ -188,73 +170,73 @@ function fu.GetAbsoluteDirectoryPathOfParentSave() if save06_parent_directory_path == nil or save06_parent_directory_path == "" then GamePrintImportant( - "Unable to find world files", - "Do yourself a favour and save&quit the game and start it again!", "" + "Unable to find world files", + "Do yourself a favour and save&quit the game and start it again!", "" ) end - save06_parent_directory_path = fu.ReplacePathSeparator(save06_parent_directory_path) + save06_parent_directory_path = FileUtils.ReplacePathSeparator(save06_parent_directory_path) return save06_parent_directory_path end --- Returns fullpath of save06 directory on devBuild or release --- @return string directory_path_of_save06 : noita installation path\save06 or %appdata%\..\LocalLow\Nolla_Games_Noita\save06 on windows and unknown for unix systems -function fu.GetAbsoluteDirectoryPathOfSave06() - local directory_path_of_save06 = fu.GetAbsoluteDirectoryPathOfParentSave() .. _G.pathSeparator .. "save06" +function FileUtils.GetAbsoluteDirectoryPathOfSave06() + local directory_path_of_save06 = FileUtils.GetAbsoluteDirectoryPathOfParentSave() .. _G.pathSeparator .. "save06" return directory_path_of_save06 end --- Returns the ABSOLUTE path of the mods folder. --- If fu.GetAbsolutePathOfNoitaRootDirectory() is not set yet, then it will be --- @return string fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" -function fu.GetAbsoluteDirectoryPathOfNoitaMP() - if not fu.GetAbsolutePathOfNoitaRootDirectory() then - fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() + if not FileUtils.GetAbsolutePathOfNoitaRootDirectory() then + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end - local p = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" - p = fu.ReplacePathSeparator(p) + local p = FileUtils.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp" + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the RELATIVE path of the mods folder. --- @return string "mods/noita-mp" -function fu.GetRelativeDirectoryPathOfNoitaMP() +function FileUtils.GetRelativeDirectoryPathOfNoitaMP() local p = "mods/noita-mp" - p = fu.ReplacePathSeparator(p) + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the RELATIVE path of the library folder required for this mod. --- @return string "/mods/noita-mp/files/libs" -function fu.GetRelativeDirectoryPathOfRequiredLibs() +function FileUtils.GetRelativeDirectoryPathOfRequiredLibs() local p = "mods/noita-mp/files/libs" - p = fu.ReplacePathSeparator(p) + p = FileUtils.ReplacePathSeparator(p) return p end --- Returns the ABSOLUTE path of the library folder required for this mod. --- If fu.GetAbsolutePathOfNoitaRootDirectory() is not set yet, then it will be --- @return string fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" -function fu.GetAbsoluteDirectoryPathOfRequiredLibs() - if not fu.GetAbsolutePathOfNoitaRootDirectory() then - fu.SetAbsolutePathOfNoitaRootDirectory() +function FileUtils.GetAbsoluteDirectoryPathOfRequiredLibs() + if not FileUtils.GetAbsolutePathOfNoitaRootDirectory() then + FileUtils.SetAbsolutePathOfNoitaRootDirectory() end - local p = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" - p = fu.ReplacePathSeparator(p) + local p = FileUtils.GetAbsolutePathOfNoitaRootDirectory() .. "/mods/noita-mp/files/libs" + p = FileUtils.ReplacePathSeparator(p) return p end --- There is a world_state.xml per each saveSlot directory, which contains Globals. Nuid are stored in Globals. --- @param saveSlotAbsDirectoryPath string Absolute directory path to the current selected save slot. --- @return string absPath world_state.xml absolute file path -function fu.GetAbsDirPathOfWorldStateXml(saveSlotAbsDirectoryPath) +function FileUtils.GetAbsDirPathOfWorldStateXml(saveSlotAbsDirectoryPath) return ("%s%s%s"):format(saveSlotAbsDirectoryPath, pathSeparator, "world_state.xml") end --- see _G.saveSlotMeta ---@return table -function fu.getLastModifiedSaveSlots() - local save0 = fu.GetAbsoluteDirectoryPathOfParentSave() .. pathSeparator .. "save0" +function FileUtils.GetLastModifiedSaveSlots() + local save0 = FileUtils.GetAbsoluteDirectoryPathOfParentSave() .. pathSeparator .. "save0" local saveSlotLastModified = {} for i = 0, 6, 1 do @@ -263,7 +245,7 @@ function fu.getLastModifiedSaveSlots() watcher(save0X, function(lastModified) if lastModified > 0 then Logger.debug(Logger.channels.initialize, - ("SaveSlot(%s) directory was last modified at %s."):format("save0" .. i, lastModified)) + ("SaveSlot(%s) directory was last modified at %s."):format("save0" .. i, lastModified)) table.insert(saveSlotLastModified, { dir = save0X, lastModified = lastModified, slot = i }) end end) @@ -273,8 +255,8 @@ end --- Returns absolute path of NoitaMP settings directory, --- @return string absPath i.e. "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\settings" -function fu.getAbsolutePathOfNoitaMpSettingsDirectory() - return fu.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "settings" +function FileUtils.GetAbsolutePathOfNoitaMpSettingsDirectory() + return FileUtils.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "settings" end ---------------------------------------------------------------------------------------------------- @@ -284,7 +266,7 @@ end --- Checks if FILE or DIRECTORY exists --- @param absolutePath string full path --- @return boolean -function fu.exists(absolutePath) +function FileUtils.Exists(absolutePath) -- https://stackoverflow.com/a/21637809/3493998 if type(absolutePath) ~= "string" then error("Parameter 'absolutePath' '" .. tostring(absolutePath) .. "' is not type of string!", 2) @@ -293,13 +275,15 @@ function fu.exists(absolutePath) return exists end -function fu.IsFile(full_path) +--- @param full_path string +--- @return boolean +function FileUtils.IsFile(full_path) -- https://stackoverflow.com/a/21637809/3493998 if type(full_path) ~= "string" then - error("file_util.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") end - if not fu.exists(full_path) then - --logger:debug("file_util.lua | Path '" .. tostring(full_path) .. "' does not exist!") + if not FileUtils.Exists(full_path) then + --logger:debug("FileUtils.lua | Path '" .. tostring(full_path) .. "' does not exist!") return false end local f = io.open(full_path) @@ -310,23 +294,27 @@ function fu.IsFile(full_path) return false end -function fu.IsDirectory(full_path) +--- @param full_path string +--- @return boolean +function FileUtils.IsDirectory(full_path) -- https://stackoverflow.com/a/21637809/3493998 if type(full_path) ~= "string" then - error("file_util.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter full_path '" .. tostring(full_path) .. "' is not type of string!") end - local exists = fu.exists(full_path) - --logger:debug("file_util.lua | Directory " .. full_path .. " exists = " .. tostring(exists)) - local is_file = fu.IsFile(full_path) - --logger:debug("file_util.lua | Is the directory a file? " .. full_path .. " is_file = " .. tostring(is_file)) + local exists = FileUtils.Exists(full_path) + --logger:debug("FileUtils.lua | Directory " .. full_path .. " exists = " .. tostring(exists)) + local is_file = FileUtils.IsFile(full_path) + --logger:debug("FileUtils.lua | Is the directory a file? " .. full_path .. " is_file = " .. tostring(is_file)) return (exists and not is_file) end -function fu.ReadBinaryFile(file_fullpath) +--- @param file_fullpath string +--- @return string|number +function FileUtils.ReadBinaryFile(file_fullpath) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- https://stackoverflow.com/a/31857671/3493998 local file = io.open(file_fullpath, "rb") -- r read mode and b binary mode if not file then @@ -337,11 +325,13 @@ function fu.ReadBinaryFile(file_fullpath) return content end -function fu.WriteBinaryFile(file_fullpath, file_content) +--- @param file_fullpath string +--- @param file_content any +function FileUtils.WriteBinaryFile(file_fullpath, file_content) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- http://lua-users.org/wiki/FileInputOutput local fh = assert(io.open(file_fullpath, "wb")) fh:write(file_content) @@ -349,15 +339,17 @@ function fu.WriteBinaryFile(file_fullpath, file_content) fh:close() end -function fu.ReadFile(file_fullpath, mode) +--- @param file_fullpath string +--- @param mode string? +function FileUtils.ReadFile(file_fullpath, mode) if mode == nil then mode = "*a" end if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) -- https://stackoverflow.com/a/31857671/3493998 local file = io.open(file_fullpath, "r") if not file then @@ -368,11 +360,13 @@ function fu.ReadFile(file_fullpath, mode) return content end -function fu.WriteFile(file_fullpath, file_content) +--- @param file_fullpath string +---@param file_content string +function FileUtils.WriteFile(file_fullpath, file_content) if type(file_fullpath) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(file_fullpath) .. "' is not type of string!") end - file_fullpath = fu.ReplacePathSeparator(file_fullpath) + file_fullpath = FileUtils.ReplacePathSeparator(file_fullpath) local segments = string.split(file_fullpath, pathSeparator) or {} local pathPerSegments = "" @@ -380,10 +374,10 @@ function fu.WriteFile(file_fullpath, file_content) -- recursively create directories local segment = segments[i] pathPerSegments = pathPerSegments .. segment .. pathSeparator - if not fu.exists(pathPerSegments) then + if not FileUtils.Exists(pathPerSegments) then if not pathPerSegments:contains(".") then -- dump check if it's a file - fu.MkDir(pathPerSegments) + FileUtils.MkDir(pathPerSegments) end end end @@ -395,12 +389,13 @@ function fu.WriteFile(file_fullpath, file_content) fh:close() end -function fu.MkDir(full_path) +--- @param full_path string +function FileUtils.MkDir(full_path) if type(full_path) ~= "string" then - error("file_util.lua | Parameter file_fullpath '" .. tostring(full_path) .. "' is not type of string!") + error("FileUtils.lua | Parameter file_fullpath '" .. tostring(full_path) .. "' is not type of string!") end -- https://stackoverflow.com/a/1690932/3493998 - full_path = fu.ReplacePathSeparator(full_path) + full_path = FileUtils.ReplacePathSeparator(full_path) local command = nil if _G.is_windows then @@ -411,8 +406,9 @@ function fu.MkDir(full_path) os.execute(command) end -function fu.AppendToFile(filenameAbsolutePath, appendContent) - -- TODO rework: have a look on plotly.lua ">>" +--- @param filenameAbsolutePath string +---@param appendContent string +function FileUtils.AppendToFile(filenameAbsolutePath, appendContent) local isEmpty = true local file = io.open(filenameAbsolutePath, "a+") for line in io.lines(filenameAbsolutePath) do @@ -427,18 +423,18 @@ function fu.AppendToFile(filenameAbsolutePath, appendContent) file:close() end ----comment --- http://lua-users.org/wiki/SplitJoin -> Example: Split a file path string into components. ---@param str any ---@return unknown -function fu.splitPath(str) +function FileUtils.SplitPath(str) return string.split(str, '[\\/]+') -- TODO: differ between windows and unix --parts = split_path("/usr/local/bin") --> {'usr','local','bin'} end -- Lua implementation of PHP scandir function -function fu.scanDir(directory) +--- @return string[] +function FileUtils.ScanDir(directory) local i, t, popen = 0, {}, io.popen local pfile = nil @@ -456,16 +452,14 @@ function fu.scanDir(directory) return t end -function fu.removeContentOfDirectory(absolutePath) +function FileUtils.RemoveContentOfDirectory(absolutePath) local successRmDir, errorRmDir = lfs.rmdir(absolutePath) - if not successRmDir or errorRmDir then local command = ('rmdir /s /q "%s"'):format(absolutePath) local success, exitCode, code = os.execute(command) Logger.debug(Logger.channels.testing, - ("Tried to remove directory. success=%s, exitCode=%s, code=%s"):format(success, exitCode, code)) + ("Tried to remove directory. success=%s, exitCode=%s, code=%s"):format(success, exitCode, code)) end - lfs.mkdir(absolutePath) end @@ -473,28 +467,29 @@ end --- 7zip stuff ---------------------------------------------------------------------------------------------------- -function fu.Find7zipExecutable() +function FileUtils.Find7zipExecutable() if is_windows then local f = io.popen("where.exe 7z", "r") if not f then error( - "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!", - 2 + "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!", + 2 ) os.exit() end local response = f:read("*a") - _G.seven_zip = tostring(fu.ReplacePathSeparator(response)) - Logger.debug(Logger.channels.testing, "file_util.lua | Found 7z.exe: " .. _G.seven_zip) + _G.seven_zip = tostring(FileUtils.ReplacePathSeparator(response)) + Logger.debug(Logger.channels.testing, "FileUtils.lua | Found 7z.exe: " .. _G.seven_zip) else error( - "Unfortunately unix systems aren't supported yet. Please consider https://github.com/Ismoh/NoitaMP/issues!", - 2 + "Unfortunately unix systems aren't supported yet. Please consider https://github.com/Ismoh/NoitaMP/issues!", + 2 ) end end -function fu.exists7zip() +--- @return boolean +function FileUtils.Exists7zip() if _G.seven_zip then return true else @@ -502,58 +497,56 @@ function fu.exists7zip() end end ----comment ---@param archive_name string server_save06_98-09-16_23:48:10 - without file extension (*.7z) ---@param absolute_directory_path_to_add_archive string "C:\Users\Ismoh-PC\AppData\LocalLow\Nolla_Games_Noita\save06" ---@param absolute_destination_path string "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\_" ---@return string|number content binary content of archive -function fu.Create7zipArchive(archive_name, absolute_directory_path_to_add_archive, absolute_destination_path) +function FileUtils.Create7zipArchive(archive_name, absolute_directory_path_to_add_archive, absolute_destination_path) assert( - fu.exists7zip(), - "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!" + FileUtils.Exists7zip(), + "Unable to find 7z.exe, please install 7z via https://7-zip.de/download.html and restart the Noita!" ) if type(archive_name) ~= "string" then - error("file_util.lua | Parameter archive_name '" .. tostring(archive_name) .. "' is not type of string!") + error("FileUtils.lua | Parameter archive_name '" .. tostring(archive_name) .. "' is not type of string!") end if type(absolute_directory_path_to_add_archive) ~= "string" then error( - "file_util.lua | Parameter absolute_directory_path_to_add_archive '" .. - tostring(absolute_directory_path_to_add_archive) .. "' is not type of string!" + "FileUtils.lua | Parameter absolute_directory_path_to_add_archive '" .. + tostring(absolute_directory_path_to_add_archive) .. "' is not type of string!" ) end if type(absolute_destination_path) ~= "string" then error( - "file_util.lua | Parameter absolute_destination_path '" .. - tostring(absolute_destination_path) .. "' is not type of string!" + "FileUtils.lua | Parameter absolute_destination_path '" .. + tostring(absolute_destination_path) .. "' is not type of string!" ) end - absolute_directory_path_to_add_archive = fu.ReplacePathSeparator(absolute_directory_path_to_add_archive) - absolute_destination_path = fu.ReplacePathSeparator(absolute_destination_path) + absolute_directory_path_to_add_archive = FileUtils.ReplacePathSeparator(absolute_directory_path_to_add_archive) + absolute_destination_path = FileUtils.ReplacePathSeparator(absolute_destination_path) local command = 'cd "' .. - absolute_destination_path .. - '" && 7z.exe a -t7z ' .. archive_name .. ' "' .. absolute_directory_path_to_add_archive .. '"' - Logger.debug(Logger.channels.testing, "file_util.lua | Running: " .. command) + absolute_destination_path .. + '" && 7z.exe a -t7z ' .. archive_name .. ' "' .. absolute_directory_path_to_add_archive .. '"' + Logger.debug(Logger.channels.testing, "FileUtils.lua | Running: " .. command) os.execute(command) local archive_full_path = absolute_destination_path .. _G.pathSeparator .. archive_name .. ".7z" - return fu.ReadBinaryFile(archive_full_path) + return FileUtils.ReadBinaryFile(archive_full_path) end ----comment ---@param archive_absolute_directory_path string path to archive location like "C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\_" ---@param archive_name string server_save06_98-09-16_23:48:10.7z - with file extension (*.7z) ---@param extract_absolute_directory_path string "C:\Users\Ismoh-PC\AppData\LocalLow\Nolla_Games_Noita" -function fu.Extract7zipArchive(archive_absolute_directory_path, archive_name, extract_absolute_directory_path) - archive_absolute_directory_path = fu.ReplacePathSeparator(archive_absolute_directory_path) - extract_absolute_directory_path = fu.ReplacePathSeparator(extract_absolute_directory_path) +function FileUtils.Extract7zipArchive(archive_absolute_directory_path, archive_name, extract_absolute_directory_path) + archive_absolute_directory_path = FileUtils.ReplacePathSeparator(archive_absolute_directory_path) + extract_absolute_directory_path = FileUtils.ReplacePathSeparator(extract_absolute_directory_path) local command = 'cd "' .. - archive_absolute_directory_path .. - '" && 7z.exe x -aoa ' .. archive_name .. ' -o"' .. extract_absolute_directory_path .. '"' - Logger.debug(Logger.channels.testing, "file_util.lua | Running: " .. command) + archive_absolute_directory_path .. + '" && 7z.exe x -aoa ' .. archive_name .. ' -o"' .. extract_absolute_directory_path .. '"' + Logger.debug(Logger.channels.testing, "FileUtils.lua | Running: " .. command) os.execute(command) end @@ -564,25 +557,25 @@ end ---------------------------------------------------------------------------------------------------- --- Credits to dextercd! -function fu.restartNoita() +function FileUtils.FestartNoita() require("ffi").cast("void(__fastcall*)()", 0x0066e120)() end -function fu.killNoitaAndRestart() +function FileUtils.KillNoitaAndRestart() local exe = "noita.exe" if DebugGetIsDevBuild() then exe = "noita_dev.exe" end - fu.removeContentOfDirectory(_G.saveSlotMeta.dir) + FileUtils.RemoveContentOfDirectory(_G.saveSlotMeta.dir) os.execute(('start "" %s -no_logo_splashes -save_slot %s -gamemode 4'):format(exe, - _G.saveSlotMeta.slot)) -- -gamemode 0 + _G.saveSlotMeta.slot)) -- -gamemode 0 os.exit() end --- This executes c code to sent SDL_QUIT command to the app -function fu.saveAndRestartNoita() +function FileUtils.SaveAndRestartNoita() ffi.cdef [[ typedef union SDL_Event { @@ -607,10 +600,10 @@ function fu.saveAndRestartNoita() exe = "noita_dev.exe" end os.execute(('start "" %s -no_logo_splashes -save_slot %s -gamemode 4'):format(exe, - _G.saveSlotMeta.slot)) -- -gamemode 0 + _G.saveSlotMeta.slot)) -- -gamemode 0 end -function fu.getAllFilesInDirectory(directory, fileExtension) +function FileUtils.GetAllFilesInDirectory(directory, fileExtension) local command = nil if _G.is_windows then command = "for /f tokens^=* %i in ('where /r \"" .. directory .. "\" *" .. fileExtension .. "')do @echo/ %~nxi" @@ -629,7 +622,7 @@ function fu.getAllFilesInDirectory(directory, fileExtension) return filenames end -function fu.getDesktopDirectory() +function FileUtils.GetDesktopDirectory() local command = nil if _G.is_windows then command = "echo %USERPROFILE%\\Desktop" @@ -644,4 +637,4 @@ function fu.getDesktopDirectory() return string.trim(content) end -return fu +return FileUtils diff --git a/mods/noita-mp/files/scripts/util/GuidUtils.lua b/mods/noita-mp/files/scripts/util/GuidUtils.lua index f6767100b..07093fbc2 100644 --- a/mods/noita-mp/files/scripts/util/GuidUtils.lua +++ b/mods/noita-mp/files/scripts/util/GuidUtils.lua @@ -1,4 +1,4 @@ -local util = require("util") +local Utils = require("Utils") local socket = require("socket") local uuid = require("uuid") @@ -51,7 +51,7 @@ end --- @return string guid function GuidUtils:getGuid(inUsedGuids) local cpc = CustomProfiler.start("GuidUtils:getGuid") - if not util.IsEmpty(inUsedGuids) and #inUsedGuids > 0 then + if not Utils.IsEmpty(inUsedGuids) and #inUsedGuids > 0 then for i = 1, #inUsedGuids do if not GuidUtils.isPatternValid(inUsedGuids[i]) then error(("Already in used guid '%s' is not a valid guid!"):format(inUsedGuids[i]), 2) @@ -60,7 +60,7 @@ function GuidUtils:getGuid(inUsedGuids) ---@cast inUsedGuids table table.insertAllButNotDuplicates(self.cached_guid, inUsedGuids) - Logger.debug(Logger.channels.guid, ("Guid:getGuid() - inUsedGuids: %s"):format(util.pformat(inUsedGuids))) + Logger.debug(Logger.channels.guid, ("Guid:getGuid() - inUsedGuids: %s"):format(Utils.pformat(inUsedGuids))) end repeat @@ -81,7 +81,7 @@ function GuidUtils.isPatternValid(guid) if type(guid) ~= "string" then return false end - if util.IsEmpty(guid) then + if Utils.IsEmpty(guid) then return false end diff --git a/mods/noita-mp/files/scripts/util/Logger.lua b/mods/noita-mp/files/scripts/util/Logger.lua index 6799b6058..49e6bc8bf 100644 --- a/mods/noita-mp/files/scripts/util/Logger.lua +++ b/mods/noita-mp/files/scripts/util/Logger.lua @@ -65,7 +65,7 @@ function Logger.log(level, channel, message) error("There is a directive (%) in your log message. Use string.format! Message = '" .. message .. "'", 2) end - if level == "off" then + if string.lower(level) == "off" then return false end @@ -94,11 +94,9 @@ function Logger.log(level, channel, message) -- add file name to logs: https://stackoverflow.com/a/48469960/3493998 local file_name = debug.getinfo(2, "S").source:sub(2) file_name = file_name:match("^.*/(.*)$") or file_name - msg = ("%s [%s][%s] %s \n(in %s)") - :format(time, level, channel, message, file_name) + msg = ("%s [%s][%s] %s \n(in %s)"):format(time, level, channel, message, file_name) else - msg = ("%s [%s][%s] %s") - :format("--:--:--", level, channel, message) + msg = ("%s [%s][%s] %s"):format("--:--:--", level, channel, message) end print(msg) diff --git a/mods/noita-mp/files/scripts/util/MinaUtils.lua b/mods/noita-mp/files/scripts/util/MinaUtils.lua index 4c6493959..9a83cf87a 100644 --- a/mods/noita-mp/files/scripts/util/MinaUtils.lua +++ b/mods/noita-mp/files/scripts/util/MinaUtils.lua @@ -78,7 +78,7 @@ function MinaUtils.getLocalMinaEntityId() local playerEntityIds = EntityGetWithTag("player_unit") for i = 1, #playerEntityIds do if NetworkVscUtils.hasNetworkLuaComponents(playerEntityIds[i]) then - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(playerEntityIds[i]) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(playerEntityIds[i]) if compOwnerGuid == localMinaGuid then EntityUtils.localPlayerEntityId = playerEntityIds[i] CustomProfiler.stop("MinaUtils.getLocalMinaEntityId", cpc) @@ -122,7 +122,7 @@ function MinaUtils.getLocalMinaInformation() NetworkVscUtils.addOrUpdateAllVscs(entityId, ownerName, ownerGuid, nuid) end - local _, _, nuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local _, _, nuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) CustomProfiler.stop("MinaUtils.getLocalMinaInformation", cpc) return { name = ownerName, @@ -144,7 +144,7 @@ function MinaUtils.isLocalMinaPolymorphed() for c = 1, #componentIds do local isPlayer = ComponentGetValue2(componentIds[c], "is_player") if isPlayer then - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(polymorphedEntityIds[e]) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(polymorphedEntityIds[e]) if compOwnerGuid == localMinaGuid then EntityUtils.localPlayerEntityIdPolymorphed = polymorphedEntityIds[e] CustomProfiler.stop("MinaUtils.isLocalMinaPolymorphed", cpc) diff --git a/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua b/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua index 44a600a01..5bce4fe0a 100644 --- a/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkCacheUtils.lua @@ -10,7 +10,7 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local util = require("util") +local Utils = require("Utils") local md5 = require("md5") ------------------------------------------------------------------------------------------------------------------------ @@ -20,11 +20,11 @@ NetworkCacheUtils = {} function NetworkCacheUtils.getSum(event, data) local cpc = CustomProfiler.start("NetworkCacheUtils.getSum") - Logger.trace(Logger.channels.testing, "getSum: " .. util.pformat(data)) - if not event or util.IsEmpty(event) or type(event) ~= "string" then + Logger.trace(Logger.channels.testing, "getSum: " .. Utils.pformat(data)) + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("Unable to calculate sum, when event is nil or not a string: '%s'"):format(event), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then error(("Unable to calculate sum, when data is nil or not a table: '%s'"):format(data), 2) end @@ -32,15 +32,15 @@ function NetworkCacheUtils.getSum(event, data) error(("Event '%s' shouldn't be cached!"):format(event), 2) end - Logger.trace(Logger.channels.testing, "data: " .. util.pformat(data)) + Logger.trace(Logger.channels.testing, "data: " .. Utils.pformat(data)) local dataCopy = NetworkUtils.getClientOrServer().zipTable(data, NetworkUtils.events[event].schema, event) - Logger.trace(Logger.channels.testing, "dataCopy zipped: " .. util.pformat(dataCopy)) + Logger.trace(Logger.channels.testing, "dataCopy zipped: " .. Utils.pformat(dataCopy)) if event ~= NetworkUtils.events.acknowledgement.name then -- when event is NOT acknowledgement, remove networkMessageId, -- but we need the networkMessageId to find the previous cached network message, when the event is acknowledgement dataCopy.networkMessageId = nil end - Logger.trace(Logger.channels.testing, "dataCopy without networkMessageId: " .. util.pformat(dataCopy)) + Logger.trace(Logger.channels.testing, "dataCopy without networkMessageId: " .. Utils.pformat(dataCopy)) local sum = "" if NetworkUtils.events[event].resendIdentifiers ~= nil then local newData = {} @@ -55,7 +55,7 @@ function NetworkCacheUtils.getSum(event, data) else sum = table.contentToString(dataCopy) end - Logger.trace(Logger.channels.testing, ("sum from %s = %s"):format(util.pformat(dataCopy), sum)) + Logger.trace(Logger.channels.testing, ("sum from %s = %s"):format(Utils.pformat(dataCopy), sum)) CustomProfiler.stop("NetworkCacheUtils.getSum", cpc) return sum end @@ -66,26 +66,26 @@ end --- function NetworkCacheUtils.set(peerGuid, networkMessageId, event, status, ackedAt, sendAt, data) local cpc = CustomProfiler.start("NetworkCacheUtils.set") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(peerGuid), 2) end - if not networkMessageId or util.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then + if not networkMessageId or Utils.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then error(("networkMessageId '%s' must not be nil or empty or isn't type of number!"):format(networkMessageId), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("event '%s' must not be nil or empty or isn't type of string!"):format(event), 2) end - if not status or util.IsEmpty(status) or type(status) ~= "string" then + if not status or Utils.IsEmpty(status) or type(status) ~= "string" then error(("status '%s' must not be nil or empty or isn't type of string!"):format(status), 2) end - if not ackedAt or util.IsEmpty(ackedAt) or type(ackedAt) ~= "number" then + if not ackedAt or Utils.IsEmpty(ackedAt) or type(ackedAt) ~= "number" then error(("ackedAt '%s' must not be nil or empty or isn't type of number!"):format(ackedAt), 2) end - if not sendAt or util.IsEmpty(sendAt) or type(sendAt) ~= "number" then + if not sendAt or Utils.IsEmpty(sendAt) or type(sendAt) ~= "number" then error(("sendAt '%s' must not be nil or empty or isn't type of number!"):format(sendAt), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then - error(("data '%s' must not be nil or empty or isn't type of table!"):format(util.pformat(data)), 2) + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then + error(("data '%s' must not be nil or empty or isn't type of table!"):format(Utils.pformat(data)), 2) end if not NetworkUtils.events[event].isCacheable then @@ -111,13 +111,13 @@ end --- @return table data { ackedAt, dataChecksum, event, messageId, sentAt, status} function NetworkCacheUtils.get(peerGuid, networkMessageId, event) local cpc = CustomProfiler.start("NetworkCacheUtils.get") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(peerGuid), 2) end - if not networkMessageId or util.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then + if not networkMessageId or Utils.IsEmpty(networkMessageId) or type(networkMessageId) ~= "number" then error(("networkMessageId '%s' must not be nil or empty or isn't type of number!"):format(networkMessageId), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then error(("event '%s' must not be nil or empty or isn't type of string!"):format(event), 2) end @@ -138,7 +138,7 @@ function NetworkCacheUtils.get(peerGuid, networkMessageId, event) local data = NetworkCache.get(clientCacheId, event, tonumber(networkMessageId)) Logger.info(Logger.channels.cache, ("Get nCache by clientCacheId %s, event %s, networkMessageId %s, data %s") - :format(clientCacheId, event, networkMessageId, util.pformat(data))) + :format(clientCacheId, event, networkMessageId, Utils.pformat(data))) CustomProfiler.stop("NetworkCacheUtils.get", cpc) return data end @@ -146,14 +146,14 @@ end --- @return table cacheData { ackedAt, dataChecksum, event, messageId, sentAt, status} function NetworkCacheUtils.getByChecksum(peerGuid, event, data) local cpc = CustomProfiler.start("NetworkCacheUtils.getByChecksum") - if not peerGuid or util.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then - error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(util.pformat(peerGuid)), 2) + if not peerGuid or Utils.IsEmpty(peerGuid) or type(peerGuid) ~= "string" then + error(("peerGuid '%s' must not be nil or empty or isn't type of string!"):format(Utils.pformat(peerGuid)), 2) end - if not event or util.IsEmpty(event) or type(event) ~= "string" then - error(("event '%s' must not be nil or empty or isn't type of string!"):format(util.pformat(event)), 2) + if not event or Utils.IsEmpty(event) or type(event) ~= "string" then + error(("event '%s' must not be nil or empty or isn't type of string!"):format(Utils.pformat(event)), 2) end - if not data or util.IsEmpty(data) or type(data) ~= "table" then - error(("data '%s' must not be nil or empty or isn't type of table!"):format(util.pformat(data)), 2) + if not data or Utils.IsEmpty(data) or type(data) ~= "table" then + error(("data '%s' must not be nil or empty or isn't type of table!"):format(Utils.pformat(data)), 2) end if not NetworkUtils.events[event].isCacheable then @@ -166,7 +166,7 @@ function NetworkCacheUtils.getByChecksum(peerGuid, event, data) local cacheData = NetworkCache.getChecksum(clientCacheId, dataChecksum) Logger.info(Logger.channels.cache, ("Get nCache by clientCacheId %s, dataChecksum %s, event %s, cacheData %s") - :format(clientCacheId, dataChecksum, event, util.pformat(cacheData))) + :format(clientCacheId, dataChecksum, event, Utils.pformat(cacheData))) CustomProfiler.stop("NetworkCacheUtils.getByChecksum", cpc) return cacheData end diff --git a/mods/noita-mp/files/scripts/util/NetworkUtils.lua b/mods/noita-mp/files/scripts/util/NetworkUtils.lua index 36ab0e59e..98cbe3975 100644 --- a/mods/noita-mp/files/scripts/util/NetworkUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkUtils.lua @@ -6,7 +6,7 @@ ------------------------------------------------------------------------------------------------------------------------ --- 'Imports' ------------------------------------------------------------------------------------------------------------------------ -local util = require("util") +local Utils = require("Utils") ------------------------------------------------------------------------------------------------------------------------ --- NetworkUtils @@ -201,7 +201,7 @@ function NetworkUtils.alreadySent(peer, event, data) if not data then error("'data' must not be nil!", 2) end - if util.IsEmpty(peer.clientCacheId) then + if Utils.IsEmpty(peer.clientCacheId) then Logger.info(Logger.channels.testing, ("peer.guid = '%s'"):format(peer.guid)) peer.clientCacheId = GuidUtils.toNumber(peer.guid) --error("peer.clientCacheId must not be nil!", 2) end diff --git a/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua b/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua index 930055a0f..35138cd34 100644 --- a/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua +++ b/mods/noita-mp/files/scripts/util/NetworkVscUtils.lua @@ -373,18 +373,18 @@ end --- Returns all Network Vsc values by its entity id. --- @param entityId number Entity Id provided by Noita --- @return string? ownerName, string? ownerGuid, number? nuid - nuid can be nil -function NetworkVscUtils.getAllVcsValuesByEntityId(entityId) - local cpc = CustomProfiler.start("NetworkVscUtils.getAllVcsValuesByEntityId") +function NetworkVscUtils.getAllVscValuesByEntityId(entityId) + local cpc = CustomProfiler.start("NetworkVscUtils.getAllVscValuesByEntityId") if not EntityUtils.isEntityAlive(entityId) then - CustomProfiler.stop("NetworkVscUtils.getAllVcsValuesByEntityId", cpc) + CustomProfiler.stop("NetworkVscUtils.getAllVscValuesByEntityId", cpc) return end local ownerNameCompId, ownerGuidCompId, nuidCompId, _, _ = getNetworkComponents(entityId) - CustomProfiler.stop("NetworkVscUtils.getAllVcsValuesByEntityId", cpc) + CustomProfiler.stop("NetworkVscUtils.getAllVscValuesByEntityId", cpc) if ownerNameCompId and ownerGuidCompId then return NetworkVscUtils.getAllVcsValuesByComponentIds(ownerNameCompId, ownerGuidCompId, nuidCompId) else - error(("getAllVcsValuesByEntityId: Got unexpected nil id. entityId, = %s ownerNameCompId = %s, ownerGuidCompId = %s, nuidCompId = %s") + error(("getAllVscValuesByEntityId: Got unexpected nil id. entityId, = %s ownerNameCompId = %s, ownerGuidCompId = %s, nuidCompId = %s") :format(entityId, ownerNameCompId, ownerGuidCompId, nuidCompId), 2) end end @@ -402,10 +402,10 @@ function NetworkVscUtils.getAllVcsValuesByComponentIds(ownerNameCompId, ownerGui local compOwnerGuid = ComponentGetValue2(ownerGuidCompId, NetworkVscUtils.valueString) local compNuid = ComponentGetValue2(nuidCompId, NetworkVscUtils.valueString) - if util.IsEmpty(compOwnerName) then + if Utils.IsEmpty(compOwnerName) then error(("Something really bad went wrong! compOwnerName must not be empty: %s"):format(compOwnerName), 2) end - if util.IsEmpty(compOwnerGuid) then + if Utils.IsEmpty(compOwnerGuid) then error(("Something really bad went wrong! compOwnerGuid must not be empty: %s"):format(compOwnerGuid), 2) end diff --git a/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua b/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua index d0240d828..fb1f06707 100644 --- a/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua +++ b/mods/noita-mp/files/scripts/util/NoitaComponentUtils.lua @@ -48,7 +48,7 @@ end --- @return string ownername, string ownerguid, number nuid, string filename, EntityHealthData health, number rotation, Vec2 velocity, number x, number y function NoitaComponentUtils.getEntityData(entityId) local cpc = CustomProfiler.start("NoitaComponentUtils.getEntityData") - local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVcsValuesByEntityId(entityId) + local compOwnerName, compOwnerGuid, compNuid = NetworkVscUtils.getAllVscValuesByEntityId(entityId) local hpCompId = EntityGetFirstComponentIncludingDisabled(entityId, "DamageModelComponent") local health = { current = 0, max = 0 } diff --git a/mods/noita-mp/files/scripts/util/NuidUtils.lua b/mods/noita-mp/files/scripts/util/NuidUtils.lua index e8af3a0b4..b518e0c59 100644 --- a/mods/noita-mp/files/scripts/util/NuidUtils.lua +++ b/mods/noita-mp/files/scripts/util/NuidUtils.lua @@ -6,7 +6,7 @@ ---------------------------------------- --- 'Imports' ---------------------------------------- -local fu = require("file_util") +local fu = require("FileUtils") local nxml = require("nxml") ----------------- @@ -27,7 +27,7 @@ local function getNextNuid() -- Are there any nuids saved in globals, if so get the highest nuid? if not xmlParsed then local worldStateXmlAbsPath = fu.GetAbsDirPathOfWorldStateXml(_G.saveSlotMeta.dir) - if fu.exists(worldStateXmlAbsPath) then + if fu.Exists(worldStateXmlAbsPath) then local f = io.open(worldStateXmlAbsPath, "r") local xml = nxml.parse(f:read("*a")) f:close() @@ -64,7 +64,7 @@ function NuidUtils.getEntityIdsByKillIndicator() local cpc = CustomProfiler.start("NuidUtils.getEntityIdsByKillIndicator") local deadNuids = GlobalsUtils.getDeadNuids() local worldStateXmlAbsPath = fu.GetAbsDirPathOfWorldStateXml(_G.saveSlotMeta.dir) - if fu.exists(worldStateXmlAbsPath) then + if fu.Exists(worldStateXmlAbsPath) then local f = io.open(worldStateXmlAbsPath, "r") local xml = nxml.parse(f:read("*a")) f:close() diff --git a/mods/noita-mp/files/scripts/util/util.lua b/mods/noita-mp/files/scripts/util/Utils.lua similarity index 88% rename from mods/noita-mp/files/scripts/util/util.lua rename to mods/noita-mp/files/scripts/util/Utils.lua index e79ef6fbe..a41bac73e 100644 --- a/mods/noita-mp/files/scripts/util/util.lua +++ b/mods/noita-mp/files/scripts/util/Utils.lua @@ -8,11 +8,12 @@ else pprint.defaults = {} end -local util = {} +--- @class Utils +local Utils = {} --- Wait for n seconds. ---@param s number seconds to wait -function util.Sleep(s) +function Utils.Sleep(s) if type(s) ~= "number" then error("Unable to wait if parameter 'seconds' isn't a number: " .. type(s)) end @@ -22,9 +23,9 @@ function util.Sleep(s) until os.clock() > ntime end -function util.IsEmpty(var) +function Utils.IsEmpty(var) -- if you change this also change NetworkVscUtils.lua - -- if you change this also change table_extensions.lua + -- if you change this also change tableExtensions.lua if var == nil then return true end @@ -38,14 +39,14 @@ function util.IsEmpty(var) end --https://noita.wiki.gg/wiki/Modding:_Utilities#Easier_entity_debugging -function util.str(var) +function Utils.Str(var) if type(var) == "table" then local s = "{ " for k, v in pairs(var) do if type(k) ~= "number" then k = '"' .. k .. '"' end - s = s .. "[" .. k .. "] = " .. util.str(v) .. "," + s = s .. "[" .. k .. "] = " .. Utils.Str(v) .. "," end return s .. "} " end @@ -53,7 +54,7 @@ function util.str(var) end --https://noita.wiki.gg/wiki/Modding:_Utilities#Easier_entity_debugging -function util.debug_entity(e) +function Utils.DebugEntity(e) local parent = EntityGetParent(e) local children = EntityGetAllChildren(e) local comps = EntityGetAllComponents(e) @@ -61,7 +62,7 @@ function util.debug_entity(e) local msg = "--- ENTITY DATA ---\n" msg = msg .. ("Parent: [" .. parent .. "] name = " .. (EntityGetName(parent) or "") .. "\n") - msg = msg .. (" Entity: [" .. util.str(e) .. "] name = " .. (EntityGetName(e) or "") .. "\n") + msg = msg .. (" Entity: [" .. Utils.Str(e) .. "] name = " .. (EntityGetName(e) or "") .. "\n") msg = msg .. (" Tags: " .. (EntityGetTags(e) or "") .. "\n") if (comps ~= nil) then for _, comp in ipairs(comps) do @@ -97,18 +98,18 @@ function util.debug_entity(e) Logger.debug(Logger.channels.testing, msg) end -function util.pformat(var) +function Utils.pformat(var) return pprint.pformat(var, pprint.defaults) end --- Reloads the whole world with a specific seed. No need to restart the game and use magic numbers. ---@param seed number max = 4294967295 -function util.reloadMap(seed) +function Utils.ReloadMap(seed) SetWorldSeed(seed) BiomeMapLoad_KeepPlayer("mods/noita-mp/files/scripts/DefaultBiomeMap.lua", "data/biome/_pixel_scenes.xml") end -function util.copyToClipboard(copy) +function Utils.CopyToClipboard(copy) local command = nil if _G.is_windows then command = ('echo "%s" | clip'):format(copy) @@ -118,4 +119,4 @@ function util.copyToClipboard(copy) os.execute(command) end -return util +return Utils diff --git a/mods/noita-mp/init.lua b/mods/noita-mp/init.lua index e29c833bb..0ce244a02 100644 --- a/mods/noita-mp/init.lua +++ b/mods/noita-mp/init.lua @@ -6,10 +6,9 @@ end --- Imports by dofile, dofile_once and require ---------------------------------------------------------------------------------------------------- dofile("mods/noita-mp/files/scripts/init/init_.lua") -local util = require("util") -local fu = require("file_util") -local ui = require("Ui").new() - +local Utils = require("Utils") +local fu = require("FileUtils") +local ui = require("Ui").new() Logger.debug(Logger.channels.initialize, "Starting to load noita-mp init.lua..") ---------------------------------------------------------------------------------------------------- @@ -20,7 +19,7 @@ NoitaMpSettings.clearAndCreateSettings() -- Is used to stop Noita pausing game, when focus is gone (tab out game) ModMagicNumbersFileAdd("mods/noita-mp/files/data/magic_numbers.xml") fu.Find7zipExecutable() -local saveSlotsLastModifiedBeforeWorldInit = fu.getLastModifiedSaveSlots() +local saveSlotsLastModifiedBeforeWorldInit = fu.GetLastModifiedSaveSlots() ---------------------------------------------------------------------------------------------------- --- NoitaMP functions @@ -36,14 +35,14 @@ local function setSeedIfConnectedSecondTime() Logger.debug(Logger.channels.initialize, ("Servers world seed = %s"):format(seed)) if not seed and seed > 0 then if DebugGetIsDevBuild() then - util.Sleep(5) -- needed to be able to attach debugger again + Utils.Sleep(5) -- needed to be able to attach debugger again end local cpc1 = CustomProfiler.start("ModSettingGet") local saveSlotMetaDirectory = ModSettingGet("noita-mp.saveSlotMetaDirectory") CustomProfiler.stop("ModSettingGet", cpc1) if saveSlotMetaDirectory then - fu.removeContentOfDirectory(saveSlotMetaDirectory) + fu.RemoveContentOfDirectory(saveSlotMetaDirectory) else error("Unable to emptying selected save slot!", 2) end @@ -73,14 +72,15 @@ function OnWorldInitialized() local archive_name = "server_save06_" .. os.date("%Y-%m-%d_%H-%M-%S") local destination = fu.GetAbsoluteDirectoryPathOfNoitaMP() .. pathSeparator .. "_" local archive_content = fu.Create7zipArchive(archive_name .. "_from_server", - fu.GetAbsoluteDirectoryPathOfSave06(), destination) - local msg = ("init.lua | Server savegame [%s] was zipped with 7z to location [%s]."):format(archive_name, - destination) + fu.GetAbsoluteDirectoryPathOfSave06(), destination) + local msg = ("init.lua | Server savegame [%s] was zipped with 7z to location [%s]."):format( + archive_name, + destination) Logger.debug(Logger.channels.initialize, msg) GamePrint(msg) local cpc1 = CustomProfiler.start("ModSettingSetNextValue") ModSettingSetNextValue("noita-mp.server_start_7zip_savegame", false, - false) -- automatically start the server again + false) -- automatically start the server again CustomProfiler.stop("ModSettingSetNextValue", cpc1) end CustomProfiler.stop("init.OnWorldInitialized", cpc) @@ -94,11 +94,11 @@ function OnPlayerSpawned(player_entity) if not GameHasFlagRun("nameTags_script_applied") then GameAddFlagRun("nameTags_script_applied") EntityAddComponent2(player_entity, - "LuaComponent", - { - script_source_file = "mods/noita-mp/files/scripts/noita-components/name_tags.lua", - execute_every_n_frame = 1, - }) + "LuaComponent", + { + script_source_file = "mods/noita-mp/files/scripts/noita-components/name_tags.lua", + execute_every_n_frame = 1, + }) end CustomProfiler.stop("init.OnPlayerSpawned", cpc) end @@ -124,7 +124,7 @@ function OnWorldPreUpdate() EntityUtils.addOrChangeDetectionRadiusDebug(MinaUtils.getLocalMinaInformation().entityId) if not _G.saveSlotMeta then - local saveSlotsLastModifiedAfterWorldInit = fu.getLastModifiedSaveSlots() + local saveSlotsLastModifiedAfterWorldInit = fu.GetLastModifiedSaveSlots() for i = 1, #saveSlotsLastModifiedBeforeWorldInit do for j = 1, #saveSlotsLastModifiedAfterWorldInit do local saveSlotMeta @@ -141,7 +141,7 @@ function OnWorldPreUpdate() ModSettingSetNextValue("noita-mp.saveSlotMetaDirectory", _G.saveSlotMeta.dir, false) CustomProfiler.stop("ModSettingSetNextValue", cpc1) Logger.info(Logger.channels.initialize, - ("Save slot found in '%s'"):format(util.pformat(_G.saveSlotMeta))) + ("Save slot found in '%s'"):format(Utils.pformat(_G.saveSlotMeta))) end end end @@ -149,7 +149,6 @@ function OnWorldPreUpdate() Server.update() Client.update() - ui.update() local cpc1 = CustomProfiler.start("init.OnWorldPreUpdate.collectgarbage.count") @@ -162,14 +161,7 @@ function OnWorldPreUpdate() collectgarbage("collect") CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.collect", cpc2) end - CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.count", cpc1) + CustomProfiler.stop("init.OnWorldPreUpdate.collectgarbage.count", cpc1) CustomProfiler.stop("init.OnWorldPreUpdate", cpc) end - ---function OnWorldPostUpdate() --- local cpc = CustomProfiler.start("init.OnWorldPostUpdate") --- Server.update() --- Client.update() --- CustomProfiler.stop("init.OnWorldPostUpdate", cpc) ---end diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua b/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua index 51c116796..6f1c8eb2f 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/os_name.lua @@ -27,6 +27,7 @@ local function getOS() raw_os_name = (raw_os_name):lower() raw_arch_name = (raw_arch_name):lower() + print(("Detected os '%s' on arch '%s'!"):format(raw_os_name, raw_arch_name)) local os_patterns = { ["windows"] = "Windows", diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua b/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua index d79b07312..445f485b5 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/profiler.lua @@ -77,7 +77,7 @@ new table using the matched key names: `profiler.configuration(overrides) ]] -local fu = require("file_util") +local fu = require("FileUtils") --[[ Configuration ]]-- diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua b/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua index c918062bf..dae0658ab 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/sock.lua @@ -33,8 +33,8 @@ local sock = { } local enet = require("enet") -local util = require("util") -local fu = require("file_util") +local Utils = require("Utils") +local fu = require("FileUtils") _G.Logger.info(_G.Logger.channels.initialize, "lua-enet version = master branch 21.10.2015") _G.Logger.info(_G.Logger.channels.initialize, "enet version = " .. enet.linked_version()) -- 1.3.17 @@ -71,7 +71,7 @@ local function zipTable(items, keys, event) if not key then error(("Missing data key for event '%s'! items = %s schema = %s") - :format(event, util.pformat(items), util.pformat(keys)), 2) + :format(event, Utils.pformat(items), Utils.pformat(keys)), 2) end data[key] = value @@ -150,7 +150,7 @@ function Logger:log(event, data) local time = os.date("%X") -- something like 24:59:59 local shortLine = ("%s [%s] %s"):format(time, event, data) local fullLine = ("%s [%s %s] %s"):format(time, self.source, event, - util.pformat(data)) --local fullLine = ("[%s][%s][%s] %s"):format(self.source, time, event, data) + Utils.pformat(data)) --local fullLine = ("[%s][%s][%s] %s"):format(self.source, time, event, data) -- The printed message may or may not be the full message local line = fullLine @@ -264,8 +264,8 @@ function Server:start(ip, port) if not self.host then --error("Failed to create the host. Is there another server running on :" .. self.port .. "?") self:log("", { "Failed to create the host. Is there another server running on :" .. self.port .. "?" }) - local pid = fu.getPidOfRunningEnetHostByPort() - fu.killProcess(pid) + local pid = fu.GetPidOfRunningEnetHostByPort() + fu.KillProcess(pid) return false end @@ -451,7 +451,7 @@ end function Server:sendToPeer(peer, event, data) local cpc = CustomProfiler.start("Server:sendToPeer") local networkMessageId = data[1] or data.networkMessageId - if util.IsEmpty(networkMessageId) then + if Utils.IsEmpty(networkMessageId) then error("networkMessageId is empty!", 3) end self.packetsSent = self.packetsSent + 1 @@ -967,7 +967,7 @@ end -- @param data The data to send. function Client:send(event, data) local networkMessageId = data[1] or data.networkMessageId - if util.IsEmpty(networkMessageId) then + if Utils.IsEmpty(networkMessageId) then error("networkMessageId is empty!", 3) end diff --git a/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua b/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua index a45063b5a..5594c34cf 100644 --- a/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua +++ b/mods/noita-mp/lua_modules/share/lua/5.1/zstd.lua @@ -88,7 +88,7 @@ local arr_utint8_t = ffi_typeof "uint8_t[?]" local ptr_zstd_inbuffer_t = ffi_typeof "ZSTD_inBuffer[1]" local ptr_zstd_outbuffer_t = ffi_typeof "ZSTD_outBuffer[1]" -local fu = require("file_util") +local fu = require("FileUtils") local zstd = ffi_load(fu.GetAbsolutePathOfNoitaRootDirectory() .. "\\mods\\noita-mp\\lua_modules\\lib\\lua\\5.1\\libzstd") local file = assert(io.popen("zstd -vV", "r")) local zstdVersion = file:read("*a") diff --git a/mods/noita-mp/noita-mp-3.0.0-3.rockspec b/mods/noita-mp/noita-mp-4.0.1-4.rockspec similarity index 51% rename from mods/noita-mp/noita-mp-3.0.0-3.rockspec rename to mods/noita-mp/noita-mp-4.0.1-4.rockspec index 9379e7d2b..79f64ab2a 100644 --- a/mods/noita-mp/noita-mp-3.0.0-3.rockspec +++ b/mods/noita-mp/noita-mp-4.0.1-4.rockspec @@ -1,6 +1,6 @@ rockspec_format = "3.0" package = "noita-mp" -version = "3.0.0-3" -- Needs to be updated manually and the same as in `.version` file. +version = "4.0.1-4" -- Needs to be updated manually and the same as in `.version` file. source = { url = "git+https://github.com/Ismoh/NoitaMP.git" } @@ -9,67 +9,75 @@ description = { license = "GNU GPL v3" } dependencies = { - "lua ~> 5.1", + "lua = 5.1", + "dkjson = 2.6-1", + "lua-path = 0.3.1-2", + "luacov = 0.15.0-1", + "luacov-coveralls = 0.2.3-1", "luafilesystem = 1.8.0-1", - "luafilesystem-ffi = scm-1", + "luajit-zstd = 0.2.3-1", + "luaposix = 36.1-1", + "luasocket = 3.1.0-1", "luaunit = 3.4-1", + "uuid = 0.3-1", + "winapi = 1.4.2-1" } build = { type = "builtin", modules = { -- change this to copy_directories? Does package path work without `modules`? - config = "config.lua", - ["files.scripts.DefaultBiomeMap"] = "files/scripts/DefaultBiomeMap.lua", - ["files.scripts.Ui"] = "files/scripts/Ui.lua", - ["files.scripts.biome.testingRoom"] = "files/scripts/biome/testingRoom.lua", - ["files.scripts.extensions.ffi_extensions"] = "files/scripts/extensions/ffi_extensions.lua", - ["files.scripts.extensions.globalExtensions"] = "files/scripts/extensions/globalExtensions.lua", - ["files.scripts.extensions.mathExtensions"] = "files/scripts/extensions/mathExtensions.lua", - ["files.scripts.extensions.string_extensions"] = "files/scripts/extensions/string_extensions.lua", - ["files.scripts.extensions.table_extensions"] = "files/scripts/extensions/table_extensions.lua", - ["files.scripts.init.init_"] = "files/scripts/init/init_.lua", - ["files.scripts.init.init_logger"] = "files/scripts/init/init_logger.lua", - ["files.scripts.init.init_package_loading"] = "files/scripts/init/init_package_loading.lua", - ["files.scripts.net.Client"] = "files/scripts/net/Client.lua", - ["files.scripts.net.Server"] = "files/scripts/net/Server.lua", - ["files.scripts.noita-components.dump_logger"] = "files/scripts/noita-components/dump_logger.lua", - ["files.scripts.noita-components.lua_component_enabler"] = "files/scripts/noita-components/lua_component_enabler.lua", - ["files.scripts.noita-components.name_tags"] = "files/scripts/noita-components/name_tags.lua", - ["files.scripts.noita-components.nuid_debug"] = "files/scripts/noita-components/nuid_debug.lua", - ["files.scripts.noita-components.nuid_updater"] = "files/scripts/noita-components/nuid_updater.lua", - ["files.scripts.util.CoroutineUtils"] = "files/scripts/util/CoroutineUtils.lua", - ["files.scripts.util.CustomProfiler"] = "files/scripts/util/CustomProfiler.lua", - ["files.scripts.util.EntityUtils"] = "files/scripts/util/EntityUtils.lua", - ["files.scripts.util.GlobalsUtils"] = "files/scripts/util/GlobalsUtils.lua", - ["files.scripts.util.NetworkUtils"] = "files/scripts/util/NetworkUtils.lua", - ["files.scripts.util.NetworkVscUtils"] = "files/scripts/util/NetworkVscUtils.lua", - ["files.scripts.util.NoitaComponentUtils"] = "files/scripts/util/NoitaComponentUtils.lua", - ["files.scripts.util.NuidUtils"] = "files/scripts/util/NuidUtils.lua", - ["files.scripts.util.file_util"] = "files/scripts/util/file_util.lua", - ["files.scripts.util.GuidUtils"] = "files/scripts/util/GuidUtils.lua", - ["files.scripts.util.util"] = "files/scripts/util/util.lua", - init = "init.lua", - modSettingsUpdater = "modSettingsUpdater.lua", - settings = "settings.lua", - ["tests.config_test"] = "tests/config_test.lua", - ["tests.files.scripts.extensions.string_extensions_test"] = "tests/files/scripts/extensions/string_extensions_test.lua", - ["tests.files.scripts.extensions.table_extensions_test"] = "tests/files/scripts/extensions/table_extensions_test.lua", - ["tests.files.scripts.init.init__test"] = "tests/files/scripts/init/init__test.lua", - ["tests.files.scripts.init.init_logger_test"] = "tests/files/scripts/init/init_logger_test.lua", - ["tests.files.scripts.init.init_package_loading_test"] = "tests/files/scripts/init/init_package_loading_test.lua", - ["tests.files.scripts.net.Server_test"] = "tests/files/scripts/net/Server_test.lua", - ["tests.files.scripts.util.EntityUtils_test"] = "tests/files/scripts/util/EntityUtils_test.lua", - ["tests.files.scripts.util.GlobalsUtils_test"] = "tests/files/scripts/util/GlobalsUtils_test.lua", - ["tests.files.scripts.util.NetworkUtils_test"] = "tests/files/scripts/util/NetworkUtils_test.lua", - ["tests.files.scripts.util.NetworkVscUtils_test"] = "tests/files/scripts/util/NetworkVscUtils_test.lua", - ["tests.files.scripts.util.NuidUtils_test"] = "tests/files/scripts/util/NuidUtils_test.lua", - ["tests.files.scripts.util.file_util_test"] = "tests/files/scripts/util/file_util_test.lua", - ["tests.files.scripts.util.GuidUtils_test"] = "tests/files/scripts/util/GuidUtils_test.lua", - ["tests.files.scripts.util.util_test"] = "tests/files/scripts/util/util_test.lua", - ["tests.init_test"] = "tests/init_test.lua", - ["tests._initializeUnitTests"] = "tests/_initializeUnitTests.lua" + config = "config.lua", + ["files.scripts.DefaultBiomeMap"] = "files/scripts/DefaultBiomeMap.lua", + ["files.scripts.Ui"] = "files/scripts/Ui.lua", + ["files.scripts.biome.testingRoom"] = "files/scripts/biome/testingRoom.lua", + ["files.scripts.extensions.ffiExtensions"] = "files/scripts/extensions/ffiExtensions.lua", + ["files.scripts.extensions.globalExtensions"] = "files/scripts/extensions/globalExtensions.lua", + ["files.scripts.extensions.mathExtensions"] = "files/scripts/extensions/mathExtensions.lua", + ["files.scripts.extensions.stringExtensions"] = "files/scripts/extensions/stringExtensions.lua", + ["files.scripts.extensions.tableExtensions"] = "files/scripts/extensions/tableExtensions.lua", + ["files.scripts.init.init_"] = "files/scripts/init/init_.lua", + ["files.scripts.init.init_logger"] = "files/scripts/init/init_logger.lua", + ["files.scripts.init.init_package_loading"] = "files/scripts/init/init_package_loading.lua", + ["files.scripts.net.Client"] = "files/scripts/net/Client.lua", + ["files.scripts.net.Server"] = "files/scripts/net/Server.lua", + ["files.scripts.noita-components.dump_logger"] = "files/scripts/noita-components/dump_logger.lua", + ["files.scripts.noita-components.lua_component_enabler"] = "files/scripts/noita-components/lua_component_enabler.lua", + ["files.scripts.noita-components.name_tags"] = "files/scripts/noita-components/name_tags.lua", + ["files.scripts.noita-components.nuid_debug"] = "files/scripts/noita-components/nuid_debug.lua", + ["files.scripts.noita-components.nuid_updater"] = "files/scripts/noita-components/nuid_updater.lua", + ["files.scripts.util.CoroutineUtils"] = "files/scripts/util/CoroutineUtils.lua", + ["files.scripts.util.CustomProfiler"] = "files/scripts/util/CustomProfiler.lua", + ["files.scripts.util.EntityUtils"] = "files/scripts/util/EntityUtils.lua", + ["files.scripts.util.GlobalsUtils"] = "files/scripts/util/GlobalsUtils.lua", + ["files.scripts.util.NetworkUtils"] = "files/scripts/util/NetworkUtils.lua", + ["files.scripts.util.NetworkVscUtils"] = "files/scripts/util/NetworkVscUtils.lua", + ["files.scripts.util.NoitaComponentUtils"] = "files/scripts/util/NoitaComponentUtils.lua", + ["files.scripts.util.NuidUtils"] = "files/scripts/util/NuidUtils.lua", + ["files.scripts.util.FileUtils"] = "files/scripts/util/FileUtils.lua", + ["files.scripts.util.GuidUtils"] = "files/scripts/util/GuidUtils.lua", + ["files.scripts.util.util"] = "files/scripts/util/util.lua", + init = "init.lua", + modSettingsUpdater = "modSettingsUpdater.lua", + settings = "settings.lua", + ["tests.config_test"] = "tests/config_test.lua", + ["tests.files.scripts.extensions.stringExtensions_test"] = "tests/files/scripts/extensions/stringExtensions_test.lua", + ["tests.files.scripts.extensions.tableExtensions_test"] = "tests/files/scripts/extensions/tableExtensions_test.lua", + ["tests.files.scripts.init.init__test"] = "tests/files/scripts/init/init__test.lua", + ["tests.files.scripts.init.init_logger_test"] = "tests/files/scripts/init/init_logger_test.lua", + ["tests.files.scripts.init.init_package_loading_test"] = "tests/files/scripts/init/init_package_loading_test.lua", + ["tests.files.scripts.net.Server_test"] = "tests/files/scripts/net/Server_test.lua", + ["tests.files.scripts.util.EntityUtils_test"] = "tests/files/scripts/util/EntityUtils_test.lua", + ["tests.files.scripts.util.GlobalsUtils_test"] = "tests/files/scripts/util/GlobalsUtils_test.lua", + ["tests.files.scripts.util.NetworkUtils_test"] = "tests/files/scripts/util/NetworkUtils_test.lua", + ["tests.files.scripts.util.NetworkVscUtils_test"] = "tests/files/scripts/util/NetworkVscUtils_test.lua", + ["tests.files.scripts.util.NuidUtils_test"] = "tests/files/scripts/util/NuidUtils_test.lua", + ["tests.files.scripts.util.FileUtils_test"] = "tests/files/scripts/util/FileUtils_test.lua", + ["tests.files.scripts.util.GuidUtils_test"] = "tests/files/scripts/util/GuidUtils_test.lua", + ["tests.files.scripts.util.util_test"] = "tests/files/scripts/util/util_test.lua", + ["tests.init_test"] = "tests/init_test.lua", + ["tests.unitTestRunner"] = "tests/unitTestRunner.lua" }, } test = { type = "command", - script = "tests/_initializeUnitTests.lua", + script = "tests/unitTestRunner.lua", } diff --git a/mods/noita-mp/tests/config_test.lua b/mods/noita-mp/tests/config_test.lua deleted file mode 100644 index dc7690ad4..000000000 --- a/mods/noita-mp/tests/config_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestConfig = {} - -function TestConfig:setUp() - -end - -function TestConfig:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua b/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua index dbf4d663f..264f047d4 100644 --- a/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua +++ b/mods/noita-mp/tests/files/scripts/NoitaMpSettings_test.lua @@ -1,11 +1,4 @@ ---- ---- Created by Ismoh. ---- DateTime: 14.02.2023 12:01 ---- -local params = ... - -local lu = require("luaunit") -local fu = require("file_util") +local fu = require("FileUtils") TestNoitaMpSettings = {} @@ -17,7 +10,7 @@ end function TestNoitaMpSettings:testClearAndCreateSettings() NoitaMpSettings.clearAndCreateSettings() - local files = fu.getAllFilesInDirectory(fu.getAbsolutePathOfNoitaMpSettingsDirectory(), "json") + local files = fu.GetAllFilesInDirectory(fu.GetAbsolutePathOfNoitaMpSettingsDirectory(), "json") lu.assertEquals(files, {}, "Settings directory wasn't empty!") end @@ -42,6 +35,4 @@ function TestNoitaMpSettings:testGetSetting() NoitaMpSettings.writeSettings("name", name) local nameSetting = NoitaMpSettings.getSetting("name") lu.assertEquals(nameSetting, name) -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua b/mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua similarity index 93% rename from mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua rename to mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua index 0c0c2ae38..535a73c2e 100644 --- a/mods/noita-mp/tests/files/scripts/extensions/string_extensions_test.lua +++ b/mods/noita-mp/tests/files/scripts/extensions/stringExtensions_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestStringExtensions = {} function TestStringExtensions:setUp() @@ -32,5 +28,3 @@ function TestStringExtensions:testContains() lu.assertIsTrue(string.contains("noita-mp.log_level_testing", "noita-mp.log_level_")) lu.assertIsFalse(string.contains("ASDF", "Noita is nice, but abandoned!")) end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua b/mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua similarity index 85% rename from mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua rename to mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua index b10eb29f3..21cea47ac 100644 --- a/mods/noita-mp/tests/files/scripts/extensions/table_extensions_test.lua +++ b/mods/noita-mp/tests/files/scripts/extensions/tableExtensions_test.lua @@ -1,25 +1,7 @@ -local params = ... - -local lu = require("luaunit") - TestTableExtensions = {} function TestTableExtensions:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedModSettingGet = ModSettingGet - ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "off", "OFF" } - end - if id == "noita-mp.name" then - return "testName" - end - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - mockedModSettingGet(id) - end + end function TestTableExtensions:tearDown() @@ -120,6 +102,4 @@ function TestTableExtensions:testContentToString() local expectedStr4 = "test,guid,1234,3,1.2,3.4,0.5,12,3" local str4 = table.contentToString(tbl4) lu.assertEquals(str4, expectedStr4) -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/init/init__test.lua b/mods/noita-mp/tests/files/scripts/init/init__test.lua index 34849eb0e..8f08e7508 100644 --- a/mods/noita-mp/tests/files/scripts/init/init__test.lua +++ b/mods/noita-mp/tests/files/scripts/init/init__test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestInit_ = {} function TestInit_:setUp() @@ -11,5 +7,3 @@ end function TestInit_:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua b/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua deleted file mode 100644 index c3f84168a..000000000 --- a/mods/noita-mp/tests/files/scripts/init/init_logger_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestInitLogger = {} - -function TestInitLogger:setUp() - -end - -function TestInitLogger:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua b/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua index 78ed3e7dd..9113aaf38 100644 --- a/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua +++ b/mods/noita-mp/tests/files/scripts/init/init_package_loading_test.lua @@ -1,6 +1,3 @@ -local params = ... - -local lu = require("luaunit") TestInitPackageLoading = {} @@ -10,6 +7,4 @@ end function TestInitPackageLoading:tearDown() -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/net/Server_test.lua b/mods/noita-mp/tests/files/scripts/net/Server_test.lua index 3d3d72753..0963cd58d 100644 --- a/mods/noita-mp/tests/files/scripts/net/Server_test.lua +++ b/mods/noita-mp/tests/files/scripts/net/Server_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestServer = {} function TestServer:setUp() @@ -15,5 +11,3 @@ end function TestServer:test() -- end - -lu.LuaUnit.run(params) \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua b/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua index 73cd10b10..7a1fd36b7 100644 --- a/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/EntityCache_test.lua @@ -1,7 +1,3 @@ -local params = ... -local lu = require("luaunit") -require("luaExtensions") - TestEntityCache = {} local guid1 = GuidUtils:getGuid() @@ -103,6 +99,4 @@ function TestEntityCache:testUsage() EntityCache.delete(4) EntityCache.delete(5) -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua index 503953a83..bb56d6855 100644 --- a/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/EntityUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestEntityUtils = {} function TestEntityUtils:setUp() @@ -11,5 +7,3 @@ end function TestEntityUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/file_util_test.lua b/mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua similarity index 79% rename from mods/noita-mp/tests/files/scripts/util/file_util_test.lua rename to mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua index 7bbe7ee51..714152a1d 100644 --- a/mods/noita-mp/tests/files/scripts/util/file_util_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/FileUtils_test.lua @@ -1,26 +1,8 @@ -local params = ... - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGet = ModSettingGet -ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "trace, debug, info, warn", "TRACE" } - end - - if mockedModSettingGet then - mockedModSettingGet(id) - end - - error(("Mod setting '%s' is not mocked! Add it!"):format(id), 2) -end - -local lu = require("luaunit") -local fu = require("file_util") - -TestFileUtil = {} +local os_name = require("os_name") +local fu = require("FileUtils") +TestFileUtil = {} function TestFileUtil:setUp() - -- Mock Noita Api global functions _G.DebugGetIsDevBuild = function() return false @@ -32,7 +14,20 @@ function TestFileUtil:setUp() end function TestFileUtil:tearDown() - + -- Make sure OS detection isn't broken, when changed in tests + _G.is_windows = true + _G.is_linux = false + _G.pathSeparator = tostring(package.config:sub(1, 1)) + local current_platform, current_architecture = os_name.getOS() + if current_platform == "Windows" then + _G.is_windows = true + _G.is_linux = false + _G.pathSeparator = "\\" + else + _G.is_windows = false + _G.is_linux = true + _G.pathSeparator = "/" + end end ---------------------------------------------------------------------------------------------------- @@ -40,58 +35,45 @@ end ---------------------------------------------------------------------------------------------------- function TestFileUtil:testReplacePathSeparatorOnWindows() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux + local old_is_windows = _G.is_windows + local old_is_linux = _G.is_linux local old_pathSeparator = _G.pathSeparator - _G.is_windows = true -- TODO: is there a better way to mock? - _G.is_linux = false -- TODO: is there a better way to mock? + _G.is_windows = true -- TODO: is there a better way to mock? + _G.is_linux = false -- TODO: is there a better way to mock? _G.pathSeparator = "\\" -- TODO: is there a better way to mock? - local path_unix = "/test/path/123" - local path_windows = fu.ReplacePathSeparator(path_unix) + local path_unix = "/test/path/123" + local path_windows = fu.ReplacePathSeparator(path_unix) lu.assertNotEquals(path_unix, path_windows) lu.assertEquals([[\test\path\123]], path_windows) - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux + _G.is_windows = old_is_windows + _G.is_linux = old_is_linux _G.pathSeparator = old_pathSeparator end function TestFileUtil:testReplacePathSeparatorOnUnix() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux + local old_is_windows = _G.is_windows + local old_is_linux = _G.is_linux local old_pathSeparator = _G.pathSeparator - _G.is_windows = false -- TODO: is there a better way to mock? - _G.is_linux = true -- TODO: is there a better way to mock? + _G.is_windows = false -- TODO: is there a better way to mock? + _G.is_linux = true -- TODO: is there a better way to mock? _G.pathSeparator = "/" -- TODO: is there a better way to mock? - local path_windows = "\\test\\path\\123" - local path_unix = fu.ReplacePathSeparator(path_windows) + local path_windows = "\\test\\path\\123" + local path_unix = fu.ReplacePathSeparator(path_windows) lu.assertNotEquals(path_windows, path_unix) lu.assertEquals("/test/path/123", path_unix) - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux + _G.is_windows = old_is_windows + _G.is_linux = old_is_linux _G.pathSeparator = old_pathSeparator end -function TestFileUtil:testReplacePathSeparatorUnknownOs() - local old_is_windows = _G.is_windows - local old_is_linux = _G.is_linux - - _G.is_windows = false -- TODO: is there a better way to mock? - _G.is_linux = false -- TODO: is there a better way to mock? - - lu.assertErrorMsgContains("file_util.lua | Unable to detect OS", fu.ReplacePathSeparator, "path doesnt matter") - - _G.is_windows = old_is_windows - _G.is_linux = old_is_linux -end - function TestFileUtil:testRemoveTrailingPathSeparator() local path = tostring(_G.pathSeparator .. "persistent" .. _G.pathSeparator .. "flags" .. _G.pathSeparator) local result = fu.RemoveTrailingPathSeparator(path) @@ -118,7 +100,7 @@ function TestFileUtil:testSetAbsolutePathOfNoitaRootDirectoryUnknownOs() _G.is_windows = false -- TODO: is there a better way to mock? _G.is_linux = false -- TODO: is there a better way to mock? - lu.assertErrorMsgContains("file_util.lua | Unable to detect OS", fu.SetAbsolutePathOfNoitaRootDirectory, + lu.assertErrorMsgContains("FileUtils.lua | Unable to detect OS", fu.SetAbsolutePathOfNoitaRootDirectory, "path doesnt matter") _G.is_windows = old_is_windows @@ -126,6 +108,8 @@ function TestFileUtil:testSetAbsolutePathOfNoitaRootDirectoryUnknownOs() end function TestFileUtil:testGetAbsolutePathOfNoitaRootDirectory() + Logger.trace(Logger.channels.testing, + ("Need to verify absolute path of root noita: %s"):format(fu.GetAbsolutePathOfNoitaRootDirectory())) lu.assertStrContains(fu.GetAbsolutePathOfNoitaRootDirectory(), _G.pathSeparator) -- TODO: Need a better test for this! end @@ -215,9 +199,9 @@ end ---------------------------------------------------------------------------------------------------- function TestFileUtil:testExists() - lu.assertNotIsTrue(fu.exists("nonexistingfile.asdf")) - lu.assertErrorMsgContains("is not type of string!", fu.exists) - lu.assertIsTrue(fu.exists(fu.GetAbsoluteDirectoryPathOfNoitaMP() .. "/mod.xml")) + lu.assertNotIsTrue(fu.Exists("nonexistingfile.asdf")) + lu.assertErrorMsgContains("is not type of string!", fu.Exists) + lu.assertIsTrue(fu.Exists(fu.GetAbsoluteDirectoryPathOfNoitaMP() .. "/mod.xml")) end function TestFileUtil:testIsFile() @@ -245,7 +229,7 @@ function TestFileUtil:testWriteBinaryFile() local full_path = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/write-temporary-binary-test-file.txt" fu.WriteBinaryFile(full_path, "File Content") - lu.assertIsTrue(fu.exists(full_path)) + lu.assertIsTrue(fu.Exists(full_path)) os.remove(full_path) end @@ -262,7 +246,7 @@ function TestFileUtil:testWriteFile() local full_path = fu.GetAbsolutePathOfNoitaRootDirectory() .. "/write-temporary-test-file.txt" fu.WriteFile(full_path, "File Content") - lu.assertIsTrue(fu.exists(full_path)) + lu.assertIsTrue(fu.Exists(full_path)) os.remove(full_path) end @@ -283,14 +267,12 @@ end function TestFileUtil:testExists7zip() local old = _G.seven_zip _G.seven_zip = false -- mock - lu.assertNotIsTrue(fu.exists7zip()) + lu.assertNotIsTrue(fu.Exists7zip()) _G.seven_zip = true -- mock - lu.assertIsTrue(fu.exists7zip()) + lu.assertIsTrue(fu.Exists7zip()) _G.seven_zip = old end function TestFileUtil:testCreate7zipArchive() --fu.Create7zipArchive() -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua index 2b8be53a7..e99d41bad 100644 --- a/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/GlobalsUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestGlobalsUtils = {} function TestGlobalsUtils:setUp() @@ -11,5 +7,3 @@ end function TestGlobalsUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua index db33101fb..a6f4d5fa5 100644 --- a/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/GuidUtils_test.lua @@ -1,17 +1,7 @@ -local params = ... - -local lu = require("luaunit") -local GuidUtils = require("GuidUtils") - TestGuidUtils = {} function TestGuidUtils:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedDebugGetIsDevBuild = DebugGetIsDevBuild - -- Mock Noita Api global functions - DebugGetIsDevBuild = function() - return DebugGetIsDevBuild or false - end + end function TestGuidUtils:tearDown() @@ -45,5 +35,3 @@ function TestGuidUtils:testToNumber() lu.assertNotIsNil(number) lu.assertIsTrue(type(number) == "number", "GuidUtils.toNumber didn't return a number!") end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/Logger_test.lua b/mods/noita-mp/tests/files/scripts/util/Logger_test.lua index 06536249b..95647e64f 100644 --- a/mods/noita-mp/tests/files/scripts/util/Logger_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/Logger_test.lua @@ -1,29 +1,18 @@ ---- ---- Created by Ismoh-PC. ---- DateTime: 22.01.2023 01:15 ---- -local params = ... - -local lu = require("luaunit") - TestLogger = {} TestLogger.mockedLogLevel = { "trace, debug, info, warn", "TRACE" } +local globalModSettingsGet = ModSettingGet function TestLogger:setUp() - -- Make absolutely sure, that the already mocked Noita API function is not overwritten - local mockedModSettingGet = ModSettingGet - ---@param id string ModSettingGet = function(id) if string.contains(id, "noita-mp.log_level_") then return TestLogger.mockedLogLevel end - mockedModSettingGet(id) + globalModSettingsGet(id) end - end function TestLogger:tearDown() - + ModSettingGet = globalModSettingsGet end function TestLogger:errors() @@ -78,5 +67,3 @@ function TestLogger:testWarn() lu.assertIsFalse(Logger.info(Logger.channels.testing, "This should NOT be logged!")) lu.assertIsTrue(Logger.warn(Logger.channels.testing, "This should be logged, warn level!")) end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua index c802d7565..cbc12f146 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkCacheUtils_test.lua @@ -1,55 +1,3 @@ ---- ---- Created by Ismoh-PC. ---- DateTime: 23.01.2023 17:37 ---- -local params = ... - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGetNextValue = ModSettingGetNextValue -ModSettingGetNextValue = function(id) - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - if mockedModSettingGetNextValue then - mockedModSettingGetNextValue(id) - end - - error(("Trying to access '%s', but it isn't mocked yet!"):format(id), 2) -end - -if not ModSettingSetNextValue then - ModSettingSetNextValue = function(id) - Logger.trace(Logger.channels.testing, ("Mocked ModSettingSetNextValue id %s."):format(id)) - return id - end -end - ---- Make absolutely sure, that the already mocked Noita API function is not overwritten -local mockedModSettingGet = ModSettingGet -ModSettingGet = function(id) - if string.contains(id, "noita-mp.log_level_") then - return { "trace, debug, info, warn", "TRACE" } - end - if id == "noita-mp.name" then - return "noita-mp.name" - end - if id == "noita-mp.guid" then - return GuidUtils:getGuid() - end - - if mockedModSettingGet then - mockedModSettingGet(id) - end - - error(("Mod setting '%s' is not mocked! Add it!"):format(id), 2) -end - --- [[ require ]] -- -require("NetworkUtils") -require("NetworkCacheUtils") -require("luaExtensions") -require("CustomProfiler") if not Server then require("Server") end @@ -57,9 +5,6 @@ if not Client then require("Client") end -local lu = require("luaunit") - --- [[ Test ]] -- TestNetworkCacheUtils = {} --- Setup function for each test. @@ -112,6 +57,4 @@ end function TestNetworkCacheUtils:testGet() --local guid = GuidUtils:getGuid() --NetworkCacheUtils.get(guid, networkMessageId, event) -end - -lu.LuaUnit.run(params) \ No newline at end of file +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua index c7ad444e9..0d2b97d10 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkUtils_test.lua @@ -1,19 +1,3 @@ -local params = ... - --- [[ Mock Noita API functions, which are needed before/during require is used ]] -- -mockedModSettingGetNextValue = ModSettingGetNextValue -ModSettingGetNextValue = function(id) - if mockedModSettingGetNextValue then - mockedModSettingGetNextValue(id) - end -end - --- [[ require ]] -- -require("luaExtensions") -require("EntityUtils") -require("NetworkUtils") -require("GuidUtils") -require("CustomProfiler") if not Server then require("Server") end @@ -21,10 +5,6 @@ if not Client then require("Client") end -local lu = require("luaunit") -local util = require("util") - --- [[ Test ]] -- TestNetworkUtils = {} --- Setup function for each test. @@ -115,7 +95,7 @@ function TestNetworkUtils:testAlreadySentConnect2() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -167,7 +147,7 @@ function TestNetworkUtils:testAlreadySentDisconnect2() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -221,7 +201,7 @@ function TestNetworkUtils:testAlreadySentSeed() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -241,13 +221,13 @@ function TestNetworkUtils:testAlreadySentSeed() end function TestNetworkUtils:testAlreadySentPlayerInfo() - local fu = require("file_util") + local fu = require("FileUtils") -- [[ Prepare mocked data for sending PlayerInfo! ]] -- local networkMessageId = NetworkUtils.getNextNetworkMessageId() local name = "ClientOwnerName" local guid = GuidUtils:getGuid() - local version = fu.getVersionByFile() + local version = fu.GetVersionByFile() local nuid = nil local data = { @@ -278,7 +258,7 @@ function TestNetworkUtils:testAlreadySentPlayerInfo() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -329,7 +309,7 @@ function TestNetworkUtils:testAlreadySentNewGuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -398,7 +378,7 @@ function TestNetworkUtils:testAlreadySentNewNuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -463,7 +443,7 @@ function TestNetworkUtils:testAlreadySentNeedNuidShouldReturnTrue() filename, health, EntityUtils.isEntityPolymorphed(entityId) } - print(("Let's see if this was already sent: entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Let's see if this was already sent: entity %s with data %s"):format(entityId, Utils.pformat(data))) -- [[ Check if the message was already sent ]] -- lu.assertIs(NetworkUtils.alreadySent(Client, "needNuid", data), true, "The message was already sent, but the function NetworkUtils.alreadySent() returned false!") @@ -519,7 +499,7 @@ function TestNetworkUtils:testAlreadySentNeedNuidShouldReturnFalse() filename, health, EntityUtils.isEntityPolymorphed(entityId) } - print(("Let's see if this WASN'T already sent: entity %s with data %s"):format(entityId, util.pformat(data))) + print(("Let's see if this WASN'T already sent: entity %s with data %s"):format(entityId, Utils.pformat(data))) -- [[ Check if the message WASN'T already sent ]] -- lu.assertIs(NetworkUtils.alreadySent(Client, event, data), false, "The message WASN'T already sent, but the function NetworkUtils.alreadySent() returned true!") @@ -554,7 +534,7 @@ function TestNetworkUtils:testAlreadySentLostNuid() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -604,13 +584,13 @@ function TestNetworkUtils:testAlreadySentDeadNuids() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end local originalDestroyByNuid = EntityUtils.destroyByNuid EntityUtils.destroyByNuid = function(peer, deadNuid) Logger.trace(Logger.channels.testing, ("Mocked 'EntityUtils.destroyByNuid' on '%s' destroyed a dead nuid '%s'!") - :format(util.pformat(peer), deadNuid)) + :format(Utils.pformat(peer), deadNuid)) end require("GlobalsUtils") local originalRemoveDeadNuid = GlobalsUtils.removeDeadNuid @@ -691,7 +671,7 @@ function TestNetworkUtils:testAlreadySentNeedModList() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -759,7 +739,7 @@ function TestNetworkUtils:testAlreadySentNeedModContent() Client.connection.send = function(serializedMessage, sendChannel, sendMode) Logger.trace(Logger.channels.testing, ("Mocked 'self.connection:send(serializedMessage %s, self.sendChannel, self.sendMode)' executed!") - :format(util.pformat(serializedMessage))) + :format(Utils.pformat(serializedMessage))) end -- [[ Send message ]] -- @@ -776,6 +756,4 @@ function TestNetworkUtils:testAlreadySentNeedModContent() local alreadySent = NetworkUtils.alreadySent(Client, event, data) lu.assertIsTrue(alreadySent, "NetworkMessage was already send, but NetworkUtils.alreadySent didn't find it in the cache?") -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua index ed98fe9d2..ca4c16160 100644 --- a/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NetworkVscUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestNetworkVscUtils = {} function TestNetworkVscUtils:setUp() @@ -11,5 +7,3 @@ end function TestNetworkVscUtils:tearDown() end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua b/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua index bab5b6cb5..d3b962393 100644 --- a/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/NuidUtils_test.lua @@ -1,7 +1,3 @@ -local params = ... - -local lu = require("luaunit") - TestNuidUtils = {} function TestNuidUtils:setUp() @@ -10,6 +6,4 @@ end function TestNuidUtils:tearDown() -end - -lu.LuaUnit.run(params) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/files/scripts/util/util_test.lua b/mods/noita-mp/tests/files/scripts/util/Utils_test.lua similarity index 64% rename from mods/noita-mp/tests/files/scripts/util/util_test.lua rename to mods/noita-mp/tests/files/scripts/util/Utils_test.lua index b7e028e7a..f1cdbbf47 100644 --- a/mods/noita-mp/tests/files/scripts/util/util_test.lua +++ b/mods/noita-mp/tests/files/scripts/util/Utils_test.lua @@ -1,8 +1,3 @@ -local params = ... - -local lu = require("luaunit") -local util = require("util") - TestUtil = {} function TestUtil:setUp() @@ -14,11 +9,11 @@ function TestUtil:tearDown() end function TestUtil:testSleep() - lu.assertErrorMsgContains("Unable to wait if parameter 'seconds' isn't a number:", util.Sleep, "seconds") + lu.assertErrorMsgContains("Unable to wait if parameter 'seconds' isn't a number:", Utils.Sleep, "seconds") local seconds_to_wait = 4 local timestamp_before = os.clock() - util.Sleep(seconds_to_wait) + Utils.Sleep(seconds_to_wait) local timestamp_after = os.clock() local diff = timestamp_before + seconds_to_wait Logger.debug(Logger.channels.testing,("timestamp_before=%s, timestamp_after=%s, diff=%s"):format(timestamp_before, timestamp_after, diff)) @@ -28,11 +23,9 @@ end function TestUtil:testIsEmpty() local tbl = {} table.insert(tbl, "1234") - lu.assertIsFalse(util.IsEmpty(tbl)) - - lu.assertIsTrue(util.IsEmpty(nil)) - lu.assertIsTrue(util.IsEmpty("")) - lu.assertIsTrue(util.IsEmpty({})) -end + lu.assertIsFalse(Utils.IsEmpty(tbl)) -lu.LuaUnit.run(params) + lu.assertIsTrue(Utils.IsEmpty(nil)) + lu.assertIsTrue(Utils.IsEmpty("")) + lu.assertIsTrue(Utils.IsEmpty({})) +end \ No newline at end of file diff --git a/mods/noita-mp/tests/init_test.lua b/mods/noita-mp/tests/init_test.lua deleted file mode 100644 index d21eeed7a..000000000 --- a/mods/noita-mp/tests/init_test.lua +++ /dev/null @@ -1,15 +0,0 @@ -local params = ... - -local lu = require("luaunit") - -TestInit = {} - -function TestInit:setUp() - -end - -function TestInit:tearDown() - -end - -lu.LuaUnit.run(params) diff --git a/mods/noita-mp/tests/_initializeUnitTests.lua b/mods/noita-mp/tests/unitTestRunner.lua similarity index 88% rename from mods/noita-mp/tests/_initializeUnitTests.lua rename to mods/noita-mp/tests/unitTestRunner.lua index 60cae0d40..dd5450876 100644 --- a/mods/noita-mp/tests/_initializeUnitTests.lua +++ b/mods/noita-mp/tests/unitTestRunner.lua @@ -1,14 +1,15 @@ _G.isTestLuaContext = true - +local params = ... dofile("../noita-mp/files/scripts/init/init_package_loading.lua") local lfs = require("lfs") +lu = require("luaunit") --- Returns a list of all files in a directory function getAllFilesInside(folder) local files = {} for entry in lfs.dir(folder) do - if entry ~= "." and entry ~= ".." and not entry:find("_initializeUnitTests") then + if entry ~= "." and entry ~= ".." and not entry:find("unitTestRunner") then local path = folder .. "/" .. entry local mode = lfs.attributes(path, "mode") if mode == "file" then @@ -41,14 +42,14 @@ if not ModSettingGet then end if id == "noita-mp.name" then local name = MinaUtils.getLocalMinaName() - if util.IsEmpty(name) then + if Utils.IsEmpty(name) then name = "initializeUnitTests" end return name end if id == "noita-mp.guid" then local guid = MinaUtils.getLocalMinaGuid() - if util.IsEmpty(guid) then + if Utils.IsEmpty(guid) then guid = GuidUtils:getGuid() end return guid @@ -93,10 +94,8 @@ end dofile("mods/noita-mp/files/scripts/init/init_.lua") for _, testFile in ipairs(testFiles) do - print("") - print("") - print("##################################################") - print("Running test: " .. testFile) - --dofile(testFile) - assert(loadfile(testFile))("--verbose", "--error", "--failure") -end \ No newline at end of file + dofile(testFile) + print("Loaded test " .. _ .. " " .. testFile) +end + +lu.LuaUnit.run(params)