diff --git a/.dockerignore b/.dockerignore
index 2f1255d2c0..f46d814c7d 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,2 +1,12 @@
+/.git/
+/.github/
+/.idea/
+/.vs/
+/android/
/build/
+/cmake-build*
+/vc17/
Dockerfile
+*.dll
+*.exe
+*.pdb
diff --git a/README.md b/README.md
index ac3670d00f..50cf96fa51 100644
--- a/README.md
+++ b/README.md
@@ -468,6 +468,7 @@ Beyond of it's flexibility with scripts, otclient comes with tons of other featu
- Module Oufit
- Placeholder
- UIGraph
+- keybinds
## The Mobile Project
The Mobile Project
diff --git a/data/images/ui/icon-edit.png b/data/images/ui/icon-edit.png
new file mode 100644
index 0000000000..f9b810a70d
Binary files /dev/null and b/data/images/ui/icon-edit.png differ
diff --git a/data/styles/10-scrollbars.otui b/data/styles/10-scrollbars.otui
index 88beafb2bb..130c0a9b8b 100644
--- a/data/styles/10-scrollbars.otui
+++ b/data/styles/10-scrollbars.otui
@@ -186,3 +186,23 @@ HorizontalQtScrollBar < UIScrollBar
image-clip: 54 10 12 12
HorizontalScrollBarQtSlider
+
+SmallButton < UIButton
+ size: 106 20
+ font: cipsoftFont
+ text-offset: 0 2
+ image-source: /images/ui/button
+ image-clip: 0 0 22 23
+ image-border: 3
+ padding: 5 10 5 10
+ change-cursor-image: true
+ cursor: pointer
+ color: #ffffff
+ $hover !disabled:
+ image-clip: 0 23 22 23
+ $pressed:
+ image-clip: 0 46 22 23
+ text-offset: 1 2
+ $disabled:
+ color: #ffffff88
+ change-cursor-image: false
diff --git a/modules/client_debug_info/debug_info.lua b/modules/client_debug_info/debug_info.lua
index 986989665a..57a90e0c47 100644
--- a/modules/client_debug_info/debug_info.lua
+++ b/modules/client_debug_info/debug_info.lua
@@ -11,7 +11,13 @@ function init()
debugInfoWindow = g_ui.displayUI('debug_info')
debugInfoWindow:hide()
- g_keyboard.bindKeyDown('Ctrl+Alt+D', toggle)
+ Keybind.new("Debug", "Toggle Stats", "Ctrl+Alt+D", "")
+ Keybind.bind("Debug", "Toggle Stats", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
updateEvent = scheduleEvent(update, 2000)
end
@@ -20,7 +26,7 @@ function terminate()
debugInfoWindow:destroy()
debugInfoButton:destroy()
- g_keyboard.unbindKeyDown('Ctrl+Alt+D')
+ Keybind.delete("Debug", "Toggle Stats")
removeEvent(updateEvent)
end
diff --git a/modules/client_entergame/entergame.lua b/modules/client_entergame/entergame.lua
index a8efcb3841..f99e2d5a47 100644
--- a/modules/client_entergame/entergame.lua
+++ b/modules/client_entergame/entergame.lua
@@ -127,7 +127,13 @@ end
-- public functions
function EnterGame.init()
enterGame = g_ui.displayUI('entergame')
- g_keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow)
+ Keybind.new("Misc.", "Change Character", "Ctrl+G", "")
+ Keybind.bind("Misc.", "Change Character", {
+ {
+ type = KEY_DOWN,
+ callback = EnterGame.openWindow,
+ }
+ })
local account = g_settings.get('account')
local password = g_settings.get('password')
@@ -259,7 +265,7 @@ function EnterGame.firstShow()
end
function EnterGame.terminate()
- g_keyboard.unbindKeyDown('Ctrl+G')
+ Keybind.delete("Misc.", "Change Character")
disconnect(clientBox, {
onOptionChange = EnterGame.onClientVersionChange
diff --git a/modules/client_options/data_options.lua b/modules/client_options/data_options.lua
index 30e3e3b968..5b56bd01ce 100644
--- a/modules/client_options/data_options.lua
+++ b/modules/client_options/data_options.lua
@@ -444,4 +444,10 @@ return {
end, 100)
end
},
+ autoSwitchPreset = false,
+ listKeybindsPanel = {
+ action = function(value, options, controller, panels, extraWidgets)
+ listKeybindsComboBox(value)
+ end
+ },
}
diff --git a/modules/client_options/keybins.lua b/modules/client_options/keybins.lua
new file mode 100644
index 0000000000..fa8abf2103
--- /dev/null
+++ b/modules/client_options/keybins.lua
@@ -0,0 +1,756 @@
+local actionNameLimit = 39
+local changedOptions = {}
+local changedKeybinds = {}
+local changedHotkeys = {}
+local presetWindow = nil
+local actionSearchEvent
+local keyEditWindow = nil
+local chatModeGroup
+
+-- controls and keybinds
+function addNewPreset()
+ presetWindow:setText(tr('Add hotkey preset'))
+
+ presetWindow.info:setText(tr('Enter a name for the new preset:'))
+
+ presetWindow.field:clearText()
+ presetWindow.field:show()
+ presetWindow.field:focus()
+
+ presetWindow:setWidth(360)
+
+ presetWindow.action = 'add'
+
+ presetWindow:show()
+ presetWindow:raise()
+ presetWindow:focus()
+
+ controller.ui:hide()
+end
+
+function copyPreset()
+ presetWindow:setText(tr('Copy hotkey preset'))
+
+ presetWindow.info:setText(tr('Enter a name for the new preset:'))
+
+ presetWindow.field:clearText()
+ presetWindow.field:show()
+ presetWindow.field:focus()
+
+ presetWindow.action = 'copy'
+
+ presetWindow:setWidth(360)
+ presetWindow:show()
+ presetWindow:raise()
+ presetWindow:focus()
+
+ controller.ui:hide()
+end
+
+function renamePreset()
+ presetWindow:setText(tr('Rename hotkey preset'))
+
+ presetWindow.info:setText(tr('Enter a name for the preset:'))
+
+ presetWindow.field:setText(panels.keybindsPanel.presets.list:getCurrentOption().text)
+ presetWindow.field:setCursorPos(1000)
+ presetWindow.field:show()
+ presetWindow.field:focus()
+
+ presetWindow.action = 'rename'
+
+ presetWindow:setWidth(360)
+ presetWindow:show()
+ presetWindow:raise()
+ presetWindow:focus()
+
+ controller.ui:hide()
+end
+
+function removePreset()
+ presetWindow:setText(tr('Warning'))
+
+ presetWindow.info:setText(tr('Do you really want to delete the hotkey preset %s?',
+ panels.keybindsPanel.presets.list:getCurrentOption().text))
+ presetWindow.field:hide()
+ presetWindow.action = 'remove'
+
+ presetWindow:setWidth(presetWindow.info:getTextSize().width + presetWindow:getPaddingLeft() +
+ presetWindow:getPaddingRight())
+ presetWindow:show()
+ presetWindow:raise()
+ presetWindow:focus()
+
+ controller.ui:hide()
+end
+
+function okPresetWindow()
+ local presetName = presetWindow.field:getText():trim()
+ local selectedPreset = panels.keybindsPanel.presets.list:getCurrentOption().text
+
+ presetWindow:hide()
+ show()
+
+ if presetWindow.action == 'add' then
+ Keybind.newPreset(presetName)
+ panels.keybindsPanel.presets.list:addOption(presetName)
+ panels.keybindsPanel.presets.list:setCurrentOption(presetName)
+ elseif presetWindow.action == 'copy' then
+ if not Keybind.copyPreset(selectedPreset, presetName) then
+ return
+ end
+
+ panels.keybindsPanel.presets.list:addOption(presetName)
+ panels.keybindsPanel.presets.list:setCurrentOption(presetName)
+ elseif presetWindow.action == 'rename' then
+ if selectedPreset ~= presetName then
+ panels.keybindsPanel.presets.list:updateCurrentOption(presetName)
+ if changedOptions['currentPreset'] then
+ changedOptions['currentPreset'].value = presetName
+ end
+ Keybind.renamePreset(selectedPreset, presetName)
+ end
+ elseif presetWindow.action == 'remove' then
+ if Keybind.removePreset(selectedPreset) then
+ panels.keybindsPanel.presets.list:removeOption(selectedPreset)
+ end
+ end
+end
+
+function cancelPresetWindow()
+ presetWindow:hide()
+ show()
+end
+
+function editKeybindKeyDown(widget, keyCode, keyboardModifiers)
+ keyEditWindow.keyCombo:setText(determineKeyComboDesc(keyCode,
+ keyEditWindow.alone:isVisible() and KeyboardNoModifier or keyboardModifiers))
+
+ local category = nil
+ local action = nil
+
+ if keyEditWindow.keybind then
+ category = keyEditWindow.keybind.category
+ action = keyEditWindow.keybind.action
+ end
+
+ local keyCombo = keyEditWindow.keyCombo:getText()
+ local keyUsed = Keybind.isKeyComboUsed(keyCombo, category, action, getChatMode())
+ if not keyUsed then
+ for _, change in ipairs(changedHotkeys) do
+ if change.primary == keyCombo or change.secondary == keyCombo then
+ keyUsed = true
+ break
+ end
+ end
+ end
+
+ keyEditWindow.buttons.ok:setEnabled(not keyUsed)
+ keyEditWindow.used:setVisible(keyUsed)
+end
+
+function editKeybind(keybind)
+ keyEditWindow.buttons.cancel.onClick = function()
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+
+ keyEditWindow.info:setText(tr(
+ 'Click \'Ok\' to assign the keybind. Click \'Clear\' to remove the keybind from \'%s: %s\'.', keybind.category,
+ keybind.action))
+ keyEditWindow.alone:setVisible(keybind.alone)
+
+ connect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+
+ keyEditWindow:show()
+ keyEditWindow:raise()
+ keyEditWindow:focus()
+ keyEditWindow:grabKeyboard()
+ hide()
+end
+
+function editKeybindPrimary(button)
+ local column = button:getParent()
+ local row = column:getParent()
+ local index = row.category .. '_' .. row.action
+ local keybind = Keybind.getAction(row.category, row.action)
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+
+ keyEditWindow.keybind = {
+ category = row.category,
+ action = row.action
+ }
+
+ keyEditWindow:setText(tr('Edit Primary Key for \'%s\'', string.format('%s: %s', keybind.category, keybind.action)))
+ keyEditWindow.keyCombo:setText(Keybind.getKeybindKeys(row.category, row.action, getChatMode(), preset).primary)
+
+ editKeybind(keybind)
+
+ keyEditWindow.buttons.ok.onClick = function()
+ local keyCombo = keyEditWindow.keyCombo:getText()
+
+ column:setText(keyEditWindow.keyCombo:getText())
+
+ if not changedKeybinds[preset] then
+ changedKeybinds[preset] = {}
+ end
+ if not changedKeybinds[preset][index] then
+ changedKeybinds[preset][index] = {}
+ end
+ changedKeybinds[preset][index].primary = {
+ category = row.category,
+ action = row.action,
+ keyCombo = keyCombo
+ }
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ applyChangedOptions()
+ end
+
+ keyEditWindow.buttons.clear.onClick = function()
+ if not changedKeybinds[preset] then
+ changedKeybinds[preset] = {}
+ end
+ if not changedKeybinds[preset][index] then
+ changedKeybinds[preset][index] = {}
+ end
+ changedKeybinds[preset][index].primary = {
+ category = row.category,
+ action = row.action,
+ keyCombo = ''
+ }
+
+ column:setText('')
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ applyChangedOptions()
+ end
+end
+
+function editKeybindSecondary(button)
+ local column = button:getParent()
+ local row = column:getParent()
+ local index = row.category .. '_' .. row.action
+ local keybind = Keybind.getAction(row.category, row.action)
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+
+ keyEditWindow.keybind = {
+ category = row.category,
+ action = row.action
+ }
+
+ keyEditWindow:setText(tr('Edit Secondary Key for \'%s\'', string.format('%s: %s', keybind.category, keybind.action)))
+ keyEditWindow.keyCombo:setText(Keybind.getKeybindKeys(row.category, row.action, getChatMode(), preset).secondary)
+
+ editKeybind(keybind)
+
+ keyEditWindow.buttons.ok.onClick = function()
+ local keyCombo = keyEditWindow.keyCombo:getText()
+
+ column:setText(keyEditWindow.keyCombo:getText())
+
+ if not changedKeybinds[preset] then
+ changedKeybinds[preset] = {}
+ end
+ if not changedKeybinds[preset][index] then
+ changedKeybinds[preset][index] = {}
+ end
+ changedKeybinds[preset][index].secondary = {
+ category = row.category,
+ action = row.action,
+ keyCombo = keyCombo
+ }
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ applyChangedOptions()
+ end
+
+ keyEditWindow.buttons.clear.onClick = function()
+ if not changedKeybinds[preset] then
+ changedKeybinds[preset] = {}
+ end
+ if not changedKeybinds[preset][index] then
+ changedKeybinds[preset][index] = {}
+ end
+ changedKeybinds[preset][index].secondary = {
+ category = row.category,
+ action = row.action,
+ keyCombo = ''
+ }
+
+ column:setText('')
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ applyChangedOptions()
+ end
+end
+
+function resetActions()
+ changedOptions['resetKeybinds'] = {
+ value = panels.keybindsPanel.presets.list:getCurrentOption().text
+ }
+ updateKeybinds()
+ applyChangedOptions()
+end
+
+function updateKeybinds()
+ panels.keybindsPanel.tablePanel.keybinds:clearData()
+
+ local sortedKeybinds = {}
+
+ for index, _ in pairs(Keybind.defaultKeybinds) do
+ table.insert(sortedKeybinds, index)
+ end
+
+ table.sort(sortedKeybinds, function(a, b)
+ local keybindA = Keybind.defaultKeybinds[a]
+ local keybindB = Keybind.defaultKeybinds[b]
+
+ if keybindA.category ~= keybindB.category then
+ return keybindA.category < keybindB.category
+ end
+ return keybindA.action < keybindB.action
+ end)
+
+
+ local comboBox = panels.keybindsPanel.presets.list:getCurrentOption()
+ if not comboBox then
+ return
+ end
+ for _, index in ipairs(sortedKeybinds) do
+ local keybind = Keybind.defaultKeybinds[index]
+ local keys = Keybind.getKeybindKeys(keybind.category, keybind.action, getChatMode(), comboBox.text,
+ changedOptions['resetKeybinds'])
+ addKeybind(keybind.category, keybind.action, keys.primary, keys.secondary)
+ end
+end
+
+function updateHotkeys()
+ panels.keybindsPanel.tablePanel.keybinds:clearData()
+
+ local chatMode = getChatMode()
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+ if Keybind.hotkeys[chatMode][preset] then
+ for _, hotkey in ipairs(Keybind.hotkeys[chatMode][preset]) do
+ addHotkey(hotkey.hotkeyId, hotkey.action, hotkey.data, hotkey.primary, hotkey.secondary)
+ end
+ end
+end
+
+function preAddHotkey(action, data)
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+ local chatMode = getChatMode()
+ local hotkeyId = #changedHotkeys + 1
+
+ if Keybind.hotkeys[chatMode] and Keybind.hotkeys[chatMode][preset] then
+ hotkeyId = hotkeyId + #Keybind.hotkeys[chatMode][preset]
+ end
+
+ table.insert(changedHotkeys, {
+ hotkeyId = hotkeyId,
+ action = action,
+ data = data,
+ new = true
+ })
+
+ addHotkey(hotkeyId, action, data)
+end
+
+function addKeybind(category, action, primary, secondary)
+ local rawText = string.format('%s: %s', category, action)
+ local text = string.format('[color=#ffffff]%s:[/color] %s', category, action)
+ local tooltip = nil
+
+ if rawText:len() > actionNameLimit then
+ tooltip = rawText
+ -- 15 and 8 are length of color codes
+ text = text:sub(1, actionNameLimit + 15 + 8) .. '...'
+ end
+
+ local row = panels.keybindsPanel.tablePanel.keybinds:addRow({ {
+ coloredText = {
+ text = text,
+ color = '#c0c0c0'
+ },
+ width = 286
+ }, {
+ style = 'VerticalSeparator'
+ }, {
+ style = 'EditableKeybindsTableColumn',
+ text = primary,
+ width = 100
+ }, {
+ style = 'VerticalSeparator'
+ }, {
+ style = 'EditableKeybindsTableColumn',
+ text = secondary,
+ width = 90
+ } })
+
+ row.category = category
+ row.action = action
+
+ if tooltip then
+ row:setTooltip(tooltip)
+ end
+
+ row:getChildByIndex(3).edit.onClick = editKeybindPrimary
+ row:getChildByIndex(5).edit.onClick = editKeybindSecondary
+end
+
+function clearHotkey(row)
+ table.insert(changedHotkeys, {
+ hotkeyId = row.hotkeyId,
+ remove = true
+ })
+ panels.keybindsPanel.tablePanel.keybinds:removeRow(row)
+end
+
+function editHotkeyKey(text)
+ keyEditWindow.buttons.cancel.onClick = function()
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+
+ keyEditWindow.info:setText(tr(
+ 'Click \'Ok\' to assign the keybind. Click \'Clear\' to remove the keybind from \'%s\'.', text))
+ keyEditWindow.alone:setVisible(false)
+
+ connect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+
+ keyEditWindow:show()
+ keyEditWindow:raise()
+ keyEditWindow:focus()
+ keyEditWindow:grabKeyboard()
+ hide()
+end
+
+function editHotkeyPrimary(button)
+ local column = button:getParent()
+ local row = column:getParent()
+ local text = row:getChildByIndex(1):getText()
+ local hotkeyId = row.hotkeyId
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+
+ keyEditWindow:setText(tr('Edit Primary Key for \'%s\'', text))
+ keyEditWindow.keyCombo:setText(Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).primary)
+
+ editHotkeyKey(text)
+
+ keyEditWindow.buttons.ok.onClick = function()
+ local keyCombo = keyEditWindow.keyCombo:getText()
+
+ column:setText(keyEditWindow.keyCombo:getText())
+
+ local changed = table.findbyfield(changedHotkeys, 'hotkeyId', hotkeyId)
+ if changed then
+ changed.primary = keyCombo
+ if not changed.secondary then
+ changed.secondary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).secondary
+ end
+ changed.editKey = true
+ else
+ table.insert(changedHotkeys, {
+ hotkeyId = hotkeyId,
+ primary = keyCombo,
+ secondary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).secondary,
+ editKey = true
+ })
+ end
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+
+ keyEditWindow.buttons.clear.onClick = function()
+ column:setText('')
+
+ local changed = table.findbyfield(changedHotkeys, 'hotkeyId', hotkeyId)
+ if changed then
+ changed.primary = nil
+ if not changed.secondary then
+ changed.secondary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).secondary
+ end
+ changed.editKey = true
+ else
+ table.insert(changedHotkeys, {
+ hotkeyId = hotkeyId,
+ secondary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).secondary,
+ editKey = true
+ })
+ end
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+end
+
+function editHotkeySecondary(button)
+ local column = button:getParent()
+ local row = column:getParent()
+ local text = row:getChildByIndex(1):getText()
+ local hotkeyId = row.hotkeyId
+ local preset = panels.keybindsPanel.presets.list:getCurrentOption().text
+
+ keyEditWindow:setText(tr('Edit Secondary Key for \'%s\'', text))
+ keyEditWindow.keyCombo:setText(Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).secondary)
+
+ editHotkeyKey(text)
+
+ keyEditWindow.buttons.ok.onClick = function()
+ local keyCombo = keyEditWindow.keyCombo:getText()
+
+ column:setText(keyEditWindow.keyCombo:getText())
+
+ if changedHotkeys[hotkeyId] then
+ if not changedHotkeys[hotkeyId].primary then
+ changedHotkeys[hotkeyId].primary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).primary
+ end
+ changedHotkeys[hotkeyId].secondary = keyCombo
+ changedHotkeys[hotkeyId].editKey = true
+ else
+ table.insert(changedHotkeys, {
+ hotkeyId = hotkeyId,
+ primary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).primary,
+ secondary = keyCombo,
+ editKey = true
+ })
+ end
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+
+ keyEditWindow.buttons.clear.onClick = function()
+ column:setText('')
+
+ if changedHotkeys[hotkeyId] then
+ if not changedHotkeys[hotkeyId].primary then
+ changedHotkeys[hotkeyId].primary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).primary
+ end
+ changedHotkeys[hotkeyId].secondary = nil
+ changedHotkeys[hotkeyId].editKey = true
+ else
+ table.insert(changedHotkeys, {
+ hotkeyId = hotkeyId,
+ primary = Keybind.getHotkeyKeys(hotkeyId, preset, getChatMode()).primary,
+ editKey = true
+ })
+ end
+
+ disconnect(keyEditWindow, {
+ onKeyDown = editKeybindKeyDown
+ })
+ keyEditWindow:hide()
+ keyEditWindow:ungrabKeyboard()
+ show()
+ end
+end
+
+function searchActions(field, text, oldText)
+ if actionSearchEvent then
+ removeEvent(actionSearchEvent)
+ end
+
+ actionSearchEvent = scheduleEvent(performeSearchActions, 200)
+end
+
+function performeSearchActions()
+ local searchText = panels.keybindsPanel.search.field:getText():trim():lower()
+
+ local rows = panels.keybindsPanel.tablePanel.keybinds.dataSpace:getChildren()
+ if searchText:len() > 0 then
+ for _, row in ipairs(rows) do
+ row:hide()
+ end
+
+ for _, row in ipairs(rows) do
+ local actionText = row:getChildByIndex(1):getText():lower()
+ local primaryText = row:getChildByIndex(3):getText():lower()
+ local secondaryText = row:getChildByIndex(5):getText():lower()
+ if actionText:find(searchText) or primaryText:find(searchText) or secondaryText:find(searchText) then
+ row:show()
+ end
+ end
+ else
+ for _, row in ipairs(rows) do
+ row:show()
+ end
+ end
+
+ removeEvent(actionSearchEvent)
+ actionSearchEvent = nil
+end
+
+function chatModeChange()
+ changedHotkeys = {}
+ changedKeybinds = {}
+
+ panels.keybindsPanel.search.field:clearText()
+
+ updateKeybinds()
+end
+
+function getChatMode()
+ if chatModeGroup:getSelectedWidget() == panels.keybindsPanel.panel.chatMode.on then
+ return CHAT_MODE.ON
+ end
+
+ return CHAT_MODE.OFF
+end
+
+function applyChangedOptions()
+ local needKeybindsUpdate = false
+ local needHotkeysUpdate = false
+
+ for key, option in pairs(changedOptions) do
+ if key == 'resetKeybinds' then
+ Keybind.resetKeybindsToDefault(option.value, option.chatMode)
+ needKeybindsUpdate = true
+ end
+ end
+ changedOptions = {}
+
+ for preset, keybinds in pairs(changedKeybinds) do
+ for index, keybind in pairs(keybinds) do
+ if keybind.primary then
+ if Keybind.setPrimaryActionKey(keybind.primary.category, keybind.primary.action, preset,
+ keybind.primary.keyCombo, getChatMode()) then
+ needKeybindsUpdate = true
+ end
+ elseif keybind.secondary then
+ if Keybind.setSecondaryActionKey(keybind.secondary.category, keybind.secondary.action, preset,
+ keybind.secondary.keyCombo, getChatMode()) then
+ needKeybindsUpdate = true
+ end
+ end
+ end
+ end
+ changedKeybinds = {}
+
+ if needKeybindsUpdate then
+ updateKeybinds()
+ end
+ g_settings.save()
+end
+
+function presetOption(widget, key, value, force)
+ if not controller.ui:isVisible() then
+ return
+ end
+
+ changedOptions[key] = { widget = widget, value = value, force = force }
+ if key == "currentPreset" then
+ Keybind.selectPreset(value)
+ panels.keybindsPanel.presets.list:setCurrentOption(value, true)
+ end
+end
+
+function init_binds()
+ chatModeGroup = UIRadioGroup.create()
+ chatModeGroup:addWidget(panels.keybindsPanel.panel.chatMode.on)
+ chatModeGroup:addWidget(panels.keybindsPanel.panel.chatMode.off)
+ chatModeGroup.onSelectionChange = chatModeChange
+ chatModeGroup:selectWidget(panels.keybindsPanel.panel.chatMode.on)
+
+ keyEditWindow = g_ui.displayUI("styles/controls/key_edit")
+ keyEditWindow:hide()
+ presetWindow = g_ui.displayUI("styles/controls/preset")
+ presetWindow:hide()
+ panels.keybindsPanel.presets.add.onClick = addNewPreset
+ panels.keybindsPanel.presets.copy.onClick = copyPreset
+ panels.keybindsPanel.presets.rename.onClick = renamePreset
+ panels.keybindsPanel.presets.remove.onClick = removePreset
+ panels.keybindsPanel.buttons.newAction:disable()
+ panels.keybindsPanel.buttons.newAction.onClick = newHotkeyAction
+ panels.keybindsPanel.buttons.reset.onClick = resetActions
+ panels.keybindsPanel.search.field.onTextChange = searchActions
+ panels.keybindsPanel.search.clear.onClick = function() panels.keybindsPanel.search.field:clearText() end
+ presetWindow.onEnter = okPresetWindow
+ presetWindow.onEscape = cancelPresetWindow
+ presetWindow.buttons.ok.onClick = okPresetWindow
+ presetWindow.buttons.cancel.onClick = cancelPresetWindow
+end
+
+function terminate_binds()
+ if presetWindow then
+ presetWindow:destroy()
+ presetWindow = nil
+ end
+
+ if chatModeGroup then
+ chatModeGroup:destroy()
+ chatModeGroup = nil
+ end
+
+ if keyEditWindow then
+ if keyEditWindow:isVisible() then
+ keyEditWindow:ungrabKeyboard()
+ disconnect(keyEditWindow, { onKeyDown = editKeybindKeyDown })
+ end
+ keyEditWindow:destroy()
+ keyEditWindow = nil
+ end
+
+ actionSearchEvent = nil
+end
+
+function listKeybindsComboBox(value)
+ local widget = panels.keybindsPanel.presets.list
+ presetOption(widget, 'currentPreset', value, false)
+ changedKeybinds = {}
+ changedHotkeys = {}
+ applyChangedOptions()
+ updateKeybinds()
+end
+
+function debug()
+ local currentOptionText = Keybind.currentPreset
+ local chatMode = Keybind.chatMode
+ local chatModeText = (chatMode == 1) and "Chat mode ON" or (chatMode == 2) and "Chat mode OFF" or "Unknown chat mode"
+ print(string.format("The current configuration is: %s, and the mode is: %s", currentOptionText, chatModeText))
+end
diff --git a/modules/client_options/options.lua b/modules/client_options/options.lua
index e9cbc62442..d89f726e7f 100644
--- a/modules/client_options/options.lua
+++ b/modules/client_options/options.lua
@@ -1,6 +1,5 @@
local options = dofile("data_options")
-
-local panels = {
+panels = {
generalPanel = nil,
graphicsPanel = nil,
soundPanel = nil,
@@ -9,24 +8,19 @@ local panels = {
interfaceHUD = nil,
interface = nil,
misc = nil,
- miscHelp = nil
+ miscHelp = nil,
+ keybindsPanel = nil
}
-- LuaFormatter off
local buttons = {{
text = "Controls",
icon = "/images/icons/icon_controls",
- open = "generalPanel"
- --[[ subCategories = {{
+ open = "generalPanel",
+ subCategories = {{
text = "General Hotkeys",
- open = "generalPanel"
- }, {
- text = "Action Bar Hotkeys",
- open = "Action_Bar_Hotkeys"
- }, {
- text = "Custom Hotkeys",
- open = "Custom_Hotkeys"
- }} ]]
+ open = "keybindsPanel"
+ }}
}, {
text = "Interface",
icon = "/images/icons/icon_interface",
@@ -106,6 +100,8 @@ local function setupComboBox()
local antialiasingModeCombobox = panels.graphicsPanel:recursiveGetChildById('antialiasingMode')
local floorViewModeCombobox = panels.graphicsEffectsPanel:recursiveGetChildById('floorViewMode')
local framesRarityCombobox = panels.interface:recursiveGetChildById('frames')
+ local vocationPresetsCombobox = panels.keybindsPanel:recursiveGetChildById('list')
+ local listKeybindsPanel = panels.keybindsPanel:recursiveGetChildById('list')
for k, v in pairs({ { 'Disabled', 'disabled' }, { 'Default', 'default' }, { 'Full', 'full' } }) do
crosshairCombo:addOption(v[1], v[2])
@@ -153,6 +149,13 @@ local function setupComboBox()
end
end
+ for _, preset in ipairs(Keybind.presets) do
+ listKeybindsPanel:addOption(preset)
+ end
+ listKeybindsPanel.onOptionChange = function(comboBox, option)
+ setOption('listKeybindsPanel', option)
+ end
+ panels.keybindsPanel.presets.list:setCurrentOption(Keybind.currentPreset)
end
local function setup()
@@ -177,8 +180,6 @@ end
controller = Controller:new()
controller:setUI('options')
-controller:bindKeyDown('Ctrl+Shift+F', function() toggleOption('fullscreen') end)
-controller:bindKeyDown('Ctrl+N', toggleDisplays)
function controller:onInit()
for k, obj in pairs(options) do
@@ -199,6 +200,7 @@ function controller:onInit()
'/images/topbuttons/logout', toggle)
panels.generalPanel = g_ui.loadUI('styles/controls/general',controller.ui.optionsTabContent)
+ panels.keybindsPanel = g_ui.loadUI('styles/controls/keybinds',controller.ui.optionsTabContent)
panels.graphicsPanel = g_ui.loadUI('styles/graphics/graphics',controller.ui.optionsTabContent)
panels.graphicsEffectsPanel = g_ui.loadUI('styles/graphics/effects',controller.ui.optionsTabContent)
@@ -216,6 +218,39 @@ function controller:onInit()
configureCharacterCategories()
addEvent(setup)
+ init_binds()
+
+ Keybind.new("UI", "Toggle Fullscreen", "Ctrl+Shift+F", "")
+ Keybind.bind("UI", "Toggle Fullscreen", {
+ {
+ type = KEY_DOWN,
+ callback = function() toggleOption('fullscreen') end,
+ }
+ })
+ Keybind.new("UI", "Show/hide FPS / lag indicator", "", "")
+ Keybind.bind("UI", "Show/hide FPS / lag indicator", {{
+ type = KEY_DOWN,
+ callback = function()
+ toggleOption('showPing')
+ toggleOption('showFps')
+ end
+ }})
+
+ Keybind.new("UI", "Show/hide Creature Names and Bars", "Ctrl+N", "")
+ Keybind.bind("UI", "Show/hide Creature Names and Bars", {
+ {
+ type = KEY_DOWN,
+ callback = toggleDisplays,
+ }
+ })
+
+ Keybind.new("Sound", "Mute/unmute", "", "")
+ Keybind.bind("Sound", "Mute/unmute", {
+ {
+ type = KEY_DOWN,
+ callback = function() toggleOption('enableAudio') end,
+ }
+ })
end
function controller:onTerminate()
@@ -224,6 +259,21 @@ function controller:onTerminate()
panels = {}
extraWidgets = {}
buttons = {}
+ Keybind.delete("UI", "Toggle Full Screen")
+ Keybind.delete("UI", "Show/hide Creature Names and Bars")
+ Keybind.delete("Sound", "Mute/unmute")
+
+ terminate_binds()
+end
+
+function controller:onGameStart()
+ if g_settings.getBoolean("autoSwitchPreset") then
+ local name = g_game.getCharacterName()
+ if Keybind.selectPreset(name) then
+ panels.keybindsPanel.presets.list:setCurrentOption(name, true)
+ updateKeybinds()
+ end
+ end
end
function setOption(key, value, force)
@@ -299,6 +349,7 @@ function toggle()
end
end
show()
+ updateKeybinds()
end
function addTab(name, panel, icon)
diff --git a/modules/client_options/options.otmod b/modules/client_options/options.otmod
index 7671184cab..2b44193a17 100644
--- a/modules/client_options/options.otmod
+++ b/modules/client_options/options.otmod
@@ -4,6 +4,6 @@ Module
author: edubart, BeniS
website: https://github.com/edubart/otclient
sandboxed: true
- scripts: [ options ]
+ scripts: [ options, keybins ]
@onLoad: controller:init()
@onUnload: controller:terminate()
diff --git a/modules/client_options/styles/controls/key_edit.otui b/modules/client_options/styles/controls/key_edit.otui
new file mode 100644
index 0000000000..aeac99932a
--- /dev/null
+++ b/modules/client_options/styles/controls/key_edit.otui
@@ -0,0 +1,66 @@
+MainWindow
+ size: 400 225
+ layout:
+ type: verticalBox
+ spacing: 10
+ fit-children: true
+
+ Label
+ font: verdana-11px-monochrome
+ text-align: center
+ color: #c0c0c0
+ text: Mode: "Chat On"
+
+ FlatPanel
+ id: keyCombo
+ height: 33
+ font: verdana-11px-monochrome
+ text-align: center
+ color: #c0c0c0
+
+ Label
+ id: info
+ font: verdana-11px-monochrome
+ color: #c0c0c0
+ text-wrap: true
+ text-auto-resize: true
+
+ Label
+ id: alone
+ font: verdana-11px-monochrome
+ color: #c0c0c0
+ !text: tr("This action must be bound to a single key.")
+ visible: false
+
+ Label
+ id: used
+ font: verdana-11px-monochrome
+ text-align: center
+ color: #f75f5f
+ !text: tr("This hotkey is already in use.")
+ visible: false
+
+ HorizontalSeparator
+
+ Panel
+ id: buttons
+ height: 20
+ layout:
+ type: horizontalBox
+ align-right: true
+ spacing: -5
+
+ SmallButton
+ id: ok
+ width: 40
+ !text: tr("Ok")
+
+ SmallButton
+ id: clear
+ width: 45
+ !text: tr("Clear")
+ SmallButton
+ id: cancel
+ width: 45
+ !text: tr("Cancel")
+
diff --git a/modules/client_options/styles/controls/keybinds.otui b/modules/client_options/styles/controls/keybinds.otui
new file mode 100644
index 0000000000..98ca8999c4
--- /dev/null
+++ b/modules/client_options/styles/controls/keybinds.otui
@@ -0,0 +1,285 @@
+RadioBox < CheckBox
+ image-source: /images/ui/outfits/checkbox_round
+
+OptionContainer < FlatPanel
+ height: 22
+ padding: 3
+KeybindsTableRow < UITableRow
+ focusable: true
+ height: 20
+ background-color: alpha
+ even-background-color: alpha
+ odd-background-color: #484848
+ text-align: left
+ @onFocusChange: for _, child in ipairs(self:getChildren()) do child:setChecked(self:isFocused()) end
+ layout: horizontalBox
+
+ $focus:
+ background-color: #585858
+
+KeybindsTableColumn < Label
+ color: #c0c0c0
+ text-align: left
+ focusable: false
+ text-offset: 2 0
+ font: verdana-11px-monochrome
+
+EditableKeybindsTableColumn < Label
+ color: #c0c0c0
+ text-align: left
+ focusable: false
+ text-offset: 2 0
+ font: verdana-11px-monochrome
+ @onCheckChange: self.edit:setVisible(self:isChecked())
+
+ Button
+ id: edit
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.right: parent.right
+ size: 13 13
+ margin-right: 2
+ icon: /images/ui/icon-edit
+ visible: false
+
+EditableHotkeysTableColumn < Label
+ color: #c0c0c0
+ text-align: left
+ focusable: false
+ text-offset: 18 0
+ font: verdana-11px-monochrome
+ @onCheckChange: self.edit:setVisible(self:isChecked())
+
+ UIItem
+ id: item
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.left: parent.left
+ size: 16 16
+ virtual: true
+ phantom: true
+
+ Button
+ id: edit
+ anchors.verticalCenter: parent.verticalCenter
+ anchors.right: parent.right
+ size: 13 13
+ margin-right: 2
+ icon: /images/options/icon-edit
+ visible: false
+
+KeybindsTableHeaderRow < TableHeaderRow
+ padding: 0
+ height: 18
+
+KeybindsTableHeaderColumn < UITableHeaderColumn
+ font: verdana-11px-monochrome
+ text-offset: 2 0
+ text-align: left
+ height: 14
+ color: #c0c0c0
+ background: #363636
+
+UIWidget
+ anchors.fill: parent
+ visible: false
+ Panel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: parent.top
+ id: presets
+ height: 20
+ layout:
+ type: horizontalBox
+ spacing: 5
+
+ QtComboBox
+ id: list
+ width: 320
+
+ SmallButton
+ id: add
+ width: 30
+ !text: tr("Add")
+ @onClick: addNewPreset()
+
+ SmallButton
+ id: copy
+ width: 35
+ !text: tr("Copy")
+ @onClick: copyPreset()
+
+ SmallButton
+ id: rename
+ width: 45
+ !text: tr("Rename")
+ @onClick : renamePreset()
+
+ SmallButton
+ id: remove
+ width: 45
+ !text: tr("Remove")
+ @onClick : removePreset()
+
+ SmallReversedQtPanel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: prev.bottom
+ height: 22
+ margin-top: 7
+
+ OptionCheckBoxMarked
+ id: autoSwitchPreset
+ !text: tr('Auto-Switch Hotkey Preset')
+ !tooltip: tr('If you have named your hotkey presets the same like your\ncharacters and have checked this option, the preset with the same\nname as the corresponding character will be activated upon login\nautomatically.')
+
+ SmallReversedQtPanel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: prev.bottom
+ height: 22
+ margin-top: 7
+ id: panel
+ OptionContainer
+ anchors.left: parent.left
+ anchors.right: parent.right
+ image-source: ""
+ !tooltip: tr('There are two chat modes for each hotkey preset: Chat On and Chat\n Off.You can find a small button that tells you which chat mode is\n currently active on the right side of the entry line of the chat console.Press this button to switch between the two chat modes.\nOf course, you can also set a hotkey to toggle between Chat On and Off.\n- Chat On\nIn this mode, you will be able to write text in the entry line of the chat console.\nHowever, if you have assigned an action to a letter key, the action will be triggered.\n- Chat On*\nThis is the temporary Chat On mode.\nIn the default hotkey preset, the Return key switches between Chat Off and this mode.\nIf the chat mode is off and you press this hotkey, it temporarily activates the chat mode so that you can write one message in the console.\nAs soon as you press Return to send the message, your chat mode will be set to Chat Off again so that you can continue walking with WASD, for example.\n- Chat Off\nIn this mode, you will not be able to write any text in the entry line of the console, but you can use your predefined hotkeys to walk or cast spells, for example.\nYou can assign functions to all keys of your keyboard, e.g. walk with WASD.')
+
+ id: chatMode
+ $!first:
+ margin-left:40
+ layout:
+ type: horizontalBox
+ spacing: 127
+
+ RadioBox
+ id: on
+ text-horizontal-auto-resize: true
+ !text: tr("Chat Mode On")
+ margin-bottom: -5
+ text-offset: 20 -3
+ RadioBox
+ id: off
+ text-horizontal-auto-resize: true
+ !text: tr("Chat Mode Off")
+ margin-bottom: -5
+ text-offset: 20 -3
+ UIWidget
+ id: toolTipWidget
+ image-source: /images/icons/show_gui_help_grey
+ size: 12 12
+ anchors.right: parent.right
+ margin-right: 3
+ !tooltip: tr('There are two chat modes for each hotkey preset: Chat On and Chat \nOff. You can find a small button that tells you which chat mode is \ncurrently active on the right side of the entry line of the chat \nconsole. Press this button to switch between the two chat modes. Of \ncourse, you can also set a hotkey to toggle between Chat On and Off.\n\tChat On\n\t\tIn this mode, you will be able to write text in the entry line of\n the chat console. However, if you have assigned an action to \na letter key, the action will be \t\ttriggered.\n\n\n\tChat On\n\t\tThis is the temporary Chat On mode. In the default hotkey \npreset, the Return key switches between Chat Off and this\n mode. If the chat mode is off and you press \t\tthis hotkey, it \ntemporarily activates the chat mode so that you can write \none message in the console. As soon as you press Return to \nsend the message, your chat \t\tmode will be set to \nChat Off again so that you can continue walking with WASD, for\n example.\n\n\tChat Off\n\t\tIn this mode, you will not be able to write any text in the entry line of the\n console, but you can use your predefined\n hotkeys to walk or cast spells, for \t\texample. You can assign\n functions to all keys of your keyboard, e.g. walk with WASD')
+
+ Panel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: prev.bottom
+ id: search
+ height: 20
+ margin-top: 5
+ layout:
+ type: horizontalBox
+ spacing: 6
+
+ Label
+ text-offset: 0 3
+ font: verdana-11px-monochrome
+ !text: tr('Type to search for a hotkey:')
+
+ TextEdit
+ id: field
+ width: 300
+ @onTextChange: searchActions()
+
+ UIButton
+ id: clear
+ image-source: /images/ui/button-clear-18x18-up
+ image-clip: 0 0 20 20
+ width: 20
+
+ $pressed:
+ image-source: /images/ui/button-clear-18x18-down
+ @onClick : self:getParent().field:clearText()
+
+ Panel
+ id: tablePanel
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: prev.bottom
+ height: 305
+ margin-top: 5
+ image-source: /images/game/actionbar/1pixel-down-frame
+ image-border: 1
+ background: #404040
+
+ Table
+ id: keybinds
+ anchors.fill: parent
+ margin: 1
+ table-data: keybindsData
+ row-style: KeybindsTableRow
+ column-style: KeybindsTableColumn
+ header-row-style: KeybindsTableHeaderRow
+ header-column-style: KeybindsTableHeaderColumn
+
+ KeybindsTableHeaderRow
+ id: header
+
+ KeybindsTableHeaderColumn
+ !text: tr("Action")
+ width: 286
+
+ VerticalSeparator
+
+ KeybindsTableHeaderColumn
+ !text: tr("Primary Key")
+ width: 100
+
+ VerticalSeparator
+
+ KeybindsTableHeaderColumn
+ !text: tr("Secondary Key")
+ width: 100
+
+ HorizontalSeparator
+
+ TableData
+ id: keybindsData
+ anchors.fill: keybinds
+ margin-top: 20
+ padding-bottom: 1
+ vertical-scrollbar: scrollBar
+
+ VerticalQtScrollBar
+ id: scrollBar
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ anchors.right: parent.right
+ step: 16
+ pixels-scroll: true
+
+ Panel
+ id: buttons
+ height: 20
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: prev.bottom
+
+ SmallButton
+ id: newAction
+ anchors.top: parent.top
+ anchors.left: parent.left
+ width: 75
+ !text: tr('New Action')
+ visible: false
+ @onClick : newHotkeyAction()
+
+ SmallButton
+ id: reset
+ anchors.top: parent.top
+ anchors.right: parent.right
+ width: 45
+ margin-top: 8
+ !text: tr('Reset')
+ @onClick : resetActions()
diff --git a/modules/client_options/styles/controls/preset.otui b/modules/client_options/styles/controls/preset.otui
new file mode 100644
index 0000000000..9b3d4ab223
--- /dev/null
+++ b/modules/client_options/styles/controls/preset.otui
@@ -0,0 +1,43 @@
+MainWindow
+ width: 360
+ text: Add hotkey preset
+ layout:
+ type: verticalBox
+ fit-children: true
+
+ Label
+ id: info
+ font: verdana-11px-monochrome
+ color: #c0c0c0
+ text: Enter a name for the new preset:
+
+ TextEdit
+ id: field
+ margin-top: 3
+ height: 16
+ padding: 1 4
+ font: verdana-11px-monochrome
+ color: #c0c0c0
+
+ HorizontalSeparator
+ margin-top: 10
+
+ Panel
+ id: buttons
+ margin-top: 10
+ height: 20
+ layout:
+ type: horizontalBox
+ align-right: true
+ spacing: -8
+
+ SmallButton
+ id: ok
+ width: 40
+ !text: tr("Ok")
+
+ SmallButton
+ id: cancel
+ width: 45
+ !text: tr("Cancel")
+
diff --git a/modules/client_terminal/terminal.lua b/modules/client_terminal/terminal.lua
index 97cb13ecc4..2bc613e1ff 100644
--- a/modules/client_terminal/terminal.lua
+++ b/modules/client_terminal/terminal.lua
@@ -150,7 +150,12 @@ function init()
terminalButton = modules.client_topmenu.addTopRightToggleButton('terminalButton', tr('Terminal') .. ' (Ctrl + T)',
'/images/topbuttons/terminal', toggle)
- g_keyboard.bindKeyDown('Ctrl+T', toggle)
+ Keybind.new("Misc.", "Toggle Terminal", "Ctrl+T", "")
+ Keybind.bind("Misc.", "Toggle Terminal", {{
+ type = KEY_DOWN,
+ callback = toggle
+ }})
+
commandHistory = g_settings.getList('terminal-history')
@@ -214,7 +219,7 @@ function terminate()
}
g_settings.setNode('terminal-window', settings)
- g_keyboard.unbindKeyDown('Ctrl+T')
+ Keybind.delete("Misc.", "Toggle Terminal")
g_logger.setOnLog(nil)
terminalWindow:destroy()
terminalButton:destroy()
diff --git a/modules/client_topmenu/topmenu.lua b/modules/client_topmenu/topmenu.lua
index f9115eae61..40dab3f738 100644
--- a/modules/client_topmenu/topmenu.lua
+++ b/modules/client_topmenu/topmenu.lua
@@ -92,7 +92,13 @@ function init()
topLeftYoutubeLink = topMenu:recursiveGetChildById('youtubeIcon')
topLeftDiscordLink = topMenu:recursiveGetChildById('discordIcon')
- g_keyboard.bindKeyDown('Ctrl+Shift+T', toggle)
+ Keybind.new("UI", "Toggle Top Menu", "Ctrl+Shift+T", "")
+ Keybind.bind("UI", "Toggle Top Menu", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
if Services.websites then
managerAccountsButton = modules.client_topmenu.addTopRightRegularButton('hotkeysButton', tr('Manage Account'),
nil, openManagerAccounts)
@@ -113,7 +119,7 @@ function terminate()
})
topMenu:destroy()
- if PingWidget then
+ if PingWidget and not PingWidget:isDestroyed() then
PingWidget:destroy()
PingWidget = nil
end
@@ -121,7 +127,7 @@ function terminate()
managerAccountsButton:destroy()
managerAccountsButton = nil
end
-
+ Keybind.delete("UI", "Toggle Top Menu")
end
function hide()
@@ -138,8 +144,23 @@ function online()
showGameButtons()
addEvent(function()
- if modules.client_options.getOption('showPing') and
- (g_game.getFeature(GameClientPing) or g_game.getFeature(GameExtendedClientPing)) then
+ local showPing = modules.client_options.getOption('showPing')
+ local pingFeatureAvailable = g_game.getFeature(GameClientPing) or g_game.getFeature(GameExtendedClientPing)
+
+ if not PingWidget then
+ PingWidget = g_ui.loadUI("pingFps", modules.game_interface.getMapPanel())
+ MainPingPanel = g_ui.createWidget("testPingPanel", PingWidget:getChildByIndex(1))
+ MainPingPanel:setId("ping")
+
+ pingImg = MainPingPanel:getChildByIndex(1)
+ pingPanel = MainPingPanel:getChildByIndex(2)
+
+ mainFpsPanel = g_ui.createWidget("testPingPanel", PingWidget:getChildByIndex(2))
+ mainFpsPanel:setId("fps")
+ fpsPanel2 = mainFpsPanel:getChildByIndex(2)
+ end
+
+ if showPing and pingFeatureAvailable then
pingLabel:show()
if pingPanel then
pingPanel:show()
@@ -152,29 +173,12 @@ function online()
pingImg:hide()
end
end
- if PingWidget then
- return
- end
- PingWidget = g_ui.loadUI("pingFps", modules.game_interface.getMapPanel())
- MainPingPanel = g_ui.createWidget("testPingPanel", PingWidget:getChildByIndex(1))
- MainPingPanel.setId(MainPingPanel, "ping")
- pingImg = MainPingPanel.getChildByIndex(MainPingPanel, 1)
- pingPanel = MainPingPanel.getChildByIndex(MainPingPanel, 2)
- if modules.client_options.getOption('showPing') then
- pingImg:setVisible(true)
- pingPanel:setVisible(true)
- else
- pingImg:setVisible(false)
- pingPanel:setVisible(true)
- end
- mainFpsPanel = g_ui.createWidget("testPingPanel", PingWidget:getChildByIndex(2))
- mainFpsPanel.setId(mainFpsPanel, "fps")
- fpsPanel2 = mainFpsPanel.getChildByIndex(mainFpsPanel, 2)
- if modules.client_options.getOption('showFps') then
- fpsPanel2:setVisible(true)
- else
- fpsPanel2:setVisible(false)
- end
+
+ pingImg:setVisible(showPing)
+ pingPanel:setVisible(showPing)
+
+ local showFps = modules.client_options.getOption('showFps')
+ fpsPanel2:setVisible(showFps)
end)
end
diff --git a/modules/corelib/corelib.otmod b/modules/corelib/corelib.otmod
index 80c3359b77..7c665fb4f5 100644
--- a/modules/corelib/corelib.otmod
+++ b/modules/corelib/corelib.otmod
@@ -17,6 +17,7 @@ Module
dofile 'globals'
dofile 'config'
dofile 'settings'
+ dofile 'keybind'
dofile 'keyboard'
dofile 'mouse'
dofile 'net'
@@ -28,4 +29,7 @@ Module
dofile 'outputmessage'
dofile 'json'
- dofile 'http'
\ No newline at end of file
+ dofile 'http'
+ Keybind.init()
+
+ @onUnload: Keybind.terminate()
diff --git a/modules/corelib/keybind.lua b/modules/corelib/keybind.lua
new file mode 100644
index 0000000000..a61cfdf553
--- /dev/null
+++ b/modules/corelib/keybind.lua
@@ -0,0 +1,1036 @@
+
+CHAT_MODE = {
+ ON = 1,
+ OFF = 2
+}
+
+Keybind = {
+ presets = {},
+ presetToIndex = {},
+ currentPreset = nil,
+ configs = {
+ keybinds = {},
+ hotkeys = {}
+ },
+ defaultKeys = {
+ [CHAT_MODE.ON] = {},
+ [CHAT_MODE.OFF] = {}
+ },
+ defaultKeybinds = {},
+ hotkeys = {
+ [CHAT_MODE.ON] = {},
+ [CHAT_MODE.OFF] = {}
+ },
+ chatMode = CHAT_MODE.ON,
+
+ reservedKeys = {
+ ["Up"] = true,
+ ["Down"] = true,
+ ["Left"] = true,
+ ["Right"] = true
+ }
+}
+
+KEY_UP = 1
+KEY_DOWN = 2
+KEY_PRESS = 3
+
+HOTKEY_ACTION = {
+ USE_YOURSELF = 1,
+ USE_CROSSHAIR = 2,
+ USE_TARGET = 3,
+ EQUIP = 4,
+ USE = 5,
+ TEXT = 6,
+ TEXT_AUTO = 7,
+ SPELL = 8
+}
+
+function Keybind.init()
+ connect(g_game, { onGameStart = Keybind.online, onGameEnd = Keybind.offline })
+
+ Keybind.presets = g_settings.getList("controls-presets")
+
+ if #Keybind.presets == 0 then
+ Keybind.presets = { "Druid", "Knight", "Paladin", "Sorcerer" }
+ Keybind.currentPreset = "Druid"
+ else
+ Keybind.currentPreset = g_settings.getValue("controls-preset-current")
+ end
+
+ for index, preset in ipairs(Keybind.presets) do
+ Keybind.presetToIndex[preset] = index
+ end
+
+ if not g_resources.directoryExists("/controls") then
+ g_resources.makeDir("/controls")
+ end
+
+ if not g_resources.directoryExists("/controls/keybinds") then
+ g_resources.makeDir("/controls/keybinds")
+ end
+
+ if not g_resources.directoryExists("/controls/hotkeys") then
+ g_resources.makeDir("/controls/hotkeys")
+ end
+
+ for _, preset in ipairs(Keybind.presets) do
+ Keybind.configs.keybinds[preset] = g_configs.create("/controls/keybinds/" .. preset .. ".otml")
+ Keybind.configs.hotkeys[preset] = g_configs.create("/controls/hotkeys/" .. preset .. ".otml")
+ end
+
+ for preset, config in pairs(Keybind.configs.hotkeys) do
+ for chatMode = CHAT_MODE.ON, CHAT_MODE.OFF do
+ Keybind.hotkeys[chatMode][preset] = {}
+ local hotkeyId = 1
+ local hotkeys = config:getNode(chatMode)
+
+ if hotkeys then
+ local hotkey = hotkeys[tostring(hotkeyId)]
+ while hotkey do
+ if hotkey.data.parameter then
+ hotkey.data.parameter = "\"" .. hotkey.data.parameter .. "\"" -- forcing quotes cause OTML is not saving them, just wow
+ end
+
+ table.insert(Keybind.hotkeys[chatMode][preset], hotkey)
+ hotkeyId = hotkeyId + 1
+
+ hotkey = hotkeys[tostring(hotkeyId)]
+ end
+ end
+ end
+ end
+end
+
+function Keybind.terminate()
+ disconnect(g_game, { onGameStart = Keybind.online, onGameEnd = Keybind.offline })
+
+ for _, preset in ipairs(Keybind.presets) do
+ Keybind.configs.keybinds[preset]:save()
+ Keybind.configs.hotkeys[preset]:save()
+ end
+
+ g_settings.setList("controls-presets", Keybind.presets)
+ g_settings.setValue("controls-preset-current", Keybind.currentPreset)
+ g_settings.save()
+end
+
+function Keybind.online()
+ for _, hotkey in ipairs(Keybind.hotkeys[Keybind.chatMode][Keybind.currentPreset]) do
+ Keybind.bindHotkey(hotkey.hotkeyId, Keybind.chatMode)
+ end
+end
+
+function Keybind.offline()
+ for _, hotkey in ipairs(Keybind.hotkeys[Keybind.chatMode][Keybind.currentPreset]) do
+ Keybind.unbindHotkey(hotkey.hotkeyId, Keybind.chatMode)
+ end
+end
+
+function Keybind.new(category, action, primary, secondary, alone)
+ local index = category .. '_' .. action
+ if Keybind.defaultKeybinds[index] then
+ pwarning(string.format("Keybind for [%s: %s] is already in use", category, action))
+ return
+ end
+
+ local keys = {}
+ if type(primary) == "string" then
+ keys[CHAT_MODE.ON] = { primary = primary }
+ keys[CHAT_MODE.OFF] = { primary = primary }
+ else
+ keys[CHAT_MODE.ON] = { primary = primary[CHAT_MODE.ON] }
+ keys[CHAT_MODE.OFF] = { primary = primary[CHAT_MODE.OFF] }
+ end
+
+ if type(secondary) == "string" then
+ keys[CHAT_MODE.ON].secondary = secondary
+ keys[CHAT_MODE.OFF].secondary = secondary
+ else
+ keys[CHAT_MODE.ON].secondary = secondary[CHAT_MODE.ON]
+ keys[CHAT_MODE.OFF].secondary = secondary[CHAT_MODE.OFF]
+ end
+
+ keys[CHAT_MODE.ON].primary = retranslateKeyComboDesc(keys[CHAT_MODE.ON].primary)
+
+ if keys[CHAT_MODE.ON].secondary then
+ keys[CHAT_MODE.ON].secondary = retranslateKeyComboDesc(keys[CHAT_MODE.ON].secondary)
+ end
+
+ keys[CHAT_MODE.OFF].primary = retranslateKeyComboDesc(keys[CHAT_MODE.OFF].primary)
+
+ if keys[CHAT_MODE.OFF].secondary then
+ keys[CHAT_MODE.OFF].secondary = retranslateKeyComboDesc(keys[CHAT_MODE.OFF].secondary)
+ end
+
+ if Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].primary] then
+ local primaryIndex = Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].primary]
+ local primaryKeybind = Keybind.defaultKeybinds[primaryIndex]
+ perror(string.format("Default primary key (Chat Mode On) assigned to [%s: %s] is already in use by [%s: %s]",
+ category, action, primaryKeybind.category, primaryKeybind.action))
+ return
+ end
+
+ if Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].primary] then
+ local primaryIndex = Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].primary]
+ local primaryKeybind = Keybind.defaultKeybinds[primaryIndex]
+ perror(string.format("Default primary key (Chat Mode Off) assigned to [%s: %s] is already in use by [%s: %s]",
+ category, action, primaryKeybind.category, primaryKeybind.action))
+ return
+ end
+
+ if keys[CHAT_MODE.ON].secondary and Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].secondary] then
+ local secondaryIndex = Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].secondary]
+ local secondaryKeybind = Keybind.defaultKeybinds[secondaryIndex]
+ perror(string.format("Default secondary key (Chat Mode On) assigned to [%s: %s] is already in use by [%s: %s]",
+ category, action, secondaryKeybind.category, secondaryKeybind.action))
+ return
+ end
+
+ if keys[CHAT_MODE.OFF].secondary and Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].secondary] then
+ local secondaryIndex = Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].secondary]
+ local secondaryKeybind = Keybind.defaultKeybinds[secondaryIndex]
+ perror(string.format("Default secondary key (Chat Mode Off) assigned to [%s: %s] is already in use by [%s: %s]",
+ category, action, secondaryKeybind.category, secondaryKeybind.action))
+ return
+ end
+
+ if keys[CHAT_MODE.ON].primary then
+ Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].primary] = index
+ end
+
+ if keys[CHAT_MODE.OFF].primary then
+ Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].primary] = index
+ end
+
+ Keybind.defaultKeybinds[index] = {
+ category = category,
+ action = action,
+ keys = keys,
+ alone = alone
+ }
+
+ if keys[CHAT_MODE.ON].secondary then
+ Keybind.defaultKeys[CHAT_MODE.ON][keys[CHAT_MODE.ON].secondary] = index
+ end
+ if keys[CHAT_MODE.OFF].secondary then
+ Keybind.defaultKeys[CHAT_MODE.OFF][keys[CHAT_MODE.OFF].secondary] = index
+ end
+end
+
+function Keybind.delete(category, action)
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+
+ if not keybind then
+ return
+ end
+
+ Keybind.unbind(category, action)
+
+ local keysOn = keybind.keys[CHAT_MODE.ON]
+ local keysOff = keybind.keys[CHAT_MODE.OFF]
+
+ local primaryOn = keysOn.primary and tostring(keysOn.primary) or nil
+ local primaryOff = keysOff.primary and tostring(keysOff.primary) or nil
+ local secondaryOn = keysOn.secondary and tostring(keysOn.secondary) or nil
+ local secondaryOff = keysOff.secondary and tostring(keysOff.secondary) or nil
+
+ if primaryOn and primaryOn:len() > 0 then
+ Keybind.defaultKeys[CHAT_MODE.ON][primaryOn] = nil
+ end
+ if secondaryOn and secondaryOn:len() > 0 then
+ Keybind.defaultKeys[CHAT_MODE.ON][secondaryOn] = nil
+ end
+
+ if primaryOff and primaryOff:len() > 0 then
+ Keybind.defaultKeys[CHAT_MODE.OFF][primaryOff] = nil
+ end
+ if secondaryOff and secondaryOff:len() > 0 then
+ Keybind.defaultKeys[CHAT_MODE.OFF][secondaryOff] = nil
+ end
+
+ Keybind.defaultKeybinds[index] = nil
+end
+
+function Keybind.bind(category, action, callbacks, widget)
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+
+ if not keybind then
+ return
+ end
+
+ keybind.callbacks = callbacks
+ keybind.widget = widget
+
+ local keys = Keybind.getKeybindKeys(category, action)
+
+ for _, callback in ipairs(keybind.callbacks) do
+ if callback.type == KEY_UP then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.bindKeyUp(keys.primary, callback.callback, keybind.widget, callback.alone)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.bindKeyUp(keys.secondary, callback.callback, keybind.widget, callback.alone)
+ end
+ end
+ elseif callback.type == KEY_DOWN then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.bindKeyDown(keys.primary, callback.callback, keybind.widget, callback.alone)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.bindKeyDown(keys.secondary, callback.callback, keybind.widget, callback.alone)
+ end
+ end
+ elseif callback.type == KEY_PRESS then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.bindKeyPress(keys.primary, callback.callback, keybind.widget)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.bindKeyPress(keys.secondary, callback.callback, keybind.widget)
+ end
+ end
+ end
+ end
+end
+
+function Keybind.unbind(category, action)
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+
+ if not keybind or not keybind.callbacks then
+ return
+ end
+
+ local keys = Keybind.getKeybindKeys(category, action)
+
+ for _, callback in ipairs(keybind.callbacks) do
+ if callback.type == KEY_UP then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.unbindKeyUp(keys.primary, callback.callback, keybind.widget)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.unbindKeyUp(keys.secondary, callback.callback, keybind.widget)
+ end
+ end
+ elseif callback.type == KEY_DOWN then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.unbindKeyDown(keys.primary, callback.callback, keybind.widget)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.unbindKeyDown(keys.secondary, callback.callback, keybind.widget)
+ end
+ end
+ elseif callback.type == KEY_PRESS then
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ g_keyboard.unbindKeyPress(keys.primary, callback.callback, keybind.widget)
+ end
+ end
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ g_keyboard.unbindKeyPress(keys.secondary, callback.callback, keybind.widget)
+ end
+ end
+ end
+ end
+end
+
+function Keybind.newPreset(presetName)
+ if Keybind.presetToIndex[presetName] then
+ return
+ end
+
+ table.insert(Keybind.presets, presetName)
+ Keybind.presetToIndex[presetName] = #Keybind.presets
+
+ Keybind.configs.keybinds[presetName] = g_configs.create("/controls/keybinds/" .. presetName .. ".otml")
+ Keybind.configs.hotkeys[presetName] = g_configs.create("/controls/hotkeys/" .. presetName .. ".otml")
+
+ Keybind.hotkeys[CHAT_MODE.ON][presetName] = {}
+ Keybind.hotkeys[CHAT_MODE.OFF][presetName] = {}
+
+ g_settings.setList("controls-presets", Keybind.presets)
+ g_settings.save()
+end
+
+function Keybind.copyPreset(fromPreset, toPreset)
+ if Keybind.presetToIndex[toPreset] then
+ return false
+ end
+
+ table.insert(Keybind.presets, toPreset)
+ Keybind.presetToIndex[toPreset] = #Keybind.presets
+
+ Keybind.configs.keybinds[fromPreset]:save()
+ Keybind.configs.hotkeys[fromPreset]:save()
+
+ local keybindsConfigPath = Keybind.configs.keybinds[fromPreset]:getFileName()
+ local keybindsConfigContent = g_resources.readFileContents(keybindsConfigPath)
+ g_resources.writeFileContents("/controls/keybinds/" .. toPreset .. ".otml", keybindsConfigContent)
+ Keybind.configs.keybinds[toPreset] = g_configs.create("/controls/keybinds/" .. toPreset .. ".otml")
+
+ local hotkeysConfigPath = Keybind.configs.hotkeys[fromPreset]:getFileName()
+ local hotkeysConfigContent = g_resources.readFileContents(hotkeysConfigPath)
+ g_resources.writeFileContents("/controls/hotkeys/" .. toPreset .. ".otml", hotkeysConfigContent)
+ Keybind.configs.hotkeys[toPreset] = g_configs.create("/controls/hotkeys/" .. toPreset .. ".otml")
+
+ for chatMode = CHAT_MODE.ON, CHAT_MODE.OFF do
+ Keybind.hotkeys[chatMode][toPreset] = {}
+
+ local hotkeyId = 1
+ local hotkeys = Keybind.configs.hotkeys[toPreset]:getNode(chatMode)
+
+ if hotkeys then
+ local hotkey = hotkeys[tostring(hotkeyId)]
+ while hotkey do
+ if hotkey.data.parameter then
+ hotkey.data.parameter = "\"" .. hotkey.data.parameter .. "\"" -- forcing quotes cause OTML is not saving them, just wow
+ end
+
+ table.insert(Keybind.hotkeys[chatMode][toPreset], hotkey)
+ hotkeyId = hotkeyId + 1
+
+ hotkey = hotkeys[tostring(hotkeyId)]
+ end
+ end
+ end
+
+ g_settings.setList("controls-presets", Keybind.presets)
+ g_settings.save()
+
+ return true
+end
+
+function Keybind.renamePreset(oldPresetName, newPresetName)
+ if Keybind.currentPreset == oldPresetName then
+ Keybind.currentPreset = newPresetName
+ end
+
+ local index = Keybind.presetToIndex[oldPresetName]
+ Keybind.presetToIndex[oldPresetName] = nil
+ Keybind.presetToIndex[newPresetName] = index
+ Keybind.presets[index] = newPresetName
+
+ local keybindsConfigPath = Keybind.configs.keybinds[oldPresetName]:getFileName()
+ Keybind.configs.keybinds[oldPresetName]:save()
+ Keybind.configs.keybinds[oldPresetName] = nil
+
+ local keybindsConfigContent = g_resources.readFileContents(keybindsConfigPath)
+ g_resources.deleteFile(keybindsConfigPath)
+ g_resources.writeFileContents("/controls/keybinds/" .. newPresetName .. ".otml", keybindsConfigContent)
+ Keybind.configs.keybinds[newPresetName] = g_configs.create("/controls/keybinds/" .. newPresetName .. ".otml")
+
+ local hotkeysConfigPath = Keybind.configs.hotkeys[oldPresetName]:getFileName()
+ Keybind.configs.hotkeys[oldPresetName]:save()
+ Keybind.configs.hotkeys[oldPresetName] = nil
+
+ local hotkeysConfigContent = g_resources.readFileContents(hotkeysConfigPath)
+ g_resources.deleteFile(hotkeysConfigPath)
+ g_resources.writeFileContents("/controls/hotkeys/" .. newPresetName .. ".otml", hotkeysConfigContent)
+ Keybind.configs.hotkeys[newPresetName] = g_configs.create("/controls/hotkeys/" .. newPresetName .. ".otml")
+
+ Keybind.hotkeys[CHAT_MODE.ON][newPresetName] = Keybind.hotkeys[CHAT_MODE.ON][oldPresetName]
+ Keybind.hotkeys[CHAT_MODE.OFF][newPresetName] = Keybind.hotkeys[CHAT_MODE.OFF][oldPresetName]
+
+ g_settings.setList("controls-presets", Keybind.presets)
+ g_settings.save()
+end
+
+function Keybind.removePreset(presetName)
+ if #Keybind.presets == 1 then
+ return false
+ end
+
+ table.remove(Keybind.presets, Keybind.presetToIndex[presetName])
+ Keybind.presetToIndex[presetName] = nil
+
+ Keybind.configs.keybinds[presetName] = nil
+ g_configs.unload("/controls/keybinds/" .. presetName .. ".otml")
+ g_resources.deleteFile("/controls/keybinds/" .. presetName .. ".otml")
+
+ Keybind.configs.hotkeys[presetName] = nil
+ g_configs.unload("/controls/hotkeys/" .. presetName .. ".otml")
+ g_resources.deleteFile("/controls/hotkeys/" .. presetName .. ".otml")
+
+ if Keybind.currentPreset == presetName then
+ Keybind.currentPreset = Keybind.presets[1]
+ end
+
+ g_settings.setList("controls-presets", Keybind.presets)
+ g_settings.save()
+
+ return true
+end
+
+function Keybind.selectPreset(presetName)
+ if Keybind.currentPreset == presetName then
+ return false
+ end
+
+ if not Keybind.presetToIndex[presetName] then
+ return false
+ end
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.unbind(keybind.category, keybind.action)
+ end
+ end
+
+ for _, hotkey in ipairs(Keybind.hotkeys[Keybind.chatMode][Keybind.currentPreset]) do
+ Keybind.unbindHotkey(hotkey.hotkeyId, Keybind.chatMode)
+ end
+
+ Keybind.currentPreset = presetName
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.bind(keybind.category, keybind.action, keybind.callbacks, keybind.widget)
+ end
+ end
+
+ for _, hotkey in ipairs(Keybind.hotkeys[Keybind.chatMode][Keybind.currentPreset]) do
+ Keybind.bindHotkey(hotkey.hotkeyId, Keybind.chatMode)
+ end
+
+ return true
+end
+
+function Keybind.getAction(category, action)
+ local index = category .. '_' .. action
+ return Keybind.defaultKeybinds[index]
+end
+
+function Keybind.setPrimaryActionKey(category, action, preset, keyCombo, chatMode)
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+
+ local keys = Keybind.configs.keybinds[preset]:getNode(index)
+ if not keys then
+ keys = table.recursivecopy(keybind.keys)
+ else
+ chatMode = tostring(chatMode)
+ end
+
+ if keybind.callbacks then
+ Keybind.unbind(category, action)
+ end
+
+ if not keys[chatMode] then
+ keys[chatMode] = { primary = keyCombo, secondary = keybind.keys[tonumber(chatMode)].secondary }
+ end
+
+ keys[chatMode].primary = keyCombo
+
+ local ret = false
+ if keys[chatMode].secondary == keyCombo then
+ keys[chatMode].secondary = nil
+ ret = true
+ end
+
+ Keybind.configs.keybinds[preset]:setNode(index, keys)
+
+ if keybind.callbacks then
+ Keybind.bind(category, action, keybind.callbacks, keybind.widget)
+ end
+
+ return ret
+end
+
+function Keybind.setSecondaryActionKey(category, action, preset, keyCombo, chatMode)
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+
+ local keys = Keybind.configs.keybinds[preset]:getNode(index)
+ if not keys then
+ keys = table.recursivecopy(keybind.keys)
+ else
+ chatMode = tostring(chatMode)
+ end
+
+ if keybind.callbacks then
+ Keybind.unbind(category, action)
+ end
+
+ if not keys[chatMode] then
+ keys[chatMode] = { primary = keybind.keys[tonumber(chatMode)].primary, secondary = keyCombo }
+ end
+
+ keys[chatMode].secondary = keyCombo
+
+ local ret = false
+ if keys[chatMode].primary == keyCombo then
+ keys[chatMode].primary = nil
+ ret = true
+ end
+
+ Keybind.configs.keybinds[preset]:setNode(index, keys)
+
+ if keybind.callbacks then
+ Keybind.bind(category, action, keybind.callbacks, keybind.widget)
+ end
+
+ return ret
+end
+
+function Keybind.resetKeybindsToDefault(presetName, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.unbind(keybind.category, keybind.action)
+ end
+ end
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ local index = keybind.category .. '_' .. keybind.action
+ Keybind.configs.keybinds[presetName]:setNode(index, keybind.keys)
+ end
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.bind(keybind.category, keybind.action, keybind.callbacks, keybind.widget)
+ end
+ end
+end
+
+function Keybind.getKeybindKeys(category, action, chatMode, preset, forceDefault)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ local index = category .. '_' .. action
+ local keybind = Keybind.defaultKeybinds[index]
+ local keys = Keybind.configs.keybinds[preset or Keybind.currentPreset]:getNode(index)
+
+ if not keys or forceDefault then
+ keys = {
+ primary = keybind.keys[chatMode].primary,
+ secondary = keybind.keys[chatMode].secondary
+ }
+ else
+ keys = keys[chatMode] or keys[tostring(chatMode)]
+ end
+
+ if not keys then
+ keys = {
+ primary = "",
+ secondary = ""
+ }
+ end
+
+ return keys
+end
+
+function Keybind.isKeyComboUsed(keyCombo, category, action, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ if Keybind.reservedKeys[keyCombo] then
+ return true
+ end
+
+ if category and action then
+ local targetKeys = Keybind.getKeybindKeys(category, action, chatMode, Keybind.currentPreset)
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ local keys = Keybind.getKeybindKeys(keybind.category, keybind.action, chatMode, Keybind.currentPreset)
+ if (keys.primary == keyCombo and targetKeys.primary ~= keyCombo) or (keys.secondary == keyCombo and targetKeys.secondary ~= keyCombo) then
+ return true
+ end
+ end
+ else
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ local keys = Keybind.getKeybindKeys(keybind.category, keybind.action, chatMode, Keybind.currentPreset)
+ if keys.primary == keyCombo or keys.secondary == keyCombo then
+ return true
+ end
+ end
+
+ if Keybind.hotkeys[chatMode][Keybind.currentPreset] then
+ for _, hotkey in ipairs(Keybind.hotkeys[chatMode][Keybind.currentPreset]) do
+ if hotkey.primary == keyCombo or hotkey.secondary == keyCombo then
+ return true
+ end
+ end
+ end
+ end
+
+ return false
+end
+
+function Keybind.newHotkey(action, data, primary, secondary, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ local hotkey = {
+ action = action,
+ data = data,
+ primary = primary or "",
+ secondary = secondary or ""
+ }
+
+ if not Keybind.hotkeys[chatMode][Keybind.currentPreset] then
+ Keybind.hotkeys[chatMode][Keybind.currentPreset] = {}
+ end
+
+ table.insert(Keybind.hotkeys[chatMode][Keybind.currentPreset], hotkey)
+
+ local hotkeyId = #Keybind.hotkeys[chatMode][Keybind.currentPreset]
+ hotkey.hotkeyId = hotkeyId
+ Keybind.configs.hotkeys[Keybind.currentPreset]:setNode(chatMode, Keybind.hotkeys[chatMode][Keybind.currentPreset])
+ Keybind.configs.hotkeys[Keybind.currentPreset]:save()
+
+ Keybind.bindHotkey(hotkeyId, chatMode)
+end
+
+function Keybind.removeHotkey(hotkeyId, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ if not Keybind.hotkeys[chatMode][Keybind.currentPreset] then
+ return
+ end
+
+ Keybind.unbindHotkey(hotkeyId, chatMode)
+
+ table.remove(Keybind.hotkeys[chatMode][Keybind.currentPreset], hotkeyId)
+
+ Keybind.configs.hotkeys[Keybind.currentPreset]:clear()
+
+ for id, hotkey in ipairs(Keybind.hotkeys[chatMode][Keybind.currentPreset]) do
+ hotkey.hotkeyId = id
+ Keybind.configs.hotkeys[Keybind.currentPreset]:setNode(id, hotkey)
+ end
+
+ Keybind.configs.hotkeys[Keybind.currentPreset]:save()
+end
+
+function Keybind.editHotkey(hotkeyId, action, data, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ Keybind.unbindHotkey(hotkeyId, chatMode)
+
+ local hotkey = Keybind.hotkeys[chatMode][Keybind.currentPreset][hotkeyId]
+ hotkey.action = action
+ hotkey.data = data
+ Keybind.configs.hotkeys[Keybind.currentPreset]:setNode(chatMode, Keybind.hotkeys[chatMode][Keybind.currentPreset])
+ Keybind.configs.hotkeys[Keybind.currentPreset]:save()
+
+ Keybind.bindHotkey(hotkeyId, chatMode)
+end
+
+function Keybind.editHotkeyKeys(hotkeyId, primary, secondary, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ Keybind.unbindHotkey(hotkeyId, chatMode)
+
+ local hotkey = Keybind.hotkeys[chatMode][Keybind.currentPreset][hotkeyId]
+ hotkey.primary = primary or ""
+ hotkey.secondary = secondary or ""
+ Keybind.configs.hotkeys[Keybind.currentPreset]:setNode(chatMode, Keybind.hotkeys[chatMode][Keybind.currentPreset])
+ Keybind.configs.hotkeys[Keybind.currentPreset]:save()
+
+ Keybind.bindHotkey(hotkeyId, chatMode)
+end
+
+function Keybind.removeAllHotkeys(chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ for _, hotkey in ipairs(Keybind.hotkeys[chatMode][Keybind.currentPreset]) do
+ Keybind.unbindHotkey(hotkey.hotkeyId)
+ end
+
+ Keybind.hotkeys[chatMode][Keybind.currentPreset] = {}
+
+ Keybind.configs.hotkeys[Keybind.currentPreset]:remove(chatMode)
+ Keybind.configs.hotkeys[Keybind.currentPreset]:save()
+end
+
+function Keybind.getHotkeyKeys(hotkeyId, preset, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+ if not preset then
+ preset = Keybind.currentPreset
+ end
+
+ local keys = { primary = "", secondary = "" }
+ if not Keybind.hotkeys[chatMode][preset] then
+ return keys
+ end
+
+ local hotkey = Keybind.hotkeys[chatMode][preset][hotkeyId]
+ if not hotkey then
+ return keys
+ end
+
+ local config = Keybind.configs.hotkeys[preset]:getNode(chatMode)
+ if not config then
+ return keys
+ end
+
+ return config[tostring(hotkeyId)] or keys
+end
+
+function Keybind.hotkeyCallback(hotkeyId, chatMode)
+ if not chatMode then
+ chatMode = Keybind.chatMode
+ end
+
+ local hotkey = Keybind.hotkeys[chatMode][Keybind.currentPreset][hotkeyId]
+
+ if not hotkey then
+ return
+ end
+
+ local action = hotkey.action
+ local data = hotkey.data
+
+ if action == HOTKEY_ACTION.USE_YOURSELF then
+ if g_game.getClientVersion() < 780 then
+ local item = g_game.findPlayerItem(data.itemId, data.subType or -1)
+
+ if item then
+ g_game.useWith(item, g_game.getLocalPlayer())
+ end
+ else
+ g_game.useInventoryItemWith(data.itemId, g_game.getLocalPlayer(), data.subType or -1)
+ end
+ elseif action == HOTKEY_ACTION.USE_CROSSHAIR then
+ local item = Item.create(data.itemId)
+
+ if g_game.getClientVersion() < 780 then
+ item = g_game.findPlayerItem(data.itemId, data.subType or -1)
+ end
+
+ if item then
+ modules.game_interface.startUseWith(item, data.subType or -1)
+ end
+ elseif action == HOTKEY_ACTION.USE_TARGET then
+ local attackingCreature = g_game.getAttackingCreature()
+ if not attackingCreature then
+ local item = Item.create(data.itemId)
+
+ if g_game.getClientVersion() < 780 then
+ item = g_game.findPlayerItem(data.itemId, data.subType or -1)
+ end
+
+ if item then
+ modules.game_interface.startUseWith(item, data.subType or -1)
+ end
+
+ return
+ end
+
+ if attackingCreature:getTile() then
+ if g_game.getClientVersion() < 780 then
+ local item = g_game.findPlayerItem(data.itemId, data.subType or -1)
+ if item then
+ g_game.useWith(item, attackingCreature, data.subType or -1)
+ end
+ else
+ g_game.useInventoryItemWith(data.itemId, attackingCreature, data.subType or -1)
+ end
+ end
+ elseif action == HOTKEY_ACTION.EQUIP then
+ if g_game.getClientVersion() >= 910 then
+ local item = Item.create(data.itemId)
+
+ g_game.equipItem(item)
+ end
+ elseif action == HOTKEY_ACTION.USE then
+ if g_game.getClientVersion() < 780 then
+ local item = g_game.findPlayerItem(data.itemId, data.subType or -1)
+
+ if item then
+ g_game.use(item)
+ end
+ else
+ g_game.useInventoryItem(data.itemId)
+ end
+ elseif action == HOTKEY_ACTION.TEXT then
+ if modules.game_interface.isChatVisible() then
+ modules.game_console.setTextEditText(hotkey.data.text)
+ end
+ elseif action == HOTKEY_ACTION.TEXT_AUTO then
+ if modules.game_interface.isChatVisible() then
+ modules.game_console.sendMessage(hotkey.data.text)
+ else
+ g_game.talk(hotkey.data.text)
+ end
+ elseif action == HOTKEY_ACTION.SPELL then
+ local text = data.words
+ if data.parameter then
+ text = text .. " " .. data.parameter
+ end
+
+ if modules.game_interface.isChatVisible() then
+ modules.game_console.sendMessage(text)
+ else
+ g_game.talk(text)
+ end
+ end
+end
+
+function Keybind.bindHotkey(hotkeyId, chatMode)
+ if not chatMode or chatMode ~= Keybind.chatMode then
+ return
+ end
+
+ if not modules.game_interface then
+ return
+ end
+
+ local hotkey = Keybind.hotkeys[chatMode][Keybind.currentPreset][hotkeyId]
+
+ if not hotkey then
+ return
+ end
+
+ local keys = Keybind.getHotkeyKeys(hotkeyId, Keybind.currentPreset, chatMode)
+ local gameRootPanel = modules.game_interface.getRootPanel()
+ local action = hotkey.action
+
+ hotkey.callback = function() Keybind.hotkeyCallback(hotkeyId, chatMode) end
+
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ if action == HOTKEY_ACTION.EQUIP or action == HOTKEY_ACTION.USE or action == HOTKEY_ACTION.TEXT or action == HOTKEY_ACTION.TEXT_AUTO then
+ g_keyboard.bindKeyDown(keys.primary, hotkey.callback, gameRootPanel)
+ else
+ g_keyboard.bindKeyPress(keys.primary, hotkey.callback, gameRootPanel)
+ end
+ end
+ end
+
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ if action == HOTKEY_ACTION.EQUIP or action == HOTKEY_ACTION.USE or action == HOTKEY_ACTION.TEXT or action == HOTKEY_ACTION.TEXT_AUTO then
+ g_keyboard.bindKeyDown(keys.secondary, hotkey.callback, gameRootPanel)
+ else
+ g_keyboard.bindKeyPress(keys.secondary, hotkey.callback, gameRootPanel)
+ end
+ end
+ end
+end
+
+function Keybind.unbindHotkey(hotkeyId, chatMode)
+ if not chatMode or chatMode ~= Keybind.chatMode then
+ return
+ end
+
+ if not modules.game_interface then
+ return
+ end
+
+ local hotkey = Keybind.hotkeys[chatMode][Keybind.currentPreset][hotkeyId]
+
+ if not hotkey then
+ return
+ end
+
+ local keys = Keybind.getHotkeyKeys(hotkeyId, Keybind.currentPreset, chatMode)
+ local gameRootPanel = modules.game_interface.getRootPanel()
+ local action = hotkey.action
+
+ if keys.primary then
+ keys.primary = tostring(keys.primary)
+ if keys.primary:len() > 0 then
+ if action == HOTKEY_ACTION.EQUIP or action == HOTKEY_ACTION.USE or action == HOTKEY_ACTION.TEXT or action == HOTKEY_ACTION.TEXT_AUTO then
+ g_keyboard.unbindKeyDown(keys.primary, hotkey.callback, gameRootPanel)
+ else
+ g_keyboard.unbindKeyPress(keys.primary, hotkey.callback, gameRootPanel)
+ end
+ end
+ end
+
+ if keys.secondary then
+ keys.secondary = tostring(keys.secondary)
+ if keys.secondary:len() > 0 then
+ if action == HOTKEY_ACTION.EQUIP or action == HOTKEY_ACTION.USE or action == HOTKEY_ACTION.TEXT or action == HOTKEY_ACTION.TEXT_AUTO then
+ g_keyboard.unbindKeyDown(keys.secondary, hotkey.callback, gameRootPanel)
+ else
+ g_keyboard.unbindKeyPress(keys.secondary, hotkey.callback, gameRootPanel)
+ end
+ end
+ end
+end
+
+function Keybind.setChatMode(chatMode)
+ if Keybind.chatMode == chatMode then
+ return
+ end
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.unbind(keybind.category, keybind.action)
+ end
+ end
+
+ for _, hotkey in ipairs(Keybind.hotkeys[Keybind.chatMode][Keybind.currentPreset]) do
+ Keybind.unbindHotkey(hotkey.hotkeyId, Keybind.chatMode)
+ end
+
+ if modules.game_walking then
+ modules.game_walking.unbindTurnKeys()
+ end
+
+ Keybind.chatMode = chatMode
+
+ for _, keybind in pairs(Keybind.defaultKeybinds) do
+ if keybind.callbacks then
+ Keybind.bind(keybind.category, keybind.action, keybind.callbacks, keybind.widget)
+ end
+ end
+
+ for _, hotkey in ipairs(Keybind.hotkeys[chatMode][Keybind.currentPreset]) do
+ Keybind.bindHotkey(hotkey.hotkeyId, chatMode)
+ end
+
+ if modules.game_walking then
+ modules.game_walking.bindTurnKeys()
+ end
+end
diff --git a/modules/corelib/ui/uicombobox.lua b/modules/corelib/ui/uicombobox.lua
index feb856727c..d41dc122c7 100644
--- a/modules/corelib/ui/uicombobox.lua
+++ b/modules/corelib/ui/uicombobox.lua
@@ -199,3 +199,12 @@ function UIComboBox:HTML_onReadNodes(nodes)
return false
end
+
+function UIComboBox:getCurrentIndex()
+ return self.currentIndex
+end
+
+function UIComboBox:updateCurrentOption(newText)
+ self.options[self.currentIndex].text = newText
+ self:setText(newText)
+end
diff --git a/modules/corelib/ui/uipopupmenu.lua b/modules/corelib/ui/uipopupmenu.lua
index dd6e44f896..d02ae72bea 100644
--- a/modules/corelib/ui/uipopupmenu.lua
+++ b/modules/corelib/ui/uipopupmenu.lua
@@ -62,11 +62,11 @@ function UIPopupMenu:onGeometryChange(newRect, oldRect)
self:bindRectToParent()
end
-function UIPopupMenu:addOption(optionName, optionCallback, shortcut)
+function UIPopupMenu:addOption(optionName, optionCallback, shortcut, disabled)
local optionWidget = g_ui.createWidget(self:getStyleName() .. 'Button', self)
optionWidget.onClick = function(widget)
self:destroy()
- optionCallback()
+ optionCallback(self:getPosition())
end
optionWidget:setText(optionName)
local width = optionWidget:getTextSize().width + optionWidget:getMarginLeft() + optionWidget:getMarginRight() + 15
@@ -77,7 +77,7 @@ function UIPopupMenu:addOption(optionName, optionCallback, shortcut)
width = width + shortcutLabel:getTextSize().width + shortcutLabel:getMarginLeft() +
shortcutLabel:getMarginRight()
end
-
+ optionWidget:setEnabled(not disabled)
self:setWidth(math.max(190, math.max(self:getWidth(), width)))
end
diff --git a/modules/corelib/ui/uitabbar.lua b/modules/corelib/ui/uitabbar.lua
index 5a9722321b..5daf117a9c 100644
--- a/modules/corelib/ui/uitabbar.lua
+++ b/modules/corelib/ui/uitabbar.lua
@@ -48,7 +48,9 @@ function UITabBar:addTab(text, panel, icon)
tab.onClick = onTabClick
tab.onMouseRelease = onTabMouseRelease
tab.onDestroy = function()
- tab.tabPanel:destroy()
+ if not tab.tabPanel:isDestroyed() then
+ tab.tabPanel:destroy()
+ end
end
table.insert(self.tabs, tab)
diff --git a/modules/corelib/ui/uitable.lua b/modules/corelib/ui/uitable.lua
index a19e101f59..e1bae68fa5 100644
--- a/modules/corelib/ui/uitable.lua
+++ b/modules/corelib/ui/uitable.lua
@@ -223,7 +223,10 @@ function UITable:addRow(data, height)
self.columns[rowId] = {}
for colId, column in pairs(data) do
- local col = g_ui.createWidget(self.columBaseStyle, row)
+ local col = g_ui.createWidget(column.style or self.columBaseStyle, row)
+ if column.id then
+ col:setId(column.id)
+ end
if column.width then
col:setWidth(column.width)
else
@@ -235,11 +238,29 @@ function UITable:addRow(data, height)
if column.text then
col:setText(column.text)
end
+ if column.color then
+ col:setColor(column.color)
+ end
+ if column.coloredText then
+ col:parseColoredText(column.coloredText.text, column.coloredText.color)
+ end
if column.sortvalue then
col.sortvalue = column.sortvalue
else
col.sortvalue = column.text or 0
end
+ if column.marginTop then
+ col:setMarginTop(column.marginTop)
+ end
+ if column.marginBottom then
+ col:setMarginBottom(column.marginBottom)
+ end
+ if column.comboBox then
+ for _, comboValue in ipairs(column.comboBox) do
+ col:addOption(comboValue[1], comboValue[2])
+ end
+ end
+
table.insert(self.columns[rowId], col)
end
diff --git a/modules/corelib/ui/uiwidget.lua b/modules/corelib/ui/uiwidget.lua
index 85a26dbf53..9e6da7fbe2 100644
--- a/modules/corelib/ui/uiwidget.lua
+++ b/modules/corelib/ui/uiwidget.lua
@@ -18,3 +18,28 @@ function UIWidget:setMargin(...)
self:setMarginLeft(params[4])
end
end
+
+function UIWidget:parseColoredText(text, default_color)
+ local result = ""
+ local i = 1
+ while i <= #text do
+ local start, stop = text:find("%[color=.-%]", i)
+ if start then
+ result = result .. text:sub(i, start - 1)
+ local closing_tag_start, closing_tag_stop = text:find("%[/color%]", stop + 1)
+ if closing_tag_start then
+ local content = text:sub(stop + 1, closing_tag_start - 1)
+ local color_start, color_stop = text:find("#%x+", start)
+ local color = text:sub(color_start, color_stop) or default_color
+ result = result .. "{" .. content .. ", " .. color .. "}"
+ i = closing_tag_stop + 1
+ else
+ break
+ end
+ else
+ result = result .. text:sub(i)
+ break
+ end
+ end
+ self:setColoredText(result)
+end
diff --git a/modules/game_battle/battle.lua b/modules/game_battle/battle.lua
index dda3268f5a..7f9e438c28 100644
--- a/modules/game_battle/battle.lua
+++ b/modules/game_battle/battle.lua
@@ -69,7 +69,13 @@ function init() -- Initiating the module (load)
battleWindow = g_ui.loadUI('battle')
-- Binding Ctrl + B shortcut
- g_keyboard.bindKeyDown('Ctrl+B', toggle)
+ Keybind.new("Windows", "Show/hide battle list", "Ctrl+B", "")
+ Keybind.bind("Windows", "Show/hide battle list", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
-- Disabling scrollbar auto hiding
local scrollbar = battleWindow:getChildById('miniwindowScrollBar')
@@ -1087,7 +1093,7 @@ function terminate() -- Terminating the Module (unload)
filterPanel = nil
toggleFilterButton = nil
- g_keyboard.unbindKeyDown('Ctrl+B')
+ Keybind.delete("Windows", "Show/hide battle list")
disconnect(g_game, {
onAttackingCreatureChange = onAttack,
diff --git a/modules/game_bugreport/bugreport.lua b/modules/game_bugreport/bugreport.lua
index 56b622f296..0cbc0a838d 100644
--- a/modules/game_bugreport/bugreport.lua
+++ b/modules/game_bugreport/bugreport.lua
@@ -12,11 +12,17 @@ function init()
bugTextEdit = bugReportWindow:getChildById('bugTextEdit')
- g_keyboard.bindKeyDown(HOTKEY, show)
+ Keybind.new("Dialogs", "Open Bugreport", HOTKEY, "")
+ Keybind.bind("Dialogs", "Open Bugreport", {
+ {
+ type = KEY_DOWN,
+ callback = show,
+ }
+ }, modules.game_interface.getRootPanel())
end
function terminate()
- g_keyboard.unbindKeyDown(HOTKEY)
+ Keybind.delete("Dialogs", "Open Bugreport")
bugReportWindow:destroy()
end
diff --git a/modules/game_console/console.lua b/modules/game_console/console.lua
index 3d92211f0e..3b07f6e6a6 100644
--- a/modules/game_console/console.lua
+++ b/modules/game_console/console.lua
@@ -222,14 +222,8 @@ function init()
g_keyboard.bindKeyPress('Shift+Down', function()
navigateMessageHistory(-1)
end, consolePanel)
- g_keyboard.bindKeyPress('Tab', function()
- consoleTabBar:selectNextTab()
- end, consolePanel)
- g_keyboard.bindKeyPress('Shift+Tab', function()
- consoleTabBar:selectPrevTab()
- end, consolePanel)
+
g_keyboard.bindKeyDown('Enter', switchChatOnCall, consolePanel)
- g_keyboard.bindKeyDown('Enter', sendCurrentMessage, consolePanel)
g_keyboard.bindKeyDown('Escape', disableChatOnCall, consolePanel)
g_keyboard.bindKeyPress('Ctrl+A', function()
consoleTextEdit:clearText()
@@ -241,9 +235,52 @@ function init()
consoleTabBar.onTabChange = onTabChange
-- tibia like hotkeys
- g_keyboard.bindKeyDown('Ctrl+O', g_game.requestChannels)
- g_keyboard.bindKeyDown('Ctrl+E', removeCurrentTab)
- g_keyboard.bindKeyDown('Ctrl+H', openHelp)
+ local gameRootPanel = modules.game_interface.getRootPanel()
+ Keybind.new("Chat Channel", "Next Channel", "Tab", "")
+ Keybind.bind("Chat Channel", "Next Channel", {
+ {
+ type = KEY_PRESS,
+ callback = function() consoleTabBar:selectNextTab() end,
+ }
+ }, consolePanel)
+
+ Keybind.new("Chat Channel", "Previous Channel", "Shift+Tab", "")
+ Keybind.bind("Chat Channel", "Previous Channel", {
+ {
+ type = KEY_PRESS,
+ callback = function() consoleTabBar:selectPrevTab() end,
+ }
+ }, consolePanel)
+ Keybind.new("Chat", "Send current chat line", { [CHAT_MODE.ON] = "Enter", [CHAT_MODE.OFF] = "" }, "")
+ Keybind.bind("Chat", "Send current chat line", {
+ {
+ type = KEY_DOWN,
+ callback = sendCurrentMessage,
+ }
+ }, consolePanel)
+ Keybind.new("Chat Channel", "Open Channel List", "Ctrl+O", "")
+ Keybind.bind("Chat Channel", "Open Channel List", {
+ {
+ type = KEY_DOWN,
+ callback = g_game.requestChannels,
+ }
+ }, gameRootPanel)
+ Keybind.new("Chat Channel", "Close Current Channel", "Ctrl+E", "")
+
+ Keybind.bind("Chat Channel", "Close Current Channel", {
+ {
+ type = KEY_DOWN,
+ callback = removeCurrentTab,
+ }
+ }, gameRootPanel)
+
+ Keybind.new("Chat Channel", "Open Help Channel", "Ctrl+H", "")
+ Keybind.bind("Chat Channel", "Open Help Channel", {
+ {
+ type = KEY_DOWN,
+ callback = openHelp,
+ }
+ }, consolePanel)
-- toggle WASD
consoleToggleChat = consolePanel:getChildById('toggleChat')
@@ -340,9 +377,11 @@ function switchChat(enabled)
if enabled then
unbindMovingKeys()
consoleToggleChat:setTooltip(tr('Disable chat mode, allow to walk using WASD'))
+ Keybind.setChatMode(CHAT_MODE.ON)
else
bindMovingKeys()
consoleToggleChat:setTooltip(tr('Enable chat mode'))
+ Keybind.setChatMode(CHAT_MODE.OFF)
end
end
@@ -401,10 +440,12 @@ function terminate()
clear()
end
- g_keyboard.unbindKeyDown('Ctrl+O')
- g_keyboard.unbindKeyDown('Ctrl+E')
- g_keyboard.unbindKeyDown('Ctrl+H')
-
+ Keybind.delete("Chat Channel", "Close Current Channel")--
+ Keybind.delete("Chat Channel", "Next Channel")--
+ Keybind.delete("Chat Channel", "Previous Channel")--
+ Keybind.delete("Chat Channel", "Open Channel List")--
+ Keybind.delete("Chat Channel", "Open Help Channel")--
+ Keybind.delete("Chat", "Send current chat line")
saveCommunicationSettings()
if channelsWindow then
@@ -1994,7 +2035,14 @@ function online()
tab.npcChat = true
end
if g_game.getClientVersion() < 862 then
- g_keyboard.bindKeyDown('Ctrl+R', openPlayerReportRuleViolationWindow)
+ Keybind.new("Dialogs", "Open Rule Violation", "Ctrl+R", "")
+ local gameRootPanel = modules.game_interface.getRootPanel()
+ Keybind.bind("Dialogs", "Open Rule Violation", {
+ {
+ type = KEY_DOWN,
+ callback = openPlayerReportRuleViolationWindow,
+ }
+ }, gameRootPanel)
end
-- open last channels
local lastChannelsOpen = g_settings.getNode('lastChannelsOpen')
@@ -2019,7 +2067,7 @@ end
function offline()
if g_game.getClientVersion() < 862 then
- g_keyboard.unbindKeyDown('Ctrl+R')
+ Keybind.delete("Dialogs", "Open Rule Violation")
end
clear()
end
diff --git a/modules/game_cooldown/cooldown.otui b/modules/game_cooldown/cooldown.otui
index 8153669ec8..b4d1086631 100644
--- a/modules/game_cooldown/cooldown.otui
+++ b/modules/game_cooldown/cooldown.otui
@@ -29,6 +29,8 @@ Panel
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
+ focusable: false
+ phantom: true
Panel
id:contentsPanel2
anchors.fill: parent
diff --git a/modules/game_cyclopedia/game_cyclopedia.lua b/modules/game_cyclopedia/game_cyclopedia.lua
index ad1c906491..535085edb0 100644
--- a/modules/game_cyclopedia/game_cyclopedia.lua
+++ b/modules/game_cyclopedia/game_cyclopedia.lua
@@ -33,7 +33,6 @@ controllerCyclopedia = Controller:new()
controllerCyclopedia:setUI('game_cyclopedia')
function controllerCyclopedia:onInit()
-
end
function controllerCyclopedia:onGameStart()
@@ -168,6 +167,19 @@ function controllerCyclopedia:onGameStart()
trackerMiniWindow:setupOnStart()
loadFilters()
Cyclopedia.BossSlots.UnlockBosses = {}
+ Keybind.new("Windows", "Show/hide Bosstiary Tracker", "", "")
+
+ Keybind.bind("Windows", "Show/hide Bosstiary Tracker", {{
+ type = KEY_DOWN,
+ callback = Cyclopedia.toggleBosstiaryTracker
+ }})
+
+ Keybind.new("Windows", "Show/hide Bestiary Tracker", "", "")
+ Keybind.bind("Windows", "Show/hide Bestiary Tracker", {{
+ type = KEY_DOWN,
+ callback = Cyclopedia.toggleBestiaryTracker
+ }})
+
end
end
@@ -179,6 +191,8 @@ function controllerCyclopedia:onGameEnd()
end
hide()
saveFilters()
+ Keybind.delete("Windows", "Show/hide Bosstiary Tracker")
+ Keybind.delete("Windows", "Show/hide Bestiary Tracker")
end
function controllerCyclopedia:onTerminate()
diff --git a/modules/game_hotkeys/hotkeys_manager.lua b/modules/game_hotkeys/hotkeys_manager.lua
index 941758480c..3bef1c9ef6 100644
--- a/modules/game_hotkeys/hotkeys_manager.lua
+++ b/modules/game_hotkeys/hotkeys_manager.lua
@@ -64,7 +64,13 @@ local hotkeysWindowButton = nil
-- public functions
function init()
- g_keyboard.bindKeyDown('Ctrl+K', toggle)
+ Keybind.new("Windows", "Show/hide Hotkeys", "Ctrl+K", "")
+ Keybind.bind("Windows", "Show/hide Hotkeys", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
hotkeysWindow = g_ui.displayUI('hotkeys_manager')
hotkeysWindow:setVisible(false)
hotkeysWindowButton = modules.client_topmenu.addRightGameToggleButton('hotkeysWindowButton', tr('Hotkeys'), '/images/options/hotkeys', toggle)
@@ -128,7 +134,7 @@ function terminate()
onGameEnd = offline
})
- g_keyboard.unbindKeyDown('Ctrl+K')
+ Keybind.delete("Windows", "Show/hide Hotkeys")
unload()
diff --git a/modules/game_interface/gameinterface.lua b/modules/game_interface/gameinterface.lua
index 1f87592706..09f30763b1 100644
--- a/modules/game_interface/gameinterface.lua
+++ b/modules/game_interface/gameinterface.lua
@@ -154,25 +154,41 @@ function bindKeys()
bindTurnKey('Ctrl+Numpad2', South)
bindTurnKey('Ctrl+Numpad4', West)
- g_keyboard.bindKeyPress('Escape', function()
- g_game.cancelAttackAndFollow()
- end, gameRootPanel)
g_keyboard.bindKeyPress('Ctrl+=', function()
gameMapPanel:zoomIn()
end, gameRootPanel)
g_keyboard.bindKeyPress('Ctrl+-', function()
gameMapPanel:zoomOut()
end, gameRootPanel)
- g_keyboard.bindKeyDown('Ctrl+Q', function()
- tryLogout(false)
- end, gameRootPanel)
- g_keyboard.bindKeyDown('Ctrl+L', function()
- tryLogout(false)
- end, gameRootPanel)
- g_keyboard.bindKeyDown('Alt+W', function()
- g_map.cleanTexts()
- modules.game_textmessage.clearMessages()
- end, gameRootPanel)
+
+ Keybind.new("Movement", "Stop All Actions", "Esc", "", true)
+ Keybind.bind("Movement", "Stop All Actions", {
+ {
+ type = KEY_PRESS,
+ callback = function()
+ g_game.cancelAttackAndFollow()
+ end,
+ }
+ }, gameRootPanel)
+
+ Keybind.new("Misc", "Logout", "Ctrl+L", "Ctrl+Q")
+ Keybind.bind("Misc", "Logout", {
+ {
+ type = KEY_PRESS,
+ callback = function() tryLogout(false) end,
+ }
+ }, gameRootPanel)
+
+ Keybind.new("UI", "Clear All Texts", "Ctrl+W", "")
+ Keybind.bind("UI", "Clear All Texts", {
+ {
+ type = KEY_DOWN,
+ callback = function()
+ g_map.cleanTexts()
+ modules.game_textmessage.clearMessages()
+ end,
+ }
+ }, gameRootPanel)
g_keyboard.bindKeyDown('Ctrl+.', nextViewMode, gameRootPanel)
end
@@ -251,6 +267,9 @@ function terminate()
logoutButton:destroy()
gameRootPanel:destroy()
+ Keybind.delete("Movement", "Stop All Actions")
+ Keybind.delete("Misc", "Logout")
+ Keybind.delete("UI", "Clear All Texts")
end
function onGameStart()
diff --git a/modules/game_playermount/playermount.lua b/modules/game_playermount/playermount.lua
index d29596ff37..477c040851 100644
--- a/modules/game_playermount/playermount.lua
+++ b/modules/game_playermount/playermount.lua
@@ -18,13 +18,19 @@ end
function online()
if g_game.getFeature(GamePlayerMounts) then
- g_keyboard.bindKeyDown('Ctrl+R', toggleMount)
+ Keybind.new("Movement", "Mount/dismount", "Ctrl+R", "")
+ Keybind.bind("Movement", "Mount/dismount", {
+ {
+ type = KEY_DOWN,
+ callback = toggleMount,
+ }
+ })
end
end
function offline()
if g_game.getFeature(GamePlayerMounts) then
- g_keyboard.unbindKeyDown('Ctrl+R')
+ Keybind.delete("Movement", "Mount/dismount")
end
end
diff --git a/modules/game_questlog/questlog.lua b/modules/game_questlog/questlog.lua
index bb3138e618..a6dccf23ea 100644
--- a/modules/game_questlog/questlog.lua
+++ b/modules/game_questlog/questlog.lua
@@ -15,6 +15,16 @@ function init()
onQuestLine = onGameQuestLine,
onGameEnd = destroyWindows
})
+
+ Keybind.new("Windows", "Show/hide quest Log", "", "")
+ Keybind.bind("Windows", "Show/hide quest Log", {
+ {
+ type = KEY_DOWN,
+ callback = function()
+ g_game.requestQuestLog()
+ end,
+ }
+ })
end
function terminate()
@@ -27,6 +37,7 @@ function terminate()
destroyWindows()
questLogButton:destroy()
questLogButton = nil
+ Keybind.delete("Windows", "Show/hide quest Log")
end
function destroyWindows()
diff --git a/modules/game_ruleviolation/ruleviolation.lua b/modules/game_ruleviolation/ruleviolation.lua
index 61e4609fca..66e7935dc3 100644
--- a/modules/game_ruleviolation/ruleviolation.lua
+++ b/modules/game_ruleviolation/ruleviolation.lua
@@ -45,7 +45,7 @@ function init()
reasonsTextList = ruleViolationWindow:getChildById('reasonList')
actionsTextList = ruleViolationWindow:getChildById('actionList')
- g_keyboard.bindKeyDown('Ctrl+Y', function()
+ g_keyboard.bindKeyDown('Ctrl+U', function()
show()
end)
@@ -58,7 +58,7 @@ function terminate()
disconnect(g_game, {
onGMActions = loadReasons
})
- g_keyboard.unbindKeyDown('Ctrl+Y')
+ g_keyboard.unbindKeyDown('Ctrl+U')
ruleViolationWindow:destroy()
end
diff --git a/modules/game_shaders/shaders.lua b/modules/game_shaders/shaders.lua
index 1418b29fca..0b75c66a25 100644
--- a/modules/game_shaders/shaders.lua
+++ b/modules/game_shaders/shaders.lua
@@ -124,19 +124,23 @@ function ShaderController:onInit()
for _, opts in pairs(MOUNT_SHADERS) do
registerShader(opts, 'setupMountShader')
end
+ Keybind.new('Windows', 'show/hide Shader Windows', HOTKEY, '')
+ Keybind.bind('Windows', 'show/hide Shader Windows', {
+ {
+ type = KEY_DOWN,
+ callback = function() ShaderController.ui:setVisible(not ShaderController.ui:isVisible()) end,
+ }
+ })
end
function ShaderController:onTerminate()
g_shaders.clear()
+ Keybind.delete('Windows', 'show/hide Shader Windows')
end
function ShaderController:onGameStart()
attachShaders()
- self:bindKeyDown(HOTKEY, function()
- ShaderController.ui:setVisible(not ShaderController.ui:isVisible())
- end)
-
self:loadHtml('shaders.html', modules.game_interface.getMapPanel())
for _, opts in pairs(MAP_SHADERS) do
diff --git a/modules/game_skills/skills.lua b/modules/game_skills/skills.lua
index 9363934b7e..7c9294b383 100644
--- a/modules/game_skills/skills.lua
+++ b/modules/game_skills/skills.lua
@@ -31,7 +31,13 @@ function init()
skillsButton:setOn(true)
skillsWindow = g_ui.loadUI('skills')
- g_keyboard.bindKeyDown('Alt+S', toggle)
+ Keybind.new("Windows", "Show/hide skills windows", "Alt+S", "")
+ Keybind.bind("Windows", "Show/hide skills windows", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
skillSettings = g_settings.getNode('skills-hide')
if not skillSettings then
@@ -69,7 +75,7 @@ function terminate()
onGameEnd = offline
})
- g_keyboard.unbindKeyDown('Alt+S')
+ Keybind.delete("Windows", "Show/hide skills windows")
skillsWindow:destroy()
skillsButton:destroy()
diff --git a/modules/game_spelllist/spelllist.lua b/modules/game_spelllist/spelllist.lua
index 7d9f682a8f..787ed76548 100644
--- a/modules/game_spelllist/spelllist.lua
+++ b/modules/game_spelllist/spelllist.lua
@@ -176,6 +176,13 @@ function init()
if g_game.isOnline() then
online()
end
+ Keybind.new("Windows", "Show/hide spell list", "Alt+L", "")
+ Keybind.bind("Windows", "Show/hide spell list", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
end
function terminate()
@@ -199,6 +206,7 @@ function terminate()
vocationRadioGroup:destroy()
groupRadioGroup:destroy()
premiumRadioGroup:destroy()
+ Keybind.delete("Windows", "Show/hide spell list")
end
function initializeSpelllist()
diff --git a/modules/game_tasks/tasks.lua b/modules/game_tasks/tasks.lua
index 91679d3a18..bedf3401ab 100644
--- a/modules/game_tasks/tasks.lua
+++ b/modules/game_tasks/tasks.lua
@@ -12,7 +12,14 @@ function init()
window = g_ui.displayUI('tasks')
window:setVisible(false)
- g_keyboard.bindKeyDown('Ctrl+A', toggleWindow)
+ Keybind.new('Windows', 'show/hide Tasks Windows', 'Ctrl+A', '')
+ Keybind.bind('Windows', 'show/hide Tasks Windows', {
+ {
+ type = KEY_DOWN,
+ callback = toggleWindow,
+ }
+ })
+
g_keyboard.bindKeyDown('Escape', hideWindowzz)
taskButton = modules.client_topmenu.addLeftGameButton('taskButton', tr('Tasks'), '/modules/game_tasks/images/taskIcon', toggleWindow)
ProtocolGame.registerExtendedJSONOpcode(215, parseOpcode)
@@ -25,6 +32,7 @@ function terminate()
ProtocolGame.unregisterExtendedJSONOpcode(215, parseOpcode)
taskButton:destroy()
destroy()
+ Keybind.delete('Windows', 'show/hide Tasks Windows')
end
function onGameStart()
diff --git a/modules/game_viplist/viplist.lua b/modules/game_viplist/viplist.lua
index 1c590d66b9..381ebe8b46 100644
--- a/modules/game_viplist/viplist.lua
+++ b/modules/game_viplist/viplist.lua
@@ -20,8 +20,13 @@ local globalSettings = {
controllerVip = Controller:new()
function controllerVip:onInit()
- g_keyboard.bindKeyDown('Ctrl+P', toggle)
-
+ Keybind.new("Windows", "Show/hide VIP list", "Ctrl+P", "")
+ Keybind.bind("Windows", "Show/hide VIP list", {
+ {
+ type = KEY_DOWN,
+ callback = toggle,
+ }
+ })
vipButton = modules.game_mainpanel.addToggleButton('vipListButton', tr('VIP List') .. ' (Ctrl+P)',
'/images/options/button_vip', toggle, false, 3)
vipWindow = g_ui.loadUI('viplist')
@@ -50,7 +55,7 @@ function controllerVip:onInit()
end
function controllerVip:onTerminate()
- g_keyboard.unbindKeyDown('Ctrl+P')
+ Keybind.delete("Windows", "Show/hide VIP list")
local ArrayWidgets = {addVipWindow, editVipWindow, vipWindow, vipButton, addGroupWindow}
for _, widget in ipairs(ArrayWidgets) do
if widget ~= nil or widget then
diff --git a/modules/gamelib/const.lua b/modules/gamelib/const.lua
index cf9a62f38a..230d59bf08 100644
--- a/modules/gamelib/const.lua
+++ b/modules/gamelib/const.lua
@@ -74,6 +74,17 @@ SouthEast = Directions.SouthEast
SouthWest = Directions.SouthWest
NorthWest = Directions.NorthWest
+DirectionString = {
+ [North] = "North",
+ [East] = "East",
+ [South] = "South",
+ [West] = "West",
+ [NorthEast] = "North East",
+ [SouthEast] = "South East",
+ [SouthWest] = "South West",
+ [NorthWest] = "North West"
+ }
+
FightOffensive = 1
FightBalanced = 2
FightDefensive = 3
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 3fde99b724..c797894b25 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -444,6 +444,7 @@ endif()
target_sources(${PROJECT_NAME} PRIVATE ${SOURCE_FILES})
+target_link_options(${PROJECT_NAME} PUBLIC -flto=auto)
# *****************************************************************************
# Includes and librarys
diff --git a/src/client/animatedtext.cpp b/src/client/animatedtext.cpp
index 27b394c932..37b0c6c9ff 100644
--- a/src/client/animatedtext.cpp
+++ b/src/client/animatedtext.cpp
@@ -21,11 +21,11 @@
*/
#include "animatedtext.h"
-#include
-#include
#include "game.h"
-#include "map.h"
#include "gameconfig.h"
+#include "map.h"
+#include
+#include
AnimatedText::AnimatedText()
{
diff --git a/src/client/animatedtext.h b/src/client/animatedtext.h
index b6ff5af8d2..744a95fea7 100644
--- a/src/client/animatedtext.h
+++ b/src/client/animatedtext.h
@@ -29,11 +29,11 @@
#include
// @bindclass
-class AnimatedText : public LuaObject
+class AnimatedText final : public LuaObject
{
public:
AnimatedText();
- AnimatedText(const std::string_view text, int color) : AnimatedText() {
+ AnimatedText(const std::string_view text, const int color) : AnimatedText() {
setText(text);
setColor(color);
}
@@ -42,7 +42,7 @@ class AnimatedText : public LuaObject
void onAppear();
- void setColor(int color) { m_color = Color::from8bit(color); }
+ void setColor(const int color) { m_color = Color::from8bit(color); }
void setText(const std::string_view text) { m_cachedText.setText(text); }
void setOffset(const Point& offset) { m_offset = offset; }
diff --git a/src/client/animator.cpp b/src/client/animator.cpp
index 1c7d86be9c..40de10365e 100644
--- a/src/client/animator.cpp
+++ b/src/client/animator.cpp
@@ -43,7 +43,7 @@ void Animator::unserializeAppearance(const appearances::SpriteAnimation& animati
assert(m_startPhase >= -1 && m_startPhase < m_animationPhases);
}
-void Animator::unserialize(int animationPhases, const FileStreamPtr& fin)
+void Animator::unserialize(const int animationPhases, const FileStreamPtr& fin)
{
m_animationPhases = animationPhases;
m_async = fin->getU8() == 0;
@@ -77,7 +77,7 @@ void Animator::serialize(const FileStreamPtr& fin) const
}
}
-void Animator::setPhase(int phase)
+void Animator::setPhase(const int phase)
{
if (m_phase == phase)
return;
@@ -133,7 +133,7 @@ int Animator::getPhase()
return m_phase;
}
-int Animator::getPhaseAt(Timer& timer, float durationFactor) const
+int Animator::getPhaseAt(Timer& timer, const float durationFactor) const
{
const ticks_t time = timer.ticksElapsed();
@@ -195,7 +195,7 @@ int Animator::getLoopPhase()
return m_phase;
}
-int Animator::getPhaseDuration(int phase) const
+int Animator::getPhaseDuration(const int phase) const
{
assert(phase < static_cast(m_phaseDurations.size()));
diff --git a/src/client/attachableobject.cpp b/src/client/attachableobject.cpp
index 8d796f87cf..8c2a733dc4 100644
--- a/src/client/attachableobject.cpp
+++ b/src/client/attachableobject.cpp
@@ -21,13 +21,15 @@
*/
#include "attachableobject.h"
-#include
#include
+#include
#include
-#include
#include
#include
+#include
+
+#include
#include "client.h"
#include "game.h"
@@ -55,7 +57,7 @@ void AttachableObject::attachEffect(const AttachedEffectPtr& obj)
++m_ownerHidden;
if (obj->getDuration() > 0) {
- g_dispatcher.scheduleEvent([self = std::static_pointer_cast(shared_from_this()), effect = obj]() {
+ g_dispatcher.scheduleEvent([self = std::static_pointer_cast(shared_from_this()), effect = obj] {
self->detachEffect(effect);
}, obj->getDuration());
}
@@ -95,7 +97,7 @@ bool AttachableObject::detachEffectById(uint16_t id)
return true;
}
-void AttachableObject::onDetachEffect(const AttachedEffectPtr& effect, bool callEvent)
+void AttachableObject::onDetachEffect(const AttachedEffectPtr& effect, const bool callEvent)
{
if (effect->isHidedOwner())
--m_ownerHidden;
@@ -106,7 +108,7 @@ void AttachableObject::onDetachEffect(const AttachedEffectPtr& effect, bool call
effect->callLuaField("onDetach", attachedObjectToLuaObject());
}
-void AttachableObject::clearAttachedEffects(bool ignoreLuaEvent)
+void AttachableObject::clearAttachedEffects(const bool ignoreLuaEvent)
{
if (!hasAttachedEffects()) return;
for (const auto& e : m_data->attachedEffects)
@@ -117,27 +119,27 @@ void AttachableObject::clearAttachedEffects(bool ignoreLuaEvent)
void AttachableObject::clearTemporaryAttachedEffects()
{
if (!hasAttachedEffects()) return;
- m_data->attachedEffects.erase(std::remove_if(m_data->attachedEffects.begin(), m_data->attachedEffects.end(),
- [this](const AttachedEffectPtr& obj) {
+ std::erase_if(m_data->attachedEffects,
+ [this](const AttachedEffectPtr& obj) {
if (!obj->isPermanent()) {
onDetachEffect(obj);
return true;
}
return false;
- }), m_data->attachedEffects.end());
+ });
}
void AttachableObject::clearPermanentAttachedEffects()
{
if (!hasAttachedEffects()) return;
- m_data->attachedEffects.erase(std::remove_if(m_data->attachedEffects.begin(), m_data->attachedEffects.end(),
- [this](const AttachedEffectPtr& obj) {
+ std::erase_if(m_data->attachedEffects,
+ [this](const AttachedEffectPtr& obj) {
if (obj->isPermanent()) {
onDetachEffect(obj);
return true;
}
return false;
- }), m_data->attachedEffects.end());
+ });
}
AttachedEffectPtr AttachableObject::getAttachedEffectById(uint16_t id)
@@ -152,13 +154,13 @@ AttachedEffectPtr AttachableObject::getAttachedEffectById(uint16_t id)
return *it;
}
-void AttachableObject::drawAttachedEffect(const Point& dest, const LightViewPtr& lightView, bool isOnTop)
+void AttachableObject::drawAttachedEffect(const Point& dest, const LightViewPtr& lightView, const bool isOnTop)
{
if (!hasAttachedEffects()) return;
for (const auto& effect : m_data->attachedEffects) {
effect->draw(dest, isOnTop, lightView);
if (effect->getLoop() == 0) {
- g_dispatcher.addEvent([self = std::static_pointer_cast(shared_from_this()), effect]() {
+ g_dispatcher.addEvent([self = std::static_pointer_cast(shared_from_this()), effect] {
self->detachEffect(effect);
});
}
@@ -228,7 +230,7 @@ void AttachableObject::updateAndAttachParticlesEffects(std::vector&
toRemove.reserve(m_data->attachedParticles.size());
for (const auto& effect : m_data->attachedParticles) {
- auto findPos = std::find(newElements.begin(), newElements.end(), effect->getEffectType()->getName());
+ auto findPos = std::ranges::find(newElements, effect->getEffectType()->getName());
if (findPos == newElements.end())
toRemove.emplace_back(effect->getEffectType()->getName());
else
@@ -262,7 +264,7 @@ void AttachableObject::attachWidget(const UIWidgetPtr& widget) {
getData()->attachedWidgets.emplace_back(widget);
g_map.addAttachedWidgetToObject(widget, std::static_pointer_cast(shared_from_this()));
widget->callLuaField("onAttached", asLuaObject());
- widget->addOnDestroyCallback("attached-widget-destroy", [this, widget]() {
+ widget->addOnDestroyCallback("attached-widget-destroy", [this, widget] {
detachWidget(widget);
});
}
@@ -301,12 +303,12 @@ bool AttachableObject::detachWidget(const UIWidgetPtr widget)
return true;
}
-void AttachableObject::clearAttachedWidgets(bool callEvent)
+void AttachableObject::clearAttachedWidgets(const bool callEvent)
{
if (!hasAttachedWidgets()) return;
// keep the same behavior as detachWidget
- auto oldList = std::move(m_data->attachedWidgets);
+ const auto oldList = std::move(m_data->attachedWidgets);
m_data->attachedWidgets.clear();
for (const auto& widget : oldList) {
diff --git a/src/client/attachableobject.h b/src/client/attachableobject.h
index 35c880ddc0..0e9cb12904 100644
--- a/src/client/attachableobject.h
+++ b/src/client/attachableobject.h
@@ -31,7 +31,7 @@ class AttachableObject : public LuaObject
{
public:
AttachableObject() = default;
- virtual ~AttachableObject();
+ ~AttachableObject() override;
virtual LuaObjectPtr attachedObjectToLuaObject() = 0;
virtual bool isTile() { return false; }
@@ -45,9 +45,9 @@ class AttachableObject : public LuaObject
bool detachEffect(const AttachedEffectPtr& obj);
AttachedEffectPtr getAttachedEffectById(uint16_t id);
- virtual void onStartAttachEffect(const AttachedEffectPtr& /*effect*/) { };
- virtual void onDispatcherAttachEffect(const AttachedEffectPtr& /*effect*/) { };
- virtual void onStartDetachEffect(const AttachedEffectPtr& /*effect*/) { };
+ virtual void onStartAttachEffect(const AttachedEffectPtr& /*effect*/) {};
+ virtual void onDispatcherAttachEffect(const AttachedEffectPtr& /*effect*/) {};
+ virtual void onStartDetachEffect(const AttachedEffectPtr& /*effect*/) {};
bool isOwnerHidden() { return m_ownerHidden > 0; }
@@ -67,7 +67,7 @@ class AttachableObject : public LuaObject
void attachWidget(const UIWidgetPtr& widget);
void clearAttachedWidgets(bool callEvent = true);
bool detachWidgetById(const std::string& id);
- bool detachWidget(const UIWidgetPtr widget);
+ bool detachWidget(UIWidgetPtr widget);
UIWidgetPtr getAttachedWidgetById(const std::string& id);
protected:
@@ -84,7 +84,7 @@ class AttachableObject : public LuaObject
void onDetachEffect(const AttachedEffectPtr& effect, bool callEvent = true);
void drawAttachedParticlesEffect(const Point& dest);
- inline auto getData() {
+ auto getData() {
if (!m_data)
m_data = std::make_shared();
return m_data;
diff --git a/src/client/attachedeffect.cpp b/src/client/attachedeffect.cpp
index ca65cab747..7f083e9c2b 100644
--- a/src/client/attachedeffect.cpp
+++ b/src/client/attachedeffect.cpp
@@ -25,11 +25,11 @@
#include "lightview.h"
#include
-#include
#include
#include
+#include
-AttachedEffectPtr AttachedEffect::create(uint16_t thingId, ThingCategory category) {
+AttachedEffectPtr AttachedEffect::create(const uint16_t thingId, const ThingCategory category) {
if (!g_things.isValidDatId(thingId, category)) {
g_logger.error(stdext::format("AttachedEffectManager::getInstance(%d, %d): invalid thing with id or category.", thingId, static_cast(category)));
return nullptr;
@@ -71,7 +71,7 @@ int getBounce(const AttachedEffect::Bounce bounce, const ticks_t ticks) {
return minHeight + (height - std::abs(height - static_cast(ticks / (bounce.speed / 100.f)) % static_cast(height * 2)));
}
-void AttachedEffect::draw(const Point& dest, bool isOnTop, const LightViewPtr& lightView, const bool drawThing) {
+void AttachedEffect::draw(const Point& dest, const bool isOnTop, const LightViewPtr& lightView, const bool drawThing) {
if (m_transform)
return;
diff --git a/src/client/attachedeffect.h b/src/client/attachedeffect.h
index a2066d1763..bf5711e03c 100644
--- a/src/client/attachedeffect.h
+++ b/src/client/attachedeffect.h
@@ -22,15 +22,15 @@
#pragma once
-#include "thingtype.h"
#include "outfit.h"
+#include "thingtype.h"
-class AttachedEffect : public LuaObject
+class AttachedEffect final : public LuaObject
{
public:
static AttachedEffectPtr create(uint16_t thingId, ThingCategory category);
- void draw(const Point& /*dest*/, bool /*isOnTop*/, const LightViewPtr & = nullptr, const bool drawThing = true);
+ void draw(const Point& /*dest*/, bool /*isOnTop*/, const LightViewPtr & = nullptr, bool drawThing = true);
void drawLight(const Point& /*dest*/, const LightViewPtr&);
uint16_t getId() { return m_id; }
@@ -38,31 +38,31 @@ class AttachedEffect : public LuaObject
AttachedEffectPtr clone();
float getSpeed() { return m_speed / 100.f; }
- void setSpeed(float speed) { m_speed = speed * 100u; }
+ void setSpeed(const float speed) { m_speed = speed * 100u; }
float getOpacity() { return m_opacity / 100.f; }
- void setOpacity(float opacity) { m_opacity = opacity * 100u; }
+ void setOpacity(const float opacity) { m_opacity = opacity * 100u; }
Size getSize() { return m_size; }
void setSize(const Size& s) { m_size = s; }
bool isHidedOwner() { return m_hideOwner; }
- void setHideOwner(bool v) { m_hideOwner = v; }
+ void setHideOwner(const bool v) { m_hideOwner = v; }
bool isTransform() { return m_transform; }
- void setTransform(bool v) { m_transform = v; }
+ void setTransform(const bool v) { m_transform = v; }
bool isDisabledWalkAnimation() { return m_disableWalkAnimation; }
- void setDisableWalkAnimation(bool v) { m_disableWalkAnimation = v; }
+ void setDisableWalkAnimation(const bool v) { m_disableWalkAnimation = v; }
bool isPermanent() { return m_permanent; }
- void setPermanent(bool permanent) { m_permanent = permanent; }
+ void setPermanent(const bool permanent) { m_permanent = permanent; }
uint16_t getDuration() { return m_duration; }
- void setDuration(uint16_t v) { m_duration = v; }
+ void setDuration(const uint16_t v) { m_duration = v; }
int8_t getLoop() { return m_loop; }
- void setLoop(int8_t v) { m_loop = v; }
+ void setLoop(const int8_t v) { m_loop = v; }
void setName(std::string_view n) { m_name = { n.data() }; }
std::string getName() { return m_name; }
@@ -70,17 +70,37 @@ class AttachedEffect : public LuaObject
Otc::Direction getDirection() { return m_direction; }
void setDirection(const Otc::Direction dir) { m_direction = std::min(dir, Otc::NorthWest); }
- void setBounce(uint8_t minHeight, uint8_t height, uint16_t speed) { m_bounce = { minHeight, height , speed }; }
- void setPulse(uint8_t minHeight, uint8_t height, uint16_t speed) { m_pulse = { minHeight, height , speed }; }
- void setFade(uint8_t start, uint8_t end, uint16_t speed) { m_fade = { start, end , speed }; }
-
- void setOnTop(bool onTop) { for (auto& control : m_offsetDirections) control.onTop = onTop; }
+ void setBounce(const uint8_t minHeight, const uint8_t height, const uint16_t speed) {
+ m_bounce = { .minHeight =
+minHeight,
+.height = height, .speed = speed
+ };
+ }
+ void setPulse(const uint8_t minHeight, const uint8_t height, const uint16_t speed) {
+ m_pulse = { .minHeight =
+minHeight,
+.height = height, .speed = speed
+ };
+ }
+ void setFade(const uint8_t start, const uint8_t end, const uint16_t speed) {
+ m_fade = { .minHeight = start, .height =
+end,
+.speed = speed
+ };
+ }
+
+ void setOnTop(const bool onTop) { for (auto& control : m_offsetDirections) control.onTop = onTop; }
void setOffset(int16_t x, int16_t y) { for (auto& control : m_offsetDirections) control.offset = { x, y }; }
- void setOnTopByDir(Otc::Direction direction, bool onTop) { m_offsetDirections[direction].onTop = onTop; }
-
- void setDirOffset(Otc::Direction direction, int8_t x, int8_t y, bool onTop = false) { m_offsetDirections[direction] = { onTop, {x, y} }; }
- void setShader(const std::string_view name);
- void setCanDrawOnUI(bool canDraw) { m_canDrawOnUI = canDraw; }
+ void setOnTopByDir(const Otc::Direction direction, const bool onTop) { m_offsetDirections[direction].onTop = onTop; }
+
+ void setDirOffset(const Otc::Direction direction, int8_t x, int8_t y, const bool onTop = false) {
+ m_offsetDirections[direction] = { .onTop =
+onTop,
+.offset = {x, y}
+ };
+ }
+ void setShader(std::string_view name);
+ void setCanDrawOnUI(const bool canDraw) { m_canDrawOnUI = canDraw; }
bool canDrawOnUI() { return m_canDrawOnUI; }
void move(const Position& fromPosition, const Position& toPosition);
@@ -88,7 +108,7 @@ class AttachedEffect : public LuaObject
void attachEffect(const AttachedEffectPtr& e) { m_effects.emplace_back(e); }
DrawOrder getDrawOrder() { return m_drawOrder; }
- void setDrawOrder(DrawOrder drawOrder) { m_drawOrder = drawOrder; }
+ void setDrawOrder(const DrawOrder drawOrder) { m_drawOrder = drawOrder; }
const Light& getLight() const { return m_light; }
void setLight(const Light& light) { m_light = light; }
@@ -116,7 +136,7 @@ class AttachedEffect : public LuaObject
uint8_t m_speed{ 100 };
uint8_t m_opacity{ 100 };
uint8_t m_lastAnimation{ 0 };
- DrawOrder m_drawOrder{ DrawOrder::FIRST };
+ DrawOrder m_drawOrder{ FIRST };
uint16_t m_id{ 0 };
uint16_t m_duration{ 0 };
diff --git a/src/client/attachedeffectmanager.cpp b/src/client/attachedeffectmanager.cpp
index 3449e563e2..100bdea3e7 100644
--- a/src/client/attachedeffectmanager.cpp
+++ b/src/client/attachedeffectmanager.cpp
@@ -22,20 +22,20 @@
#include "attachedeffectmanager.h"
#include "attachedeffect.h"
-#include "thingtypemanager.h"
#include "spritemanager.h"
+#include "thingtypemanager.h"
#include
AttachedEffectManager g_attachedEffects;
-AttachedEffectPtr AttachedEffectManager::getById(uint16_t id) {
+AttachedEffectPtr AttachedEffectManager::getById(const uint16_t id) {
const auto it = m_effects.find(id);
if (it == m_effects.end()) {
g_logger.error(stdext::format("AttachedEffectManager::getById(%d): not found.", id));
return nullptr;
}
- const auto& obj = (*it).second;
+ const auto& obj = it->second;
if (obj->m_thingId > 0 && !g_things.isValidDatId(obj->m_thingId, obj->m_thingCategory)) {
g_logger.error(stdext::format("AttachedEffectManager::getById(%d): invalid thing with id %d.", id, obj->m_thingId));
return nullptr;
@@ -44,7 +44,7 @@ AttachedEffectPtr AttachedEffectManager::getById(uint16_t id) {
return obj->clone();
}
-AttachedEffectPtr AttachedEffectManager::registerByThing(uint16_t id, const std::string_view name, uint16_t thingId, ThingCategory category) {
+AttachedEffectPtr AttachedEffectManager::registerByThing(uint16_t id, const std::string_view name, const uint16_t thingId, const ThingCategory category) {
const auto it = m_effects.find(id);
if (it != m_effects.end()) {
g_logger.error(stdext::format("AttachedEffectManager::registerByThing(%d, %s): has already been registered.", id, name));
@@ -62,7 +62,7 @@ AttachedEffectPtr AttachedEffectManager::registerByThing(uint16_t id, const std:
return obj;
}
-AttachedEffectPtr AttachedEffectManager::registerByImage(uint16_t id, const std::string_view name, const std::string_view path, bool smooth) {
+AttachedEffectPtr AttachedEffectManager::registerByImage(uint16_t id, const std::string_view name, const std::string_view path, const bool smooth) {
const auto it = m_effects.find(id);
if (it != m_effects.end()) {
g_logger.error(stdext::format("AttachedEffectManager::registerByImage(%d, %s): has already been registered.", id, name));
diff --git a/src/client/attachedeffectmanager.h b/src/client/attachedeffectmanager.h
index 000d8a81b5..acf1e5106a 100644
--- a/src/client/attachedeffectmanager.h
+++ b/src/client/attachedeffectmanager.h
@@ -28,11 +28,11 @@
class AttachedEffectManager
{
public:
- AttachedEffectPtr registerByThing(uint16_t id, const std::string_view name, uint16_t thingId, ThingCategory category);
- AttachedEffectPtr registerByImage(uint16_t id, const std::string_view name, const std::string_view path, bool smooth);
+ AttachedEffectPtr registerByThing(uint16_t id, std::string_view name, uint16_t thingId, ThingCategory category);
+ AttachedEffectPtr registerByImage(uint16_t id, std::string_view name, std::string_view path, bool smooth);
AttachedEffectPtr getById(uint16_t id);
- void remove(uint16_t id) { m_effects.erase(id); }
+ void remove(const uint16_t id) { m_effects.erase(id); }
void clear() { m_effects.clear(); }
private:
diff --git a/src/client/client.cpp b/src/client/client.cpp
index 20b6776ca8..99aa6beb1b 100644
--- a/src/client/client.cpp
+++ b/src/client/client.cpp
@@ -22,19 +22,19 @@
#include "client.h"
#include "game.h"
+#include "gameconfig.h"
#include "map.h"
-#include "uimap.h"
#include "minimap.h"
#include "spriteappearances.h"
#include "spritemanager.h"
-#include "gameconfig.h"
+#include "uimap.h"
-#include
-#include
#include
+#include
#include
-#include
#include
+#include
+#include
Client g_client;
@@ -77,7 +77,7 @@ void Client::preLoad() {
}
}
-void Client::draw(DrawPoolType type)
+void Client::draw(const DrawPoolType type)
{
if (!g_game.isOnline()) {
m_mapWidget = nullptr;
@@ -96,7 +96,7 @@ void Client::draw(DrawPoolType type)
m_mapWidget->draw(type);
}
-bool Client::canDraw(DrawPoolType type) const
+bool Client::canDraw(const DrawPoolType type) const
{
switch (type) {
case DrawPoolType::FOREGROUND:
diff --git a/src/client/client.h b/src/client/client.h
index 210aafb73d..9c33f26c3e 100644
--- a/src/client/client.h
+++ b/src/client/client.h
@@ -26,8 +26,8 @@
#include "uimap.h"
-#include
#include
+#include
class Client : public ApplicationDrawEvents
{
@@ -49,10 +49,10 @@ class Client : public ApplicationDrawEvents
UIMapPtr getMapWidget() { return m_mapWidget; }
float getEffectAlpha() const { return m_effectAlpha; }
- void setEffectAlpha(float v) { m_effectAlpha = v; }
+ void setEffectAlpha(const float v) { m_effectAlpha = v; }
float getMissileAlpha() const { return m_missileAlpha; }
- void setMissileAlpha(float v) { m_missileAlpha = v; }
+ void setMissileAlpha(const float v) { m_missileAlpha = v; }
private:
UIMapPtr m_mapWidget;
diff --git a/src/client/const.h b/src/client/const.h
index 64f4cd69b7..6f50c2de1d 100644
--- a/src/client/const.h
+++ b/src/client/const.h
@@ -762,8 +762,8 @@ namespace Otc
INSPECT_NPCTRADE = 1,
INSPECT_PLAYERTRADE = 2,
INSPECT_CYCLOPEDIA = 3
- };
-
+ };
+
enum GameStoreInfoType_t : uint8_t
{
SHOW_NONE = 0,
diff --git a/src/client/container.cpp b/src/client/container.cpp
index 7295816690..e0e9ef957c 100644
--- a/src/client/container.cpp
+++ b/src/client/container.cpp
@@ -23,7 +23,7 @@
#include "container.h"
#include "item.h"
-ItemPtr Container::getItem(int slot)
+ItemPtr Container::getItem(const int slot)
{
if (slot < 0 || slot >= static_cast(m_items.size()))
return nullptr;
@@ -62,7 +62,7 @@ void Container::onAddItem(const ItemPtr& item, int slot)
callLuaField("onAddItem", slot, item);
}
-ItemPtr Container::findItemById(uint32_t itemId, int subType) const
+ItemPtr Container::findItemById(const uint32_t itemId, const int subType) const
{
for (const auto& item : m_items)
if (item->getId() == itemId && (subType == -1 || item->getSubType() == subType))
diff --git a/src/client/container.h b/src/client/container.h
index d99eb1000d..18ea81314f 100644
--- a/src/client/container.h
+++ b/src/client/container.h
@@ -28,14 +28,14 @@
#include
// @bindclass
-class Container : public LuaObject
+class Container final : public LuaObject
{
public:
ItemPtr getItem(int slot);
std::deque getItems() { return m_items; }
int getItemsCount() { return m_items.size(); }
- Position getSlotPosition(int slot) { return { 0xffff, m_id | 0x40, static_cast(slot) }; }
+ Position getSlotPosition(const int slot) { return { 0xffff, m_id | 0x40, static_cast(slot) }; }
int getId() { return m_id; }
int getCapacity() { return m_capacity; }
ItemPtr getContainerItem() { return m_containerItem; }
@@ -49,9 +49,10 @@ class Container : public LuaObject
ItemPtr findItemById(uint32_t itemId, int subType) const;
protected:
- Container(uint8_t id, uint8_t capacity, const std::string_view name, const ItemPtr& containerItem, bool hasParent, bool isUnlocked, bool hasPages, uint16_t containerSize, uint16_t firstIndex)
- :m_id(id), m_capacity(capacity), m_containerItem(containerItem), m_name(name), m_hasParent(hasParent), m_unlocked(isUnlocked), m_hasPages(hasPages), m_size(containerSize), m_firstIndex(firstIndex)
- {}
+ Container(const uint8_t id, const uint8_t capacity, const std::string_view name, ItemPtr containerItem, const bool hasParent, const bool isUnlocked, const bool hasPages, const uint16_t containerSize, const uint16_t firstIndex)
+ :m_id(id), m_capacity(capacity), m_containerItem(std::move(containerItem)), m_name(name), m_hasParent(hasParent), m_unlocked(isUnlocked), m_hasPages(hasPages), m_size(containerSize), m_firstIndex(firstIndex)
+ {
+ }
void onOpen(const ContainerPtr& previousContainer);
void onClose();
diff --git a/src/client/creature.cpp b/src/client/creature.cpp
index b69cf2490b..73b3b40f14 100644
--- a/src/client/creature.cpp
+++ b/src/client/creature.cpp
@@ -26,17 +26,17 @@
#include "localplayer.h"
#include "luavaluecasts_client.h"
#include "map.h"
+#include "statictext.h"
#include "thingtypemanager.h"
#include "tile.h"
-#include "statictext.h"
#include
#include
#include
#include
#include
-#include
#include
+#include
#include
double Creature::speedA = 0;
@@ -58,7 +58,7 @@ void Creature::onCreate() {
callLuaField("onCreate");
}
-void Creature::draw(const Point& dest, bool drawThings, const LightViewPtr& /*lightView*/)
+void Creature::draw(const Point& dest, const bool drawThings, const LightViewPtr& /*lightView*/)
{
if (!canBeSeen() || !canDraw())
return;
@@ -105,7 +105,7 @@ void Creature::drawLight(const Point& dest, const LightViewPtr& lightView) {
drawAttachedLightEffect(dest + m_walkOffset * g_drawPool.getScaleFactor(), lightView);
}
-void Creature::draw(const Rect& destRect, uint8_t size, bool center)
+void Creature::draw(const Rect& destRect, const uint8_t size, const bool center)
{
if (!getThingType())
return;
@@ -127,7 +127,7 @@ void Creature::draw(const Rect& destRect, uint8_t size, bool center)
} g_drawPool.releaseFrameBuffer(destRect);
}
-void Creature::drawInformation(const MapPosInfo& mapRect, const Point& dest, int drawFlags)
+void Creature::drawInformation(const MapPosInfo& mapRect, const Point& dest, const int drawFlags)
{
static const Color
DEFAULT_COLOR(96, 96, 96),
@@ -168,7 +168,7 @@ void Creature::drawInformation(const MapPosInfo& mapRect, const Point& dest, int
const int cropSizeText = g_gameConfig.isAdjustCreatureInformationBasedCropSize() ? getExactSize() : 12;
const int cropSizeBackGround = g_gameConfig.isAdjustCreatureInformationBasedCropSize() ? cropSizeText - nameSize.height() : 0;
- bool isScaled = g_app.getCreatureInformationScale() != PlatformWindow::DEFAULT_DISPLAY_DENSITY;
+ const bool isScaled = g_app.getCreatureInformationScale() != PlatformWindow::DEFAULT_DISPLAY_DENSITY;
if (isScaled) {
p.scale(g_app.getCreatureInformationScale());
}
@@ -255,7 +255,7 @@ void Creature::internalDraw(Point dest, const Color& color)
m_shader->setUniformValue(ShaderManager::OUTFIT_ID_UNIFORM, id);
};*/
- bool replaceColorShader = color != Color::white;
+ const bool replaceColorShader = color != Color::white;
if (replaceColorShader)
g_drawPool.setShaderProgram(g_painter->getReplaceColorShader());
else
@@ -362,7 +362,7 @@ void Creature::internalDraw(Point dest, const Color& color)
}
}
-void Creature::turn(Otc::Direction direction)
+void Creature::turn(const Otc::Direction direction)
{
// schedules to set the new direction when walk ends
if (m_walking) {
@@ -413,7 +413,7 @@ void Creature::stopWalk()
terminateWalk();
}
-void Creature::jump(int height, int duration)
+void Creature::jump(const int height, const int duration)
{
if (!m_jumpOffset.isNull())
return;
@@ -558,7 +558,7 @@ void Creature::updateWalkAnimation()
return;
int minFootDelay = 20;
- int maxFootDelay = footAnimPhases > 2 ? 80 : 205;
+ const int maxFootDelay = footAnimPhases > 2 ? 80 : 205;
int footAnimDelay = footAnimPhases;
if (g_game.getFeature(Otc::GameEnhancedAnimations) && footAnimPhases > 2) {
@@ -578,7 +578,7 @@ void Creature::updateWalkAnimation()
}
}
-void Creature::updateWalkOffset(uint8_t totalPixelsWalked)
+void Creature::updateWalkOffset(const uint8_t totalPixelsWalked)
{
m_walkOffset = {};
if (m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
@@ -703,7 +703,7 @@ void Creature::terminateWalk()
}, g_game.getServerBeat());
}
-void Creature::setHealthPercent(uint8_t healthPercent)
+void Creature::setHealthPercent(const uint8_t healthPercent)
{
static const Color
COLOR1(0x00, 0xBC, 0x00),
@@ -737,7 +737,7 @@ void Creature::setHealthPercent(uint8_t healthPercent)
onDeath();
}
-void Creature::setDirection(Otc::Direction direction)
+void Creature::setDirection(const Otc::Direction direction)
{
if (direction == Otc::InvalidDirection)
return;
@@ -813,7 +813,7 @@ void Creature::setSpeed(uint16_t speed)
callLuaField("onSpeedChange", m_speed, oldSpeed);
}
-void Creature::setBaseSpeed(uint16_t baseSpeed)
+void Creature::setBaseSpeed(const uint16_t baseSpeed)
{
if (m_baseSpeed == baseSpeed)
return;
@@ -824,18 +824,18 @@ void Creature::setBaseSpeed(uint16_t baseSpeed)
callLuaField("onBaseSpeedChange", baseSpeed, oldBaseSpeed);
}
-void Creature::setType(uint8_t v) { if (m_type != v) callLuaField("onTypeChange", m_type = v); }
-void Creature::setIcon(uint8_t v) { if (m_icon != v) callLuaField("onIconChange", m_icon = v); }
-void Creature::setSkull(uint8_t v) { if (m_skull != v) callLuaField("onSkullChange", m_skull = v); }
-void Creature::setShield(uint8_t v) { if (m_shield != v) callLuaField("onShieldChange", m_shield = v); }
-void Creature::setEmblem(uint8_t v) { if (m_emblem != v) callLuaField("onEmblemChange", m_emblem = v); }
+void Creature::setType(const uint8_t v) { if (m_type != v) callLuaField("onTypeChange", m_type = v); }
+void Creature::setIcon(const uint8_t v) { if (m_icon != v) callLuaField("onIconChange", m_icon = v); }
+void Creature::setSkull(const uint8_t v) { if (m_skull != v) callLuaField("onSkullChange", m_skull = v); }
+void Creature::setShield(const uint8_t v) { if (m_shield != v) callLuaField("onShieldChange", m_shield = v); }
+void Creature::setEmblem(const uint8_t v) { if (m_emblem != v) callLuaField("onEmblemChange", m_emblem = v); }
void Creature::setTypeTexture(const std::string& filename) { m_typeTexture = g_textures.getTexture(filename); }
void Creature::setIconTexture(const std::string& filename) { m_iconTexture = g_textures.getTexture(filename); }
void Creature::setSkullTexture(const std::string& filename) { m_skullTexture = g_textures.getTexture(filename); }
void Creature::setEmblemTexture(const std::string& filename) { m_emblemTexture = g_textures.getTexture(filename); }
-void Creature::setShieldTexture(const std::string& filename, bool blink)
+void Creature::setShieldTexture(const std::string& filename, const bool blink)
{
m_shieldTexture = g_textures.getTexture(filename);
m_showShieldTexture = true;
@@ -850,7 +850,7 @@ void Creature::setShieldTexture(const std::string& filename, bool blink)
m_shieldBlink = blink;
}
-void Creature::addTimedSquare(uint8_t color)
+void Creature::addTimedSquare(const uint8_t color)
{
m_showTimedSquare = true;
m_timedSquareColor = Color::from8bit(color != 0 ? color : 1);
@@ -875,7 +875,7 @@ void Creature::updateShield()
m_showShieldTexture = true;
}
-int getSmoothedElevation(const Creature* creature, int currentElevation, float factor) {
+int getSmoothedElevation(const Creature* creature, const int currentElevation, const float factor) {
const auto& fromPos = creature->getLastStepFromPosition();
const auto& toPos = creature->getLastStepToPosition();
const auto& fromTile = g_map.getTile(fromPos);
@@ -908,7 +908,7 @@ int Creature::getDrawElevation() {
bool Creature::hasSpeedFormula() { return g_game.getFeature(Otc::GameNewSpeedLaw) && speedA != 0 && speedB != 0 && speedC != 0; }
-uint16_t Creature::getStepDuration(bool ignoreDiagonal, Otc::Direction dir)
+uint16_t Creature::getStepDuration(const bool ignoreDiagonal, const Otc::Direction dir)
{
if (m_speed < 1)
return 0;
@@ -1060,7 +1060,7 @@ void Creature::setTypingIconTexture(const std::string& filename)
m_typingIconTexture = g_textures.getTexture(filename);
}
-void Creature::setTyping(bool typing)
+void Creature::setTyping(const bool typing)
{
m_typing = typing;
}
@@ -1107,7 +1107,7 @@ void Creature::onStartDetachEffect(const AttachedEffectPtr& effect) {
}
}
-void Creature::setStaticWalking(uint16_t v) {
+void Creature::setStaticWalking(const uint16_t v) {
if (m_walkUpdateEvent) {
m_walkUpdateEvent->cancel();
m_walkUpdateEvent = nullptr;
diff --git a/src/client/creature.h b/src/client/creature.h
index e806eb3034..2201fdf383 100644
--- a/src/client/creature.h
+++ b/src/client/creature.h
@@ -22,16 +22,15 @@
#pragma once
-#include
-#include
-#include
#include "mapview.h"
#include "outfit.h"
#include "thing.h"
+#include
+#include
+#include
struct PreyMonster
{
-public:
std::string name;
Outfit outfit;
};
@@ -45,7 +44,7 @@ class Creature : public Thing
static double speedC;
Creature();
- ~Creature();
+ ~Creature() override;
static bool hasSpeedFormula();
@@ -61,9 +60,9 @@ class Creature : public Thing
void internalDraw(Point dest, const Color& color = Color::white);
void drawInformation(const MapPosInfo& mapRect, const Point& dest, int drawFlags);
- void setId(uint32_t id) override { m_id = id; }
- void setMasterId(uint32_t id) { m_masterId = id; }
- void setName(const std::string_view name);
+ void setId(const uint32_t id) override { m_id = id; }
+ void setMasterId(const uint32_t id) { m_masterId = id; }
+ void setName(std::string_view name);
void setHealthPercent(uint8_t healthPercent);
void setDirection(Otc::Direction direction);
void setOutfit(const Outfit& outfit);
@@ -80,8 +79,8 @@ class Creature : public Thing
void setEmblemTexture(const std::string& filename);
void setTypeTexture(const std::string& filename);
void setIconTexture(const std::string& filename);
- void setPassable(bool passable) { m_passable = passable; }
- void setMountShader(const std::string_view name);
+ void setPassable(const bool passable) { m_passable = passable; }
+ void setMountShader(std::string_view name);
void setStaticWalking(uint16_t v);
void onStartAttachEffect(const AttachedEffectPtr& effect) override;
@@ -160,7 +159,7 @@ class Creature : public Thing
void setCovered(bool covered);
bool isDisabledWalkAnimation() { return m_disableWalkAnimation > 0; }
- void setDisableWalkAnimation(bool v) {
+ void setDisableWalkAnimation(const bool v) {
if (v) ++m_disableWalkAnimation; else {
if (m_disableWalkAnimation <= 1) m_disableWalkAnimation = 0;
else --m_disableWalkAnimation;
@@ -171,7 +170,12 @@ class Creature : public Thing
void sendTyping();
bool getTyping() { return m_typing; }
void setTypingIconTexture(const std::string& filename);
- void setBounce(uint8_t minHeight, uint8_t height, uint16_t speed) { m_bounce = { minHeight, height , speed }; }
+ void setBounce(const uint8_t minHeight, const uint8_t height, const uint16_t speed) {
+ m_bounce = { .minHeight =
+minHeight,
+.height = height, .speed = speed
+ };
+ }
void setWidgetInformation(const UIWidgetPtr& info);
UIWidgetPtr getWidgetInformation() { return m_widgetInformation; }
@@ -219,7 +223,7 @@ class Creature : public Thing
uint16_t walkDuration{ 0 };
uint16_t diagonalDuration{ 0 };
- uint16_t getDuration(Otc::Direction dir) const { return Position::isDiagonal(dir) ? diagonalDuration : duration; }
+ uint16_t getDuration(const Otc::Direction dir) const { return Position::isDiagonal(dir) ? diagonalDuration : duration; }
};
UIWidgetPtr m_widgetInformation;
@@ -316,14 +320,14 @@ class Creature : public Thing
};
// @bindclass
-class Npc : public Creature
+class Npc final : public Creature
{
public:
bool isNpc() override { return true; }
};
// @bindclass
-class Monster : public Creature
+class Monster final : public Creature
{
public:
bool isMonster() override { return true; }
diff --git a/src/client/declarations.h b/src/client/declarations.h
index 755a029fae..5f2cb1a041 100644
--- a/src/client/declarations.h
+++ b/src/client/declarations.h
@@ -22,9 +22,9 @@
#pragma once
+#include "global.h"
#include
#include
-#include "global.h"
// core
class Map;
diff --git a/src/client/effect.cpp b/src/client/effect.cpp
index 54ddcf2154..24b50e098e 100644
--- a/src/client/effect.cpp
+++ b/src/client/effect.cpp
@@ -21,13 +21,13 @@
*/
#include "effect.h"
-#include
-#include
#include "game.h"
#include "map.h"
#include
+#include
+#include
-void Effect::draw(const Point& dest, bool drawThings, const LightViewPtr& lightView)
+void Effect::draw(const Point& dest, const bool drawThings, const LightViewPtr& lightView)
{
if (!canDraw() || isHided())
return;
@@ -57,11 +57,11 @@ void Effect::draw(const Point& dest, bool drawThings, const LightViewPtr& lightV
const int offsetX = m_position.x - g_map.getCentralPosition().x;
const int offsetY = m_position.y - g_map.getCentralPosition().y;
- int xPattern = unsigned(offsetX) % getNumPatternX();
+ int xPattern = static_cast(offsetX) % getNumPatternX();
xPattern = 1 - xPattern - getNumPatternX();
if (xPattern < 0) xPattern += getNumPatternX();
- int yPattern = unsigned(offsetY) % getNumPatternY();
+ int yPattern = static_cast(offsetY) % getNumPatternY();
if (g_game.getFeature(Otc::GameMapOldEffectRendering)) {
xPattern = offsetX % getNumPatternX();
@@ -76,7 +76,7 @@ void Effect::draw(const Point& dest, bool drawThings, const LightViewPtr& lightV
if (g_drawPool.getCurrentType() == DrawPoolType::MAP) {
if (g_app.isDrawingEffectsOnTop() && !m_drawConductor.agroup) {
m_drawConductor.agroup = true;
- m_drawConductor.order = DrawOrder::FOURTH;
+ m_drawConductor.order = FOURTH;
}
if (drawThings && g_client.getEffectAlpha() < 1.f)
@@ -126,7 +126,7 @@ bool Effect::waitFor(const EffectPtr& effect)
return true;
}
-void Effect::setId(uint32_t id)
+void Effect::setId(const uint32_t id)
{
if (!g_things.isValidDatId(id, ThingCategoryEffect))
return;
@@ -134,7 +134,7 @@ void Effect::setId(uint32_t id)
m_clientId = id;
}
-void Effect::setPosition(const Position& position, uint8_t stackPos, bool hasElevation)
+void Effect::setPosition(const Position& position, const uint8_t stackPos, const bool hasElevation)
{
if (m_clientId == 0)
return;
diff --git a/src/client/effect.h b/src/client/effect.h
index afb1850759..e8772caddd 100644
--- a/src/client/effect.h
+++ b/src/client/effect.h
@@ -22,12 +22,12 @@
#pragma once
-#include
-#include
#include "thing.h"
+#include
+#include
// @bindclass
-class Effect : public Thing
+class Effect final : public Thing
{
public:
void draw(const Point& /*dest*/, bool drawThings = true, const LightViewPtr & = nullptr) override;
diff --git a/src/client/game.cpp b/src/client/game.cpp
index a59251fd23..332bde002e 100644
--- a/src/client/game.cpp
+++ b/src/client/game.cpp
@@ -21,8 +21,6 @@
*/
#include "game.h"
-#include
-#include
#include "container.h"
#include "creature.h"
#include "localplayer.h"
@@ -30,9 +28,11 @@
#include "map.h"
#include "protocolcodes.h"
#include "protocolgame.h"
+#include
+#include
-#include "tile.h"
#include "framework/core/graphicalapplication.h"
+#include "tile.h"
Game g_game;
@@ -384,7 +384,7 @@ void Game::processVipStateChange(const uint32_t id, const uint32_t status)
g_lua.callGlobalField("g_game", "onVipStateChange", id, status, groupID);
}
-void Game::processVipGroupChange(const std::vector>& vipGroups, uint8_t groupsAmountLeft)
+void Game::processVipGroupChange(const std::vector>& vipGroups, const uint8_t groupsAmountLeft)
{
g_lua.callGlobalField("g_game", "onVipGroupChange", vipGroups, groupsAmountLeft);
}
@@ -532,7 +532,7 @@ void Game::processCyclopediaCharacterItemSummary(const CyclopediaCharacterItemSu
}
void Game::processCyclopediaCharacterAppearances(const OutfitColorStruct& currentOutfit, const std::vector& outfits,
- const std::vector& mounts, std::vector& familiars)
+ const std::vector& mounts, const std::vector& familiars)
{
g_lua.callGlobalField("g_game", "onParseCyclopediaCharacterAppearances", currentOutfit, outfits, mounts, familiars);
}
@@ -588,7 +588,7 @@ void Game::processWalkCancel(const Otc::Direction direction)
m_localPlayer->cancelWalk(direction);
}
-void Game::loginWorld(const std::string_view account, const std::string_view password, const std::string_view worldName, const std::string_view worldHost, int worldPort, const std::string_view characterName, const std::string_view authenticatorToken, const std::string_view sessionKey)
+void Game::loginWorld(const std::string_view account, const std::string_view password, const std::string_view worldName, const std::string_view worldHost, const int worldPort, const std::string_view characterName, const std::string_view authenticatorToken, const std::string_view sessionKey)
{
if (m_protocolGame || isOnline())
throw Exception("Unable to login into a world while already online or logging.");
diff --git a/src/client/game.h b/src/client/game.h
index 66cae74310..89f0a0cd89 100644
--- a/src/client/game.h
+++ b/src/client/game.h
@@ -22,8 +22,6 @@
#pragma once
-#include
-#include
#include "animatedtext.h"
#include "container.h"
#include "creature.h"
@@ -31,6 +29,8 @@
#include "item.h"
#include "outfit.h"
#include "protocolgame.h"
+#include
+#include
struct UnjustifiedPoints
{
@@ -419,60 +419,60 @@ class Game
void processPing();
void processPingBack();
- static void processUpdateNeeded(const std::string_view signature);
- static void processLoginError(const std::string_view error);
- static void processLoginAdvice(const std::string_view message);
- static void processLoginWait(const std::string_view message, const uint8_t time);
- static void processSessionEnd(const uint8_t reason);
+ static void processUpdateNeeded(std::string_view signature);
+ static void processLoginError(std::string_view error);
+ static void processLoginAdvice(std::string_view message);
+ static void processLoginWait(std::string_view message, uint8_t time);
+ static void processSessionEnd(uint8_t reason);
static void processLogin();
void processPendingGame();
void processEnterGame();
void processGameStart();
void processGameEnd();
- void processDeath(const uint8_t deathType, const uint8_t penality);
+ void processDeath(uint8_t deathType, uint8_t penality);
void processGMActions(const std::vector& actions);
- void processInventoryChange(const uint8_t slot, const ItemPtr& item);
- void processAttackCancel(const uint32_t seq);
- void processWalkCancel(const Otc::Direction direction);
+ void processInventoryChange(uint8_t slot, const ItemPtr& item);
+ void processAttackCancel(uint32_t seq);
+ void processWalkCancel(Otc::Direction direction);
- static void processPlayerHelpers(const uint16_t helpers);
- void processPlayerModes(const Otc::FightModes fightMode, const Otc::ChaseModes chaseMode, const bool safeMode, const Otc::PVPModes pvpMode);
+ static void processPlayerHelpers(uint16_t helpers);
+ void processPlayerModes(Otc::FightModes fightMode, Otc::ChaseModes chaseMode, bool safeMode, Otc::PVPModes pvpMode);
// message related
- static void processTextMessage(const Otc::MessageMode mode, const std::string_view text);
- static void processTalk(const std::string_view name, const uint16_t level, const Otc::MessageMode mode, const std::string_view text, const uint16_t channelId, const Position& pos);
+ static void processTextMessage(Otc::MessageMode mode, std::string_view text);
+ static void processTalk(std::string_view name, uint16_t level, Otc::MessageMode mode, std::string_view text, uint16_t channelId, const Position& pos);
// container related
- void processOpenContainer(const uint8_t containerId, const ItemPtr& containerItem, const std::string_view name, const uint8_t capacity, const bool hasParent, const std::vector& items, const bool isUnlocked, const bool hasPages, const uint16_t containerSize, const uint16_t firstIndex);
- void processCloseContainer(const uint8_t containerId);
- void processContainerAddItem(const uint8_t containerId, const ItemPtr& item, const uint16_t slot);
- void processContainerUpdateItem(const uint8_t containerId, const uint16_t slot, const ItemPtr& item);
- void processContainerRemoveItem(const uint8_t containerId, const uint16_t slot, const ItemPtr& lastItem);
+ void processOpenContainer(uint8_t containerId, const ItemPtr& containerItem, std::string_view name, uint8_t capacity, bool hasParent, const std::vector& items, bool isUnlocked, bool hasPages, uint16_t containerSize, uint16_t firstIndex);
+ void processCloseContainer(uint8_t containerId);
+ void processContainerAddItem(uint8_t containerId, const ItemPtr& item, uint16_t slot);
+ void processContainerUpdateItem(uint8_t containerId, uint16_t slot, const ItemPtr& item);
+ void processContainerRemoveItem(uint8_t containerId, uint16_t slot, const ItemPtr& lastItem);
// channel related
static void processChannelList(const std::vector>& channelList);
- static void processOpenChannel(const uint16_t channelId, const std::string_view name);
- static void processOpenPrivateChannel(const std::string_view name);
- static void processOpenOwnPrivateChannel(const uint16_t channelId, const std::string_view name);
- static void processCloseChannel(const uint16_t channelId);
+ static void processOpenChannel(uint16_t channelId, std::string_view name);
+ static void processOpenPrivateChannel(std::string_view name);
+ static void processOpenOwnPrivateChannel(uint16_t channelId, std::string_view name);
+ static void processCloseChannel(uint16_t channelId);
// rule violations
- static void processRuleViolationChannel(const uint16_t channelId);
- static void processRuleViolationRemove(const std::string_view name);
- static void processRuleViolationCancel(const std::string_view name);
+ static void processRuleViolationChannel(uint16_t channelId);
+ static void processRuleViolationRemove(std::string_view name);
+ static void processRuleViolationCancel(std::string_view name);
static void processRuleViolationLock();
// vip related
- void processVipAdd(const uint32_t id, const std::string_view name, const uint32_t status, const std::string_view description, const uint32_t iconId, const bool notifyLogin, const std::vector& groupID);
- void processVipStateChange(const uint32_t id, const uint32_t status);
+ void processVipAdd(uint32_t id, std::string_view name, uint32_t status, std::string_view description, uint32_t iconId, bool notifyLogin, const std::vector& groupID);
+ void processVipStateChange(uint32_t id, uint32_t status);
void processVipGroupChange(const std::vector>& vipGroups, uint8_t groupsAmountLeft);
// tutorial hint
- static void processTutorialHint(const uint8_t id);
- static void processAddAutomapFlag(const Position& pos, const uint8_t icon, const std::string_view message);
- static void processRemoveAutomapFlag(const Position& pos, const uint8_t icon, const std::string_view message);
+ static void processTutorialHint(uint8_t id);
+ static void processAddAutomapFlag(const Position& pos, uint8_t icon, std::string_view message);
+ static void processRemoveAutomapFlag(const Position& pos, uint8_t icon, std::string_view message);
// outfit
void processOpenOutfitWindow(const Outfit& currentOutfit, const std::vector>& outfitList,
@@ -485,47 +485,47 @@ class Game
// npc trade
static void processOpenNpcTrade(const std::vector>& items);
- static void processPlayerGoods(const uint64_t money, const std::vector>& goods);
+ static void processPlayerGoods(uint64_t money, const std::vector>& goods);
static void processCloseNpcTrade();
// player trade
- static void processOwnTrade(const std::string_view name, const std::vector& items);
- static void processCounterTrade(const std::string_view name, const std::vector& items);
+ static void processOwnTrade(std::string_view name, const std::vector& items);
+ static void processCounterTrade(std::string_view name, const std::vector& items);
static void processCloseTrade();
// edit text/list
- static void processEditText(const uint32_t id, const uint32_t itemId, const uint16_t maxLength, const std::string_view text, const std::string_view writer, const std::string_view date);
- static void processEditList(const uint32_t id, const uint8_t doorId, const std::string_view text);
+ static void processEditText(uint32_t id, uint32_t itemId, uint16_t maxLength, std::string_view text, std::string_view writer, std::string_view date);
+ static void processEditList(uint32_t id, uint8_t doorId, std::string_view text);
// questlog
static void processQuestLog(const std::vector>& questList);
- static void processQuestLine(const uint16_t questId, const std::vector>& questMissions);
+ static void processQuestLine(uint16_t questId, const std::vector>& questMissions);
// modal dialogs >= 970
- static void processModalDialog(const uint32_t id, const std::string_view title, const std::string_view message, const std::vector>
- & buttonList, const uint8_t enterButton, const uint8_t escapeButton, const std::vector>
- & choiceList, const bool priority);
+ static void processModalDialog(uint32_t id, std::string_view title, std::string_view message, const std::vector>
+ & buttonList, uint8_t enterButton, uint8_t escapeButton, const std::vector>
+ & choiceList, bool priority);
// cyclopedia
- static void processItemDetail(const uint32_t itemId, const std::vector>& descriptions);
+ static void processItemDetail(uint32_t itemId, const std::vector>& descriptions);
static void processBestiaryRaces(const std::vector& bestiaryRaces);
static void processCyclopediaCharacterGeneralStats(const CyclopediaCharacterGeneralStats& stats, const std::vector>& skills,
const std::vector>& combats);
- static void processCyclopediaCharacterCombatStats(const CyclopediaCharacterCombatStats& data, const double mitigation,
+ static void processCyclopediaCharacterCombatStats(const CyclopediaCharacterCombatStats& data, double mitigation,
const std::vector>& additionalSkillsArray,
const std::vector>& forgeSkillsArray, const std::vector& perfectShotDamageRangesArray,
const std::vector>& combatsArray,
const std::vector>& concoctionsArray);
- static void processCyclopediaCharacterGeneralStatsBadge(const uint8_t showAccountInformation, const uint8_t playerOnline, const uint8_t playerPremium,
- const std::string_view loyaltyTitle,
- const std::vector>& badgesVector);
+ static void processCyclopediaCharacterGeneralStatsBadge(uint8_t showAccountInformation, uint8_t playerOnline, uint8_t playerPremium,
+ std::string_view loyaltyTitle,
+ const std::vector>& badgesVector);
static void processCyclopediaCharacterItemSummary(const CyclopediaCharacterItemSummary& data);
static void processCyclopediaCharacterAppearances(const OutfitColorStruct& currentOutfit, const std::vector& outfits,
- const std::vector& mounts, std::vector& familiars);
+ const std::vector& mounts, const std::vector& familiars);
static void processCyclopediaCharacterRecentDeaths(const CyclopediaCharacterRecentDeaths& data);
static void processCyclopediaCharacterRecentPvpKills(const CyclopediaCharacterRecentPvPKills& data);
static void processParseBestiaryRaces(const std::vector& bestiaryData);
- static void processParseBestiaryOverview(const std::string_view raceName, const std::vector& data, const uint16_t animusMasteryPoints);
+ static void processParseBestiaryOverview(std::string_view raceName, const std::vector& data, uint16_t animusMasteryPoints);
static void processUpdateBestiaryMonsterData(const BestiaryMonsterData& data);
static void processUpdateBestiaryCharmsData(const BestiaryCharmsData& charmData);
static void processBosstiaryInfo(const std::vector& boss);
@@ -536,29 +536,29 @@ class Game
public:
// login related
- void loginWorld(const std::string_view account, const std::string_view password, const std::string_view worldName, const std::string_view worldHost, int worldPort, const std::string_view characterName, const std::string_view authenticatorToken, const std::string_view sessionKey);
+ void loginWorld(std::string_view account, std::string_view password, std::string_view worldName, std::string_view worldHost, int worldPort, std::string_view characterName, std::string_view authenticatorToken, std::string_view sessionKey);
void cancelLogin();
void forceLogout();
void safeLogout();
// walk related
- bool walk(const Otc::Direction direction);
+ bool walk(Otc::Direction direction);
void autoWalk(const std::vector& dirs, const Position& startPos);
- void forceWalk(const Otc::Direction direction);
- void turn(const Otc::Direction direction);
+ void forceWalk(Otc::Direction direction);
+ void turn(Otc::Direction direction);
void stop();
// item related
- void look(const ThingPtr& thing, const bool isBattleList = false);
+ void look(const ThingPtr& thing, bool isBattleList = false);
void move(const ThingPtr& thing, const Position& toPos, int count);
- void moveToParentContainer(const ThingPtr& thing, const int count);
+ void moveToParentContainer(const ThingPtr& thing, int count);
void rotate(const ThingPtr& thing);
void wrap(const ThingPtr& thing);
void use(const ThingPtr& thing);
void useWith(const ItemPtr& item, const ThingPtr& toThing);
- void useInventoryItem(const uint16_t itemId);
- void useInventoryItemWith(const uint16_t itemId, const ThingPtr& toThing);
- ItemPtr findItemInContainers(const uint32_t itemId, const int subType);
+ void useInventoryItem(uint16_t itemId);
+ void useInventoryItemWith(uint16_t itemId, const ThingPtr& toThing);
+ ItemPtr findItemInContainers(uint32_t itemId, int subType);
// container related
int open(const ItemPtr& item, const ContainerPtr& previousContainer);
@@ -574,27 +574,27 @@ class Game
void cancelAttackAndFollow();
// talk related
- void talk(const std::string_view message);
- void talkChannel(const Otc::MessageMode mode, const uint16_t channelId, const std::string_view message);
- void talkPrivate(const Otc::MessageMode mode, const std::string_view receiver, const std::string_view message);
+ void talk(std::string_view message);
+ void talkChannel(Otc::MessageMode mode, uint16_t channelId, std::string_view message);
+ void talkPrivate(Otc::MessageMode mode, std::string_view receiver, std::string_view message);
// channel related
- void openPrivateChannel(const std::string_view receiver);
+ void openPrivateChannel(std::string_view receiver);
void requestChannels();
- void joinChannel(const uint16_t channelId);
- void leaveChannel(const uint16_t channelId);
+ void joinChannel(uint16_t channelId);
+ void leaveChannel(uint16_t channelId);
void closeNpcChannel();
void openOwnChannel();
- void inviteToOwnChannel(const std::string_view name);
- void excludeFromOwnChannel(const std::string_view name);
+ void inviteToOwnChannel(std::string_view name);
+ void excludeFromOwnChannel(std::string_view name);
// party related
- void partyInvite(const uint32_t creatureId);
- void partyJoin(const uint32_t creatureId);
- void partyRevokeInvitation(const uint32_t creatureId);
- void partyPassLeadership(const uint32_t creatureId);
+ void partyInvite(uint32_t creatureId);
+ void partyJoin(uint32_t creatureId);
+ void partyRevokeInvitation(uint32_t creatureId);
+ void partyPassLeadership(uint32_t creatureId);
void partyLeave();
- void partyShareExperience(const bool active);
+ void partyShareExperience(bool active);
// outfit related
void requestOutfit();
@@ -603,104 +603,104 @@ class Game
void sendTyping(bool typing);
// vip related
- void addVip(const std::string_view name);
- void removeVip(const uint32_t playerId);
- void editVip(const uint32_t playerId, const std::string_view description, const uint32_t iconId, const bool notifyLogin, const std::vector& groupID = {});
- void editVipGroups(const Otc::GroupsEditInfoType_t action, const uint8_t groupId, const std::string_view groupName);
+ void addVip(std::string_view name);
+ void removeVip(uint32_t playerId);
+ void editVip(uint32_t playerId, std::string_view description, uint32_t iconId, bool notifyLogin, const std::vector& groupID = {});
+ void editVipGroups(Otc::GroupsEditInfoType_t action, uint8_t groupId, std::string_view groupName);
// fight modes related
- void setChaseMode(const Otc::ChaseModes chaseMode);
- void setFightMode(const Otc::FightModes fightMode);
- void setSafeFight(const bool on);
- void setPVPMode(const Otc::PVPModes pvpMode);
+ void setChaseMode(Otc::ChaseModes chaseMode);
+ void setFightMode(Otc::FightModes fightMode);
+ void setSafeFight(bool on);
+ void setPVPMode(Otc::PVPModes pvpMode);
Otc::ChaseModes getChaseMode() { return m_chaseMode; }
Otc::FightModes getFightMode() { return m_fightMode; }
bool isSafeFight() { return m_safeFight; }
Otc::PVPModes getPVPMode() { return m_pvpMode; }
// pvp related
- void setUnjustifiedPoints(const UnjustifiedPoints unjustifiedPoints);
+ void setUnjustifiedPoints(UnjustifiedPoints unjustifiedPoints);
UnjustifiedPoints getUnjustifiedPoints() { return m_unjustifiedPoints; };
- void setOpenPvpSituations(const uint8_t openPvpSituations);
+ void setOpenPvpSituations(uint8_t openPvpSituations);
int getOpenPvpSituations() { return m_openPvpSituations; }
// npc trade related
void inspectNpcTrade(const ItemPtr& item);
- void buyItem(const ItemPtr& item, const uint16_t amount, const bool ignoreCapacity, const bool buyWithBackpack);
- void sellItem(const ItemPtr& item, const uint16_t amount, const bool ignoreEquipped);
+ void buyItem(const ItemPtr& item, uint16_t amount, bool ignoreCapacity, bool buyWithBackpack);
+ void sellItem(const ItemPtr& item, uint16_t amount, bool ignoreEquipped);
void closeNpcTrade();
// player trade related
void requestTrade(const ItemPtr& item, const CreaturePtr& creature);
- void inspectTrade(const bool counterOffer, const uint8_t index);
+ void inspectTrade(bool counterOffer, uint8_t index);
void acceptTrade();
void rejectTrade();
// house window and editable items related
- void editText(const uint32_t id, const std::string_view text);
- void editList(const uint32_t id, const uint8_t doorId, const std::string_view text);
+ void editText(uint32_t id, std::string_view text);
+ void editList(uint32_t id, uint8_t doorId, std::string_view text);
// rule violations (only gms)
- void openRuleViolation(const std::string_view reporter);
- void closeRuleViolation(const std::string_view reporter);
+ void openRuleViolation(std::string_view reporter);
+ void closeRuleViolation(std::string_view reporter);
void cancelRuleViolation();
// reports
- void reportBug(const std::string_view comment);
- void reportRuleViolation(const std::string_view target, const uint8_t reason, const uint8_t action, const std::string_view comment, const std::string_view statement, const uint16_t statementId, const bool ipBanishment);
- void debugReport(const std::string_view a, const std::string_view b, const std::string_view c, const std::string_view d);
+ void reportBug(std::string_view comment);
+ void reportRuleViolation(std::string_view target, uint8_t reason, uint8_t action, std::string_view comment, std::string_view statement, uint16_t statementId, bool ipBanishment);
+ void debugReport(std::string_view a, std::string_view b, std::string_view c, std::string_view d);
// questlog related
void requestQuestLog();
- void requestQuestLine(const uint16_t questId);
+ void requestQuestLine(uint16_t questId);
// 870 only
void equipItem(const ItemPtr& item);
- void mount(const bool mount);
+ void mount(bool mount);
// 910 only
- void requestItemInfo(const ItemPtr& item, const uint8_t index);
+ void requestItemInfo(const ItemPtr& item, uint8_t index);
// >= 970 modal dialog
- void answerModalDialog(const uint32_t dialog, const uint8_t button, const uint8_t choice);
+ void answerModalDialog(uint32_t dialog, uint8_t button, uint8_t choice);
// >= 984 browse field
void browseField(const Position& position);
- void seekInContainer(const uint8_t containerId, const uint16_t index);
+ void seekInContainer(uint8_t containerId, uint16_t index);
// >= 1080 ingame store
- void buyStoreOffer(const uint32_t offerId, const uint8_t productType, const std::string_view name = "");
- void requestTransactionHistory(const uint32_t page, const uint32_t entriesPerPage);
- void requestStoreOffers(const std::string_view categoryName, const uint8_t serviceType = 0);
- void openStore(const uint8_t serviceType = 0, const std::string_view category = "");
- void transferCoins(const std::string_view recipient, const uint16_t amount);
- void openTransactionHistory(const uint8_t entriesPerPage);
+ void buyStoreOffer(uint32_t offerId, uint8_t productType, std::string_view name = "");
+ void requestTransactionHistory(uint32_t page, uint32_t entriesPerPage);
+ void requestStoreOffers(std::string_view categoryName, uint8_t serviceType = 0);
+ void openStore(uint8_t serviceType = 0, std::string_view category = "");
+ void transferCoins(std::string_view recipient, uint16_t amount);
+ void openTransactionHistory(uint8_t entriesPerPage);
//void reportRuleViolation2();
void ping();
void setPingDelay(const int delay) { m_pingDelay = delay; }
// otclient only
- void changeMapAwareRange(const uint8_t xrange, const uint8_t yrange);
+ void changeMapAwareRange(uint8_t xrange, uint8_t yrange);
// dynamic support for game features
void enableFeature(const Otc::GameFeature feature) { m_features.set(feature, true); }
void disableFeature(const Otc::GameFeature feature) { m_features.set(feature, false); }
- void setFeature(const Otc::GameFeature feature, bool enabled) { m_features.set(feature, enabled); }
+ void setFeature(const Otc::GameFeature feature, const bool enabled) { m_features.set(feature, enabled); }
bool getFeature(const Otc::GameFeature feature) { return m_features.test(feature); }
- void setProtocolVersion(const uint16_t version);
+ void setProtocolVersion(uint16_t version);
int getProtocolVersion() { return m_protocolVersion; }
bool isUsingProtobuf() { return getProtocolVersion() >= 1281 && !getFeature(Otc::GameLoadSprInsteadProtobuf); }
- void setClientVersion(const uint16_t version);
+ void setClientVersion(uint16_t version);
int getClientVersion() { return m_clientVersion; }
void setCustomOs(const Otc::OperatingSystem_t os) { m_clientCustomOs = os; }
Otc::OperatingSystem_t getOs();
- void setWalkTurnDelay(uint16_t v) { m_walkTurnDelay = v; }
- void setWalkFirstStepDelay(uint16_t v) { m_walkFirstStepDelay = v; }
+ void setWalkTurnDelay(const uint16_t v) { m_walkTurnDelay = v; }
+ void setWalkFirstStepDelay(const uint16_t v) { m_walkFirstStepDelay = v; }
uint16_t getWalkTurnDelay() { return m_walkTurnDelay; }
uint16_t getWalkFirstStepDelay() { return m_walkFirstStepDelay; }
@@ -723,16 +723,16 @@ class Game
bool isConnectionOk() { return m_protocolGame && m_protocolGame->getElapsedTicksSinceLastRead() < 5000; }
int getPing() { return m_ping; }
- ContainerPtr getContainer(int index) { return m_containers[index]; }
+ ContainerPtr getContainer(const int index) { return m_containers[index]; }
stdext::map getContainers() { return m_containers; }
stdext::map getVips() { return m_vips; }
CreaturePtr getAttackingCreature() { return m_attackingCreature; }
CreaturePtr getFollowingCreature() { return m_followingCreature; }
- void setServerBeat(int beat) { m_serverBeat = beat; }
+ void setServerBeat(const int beat) { m_serverBeat = beat; }
int getServerBeat() { return m_serverBeat; }
- void setCanReportBugs(bool enable) { m_canReportBugs = enable; }
+ void setCanReportBugs(const bool enable) { m_canReportBugs = enable; }
bool canReportBugs() { return m_canReportBugs; }
- void setExpertPvpMode(bool enable) { m_expertPvpMode = enable; }
+ void setExpertPvpMode(const bool enable) { m_expertPvpMode = enable; }
bool getExpertPvpMode() { return m_expertPvpMode; }
LocalPlayerPtr getLocalPlayer() { return m_localPlayer; }
ProtocolGamePtr getProtocolGame() { return m_protocolGame; }
@@ -741,56 +741,56 @@ class Game
std::vector getGMActions() { return m_gmActions; }
bool isGM() { return !m_gmActions.empty(); }
- std::string formatCreatureName(const std::string_view name);
+ std::string formatCreatureName(std::string_view name);
int findEmptyContainerId();
// market related
void leaveMarket();
- void browseMarket(const uint8_t browseId, const uint8_t browseType);
- void createMarketOffer(const uint8_t type, const uint16_t itemId, const uint8_t itemTier, const uint16_t amount, const uint64_t price, const uint8_t anonymous);
- void cancelMarketOffer(const uint32_t timestamp, const uint16_t counter);
- void acceptMarketOffer(const uint32_t timestamp, const uint16_t counter, const uint16_t amount);
+ void browseMarket(uint8_t browseId, uint8_t browseType);
+ void createMarketOffer(uint8_t type, uint16_t itemId, uint8_t itemTier, uint16_t amount, uint64_t price, uint8_t anonymous);
+ void cancelMarketOffer(uint32_t timestamp, uint16_t counter);
+ void acceptMarketOffer(uint32_t timestamp, uint16_t counter, uint16_t amount);
// prey related
- void preyAction(const uint8_t slot, const uint8_t actionType, const uint16_t index);
+ void preyAction(uint8_t slot, uint8_t actionType, uint16_t index);
void preyRequest();
// imbuing related
- void applyImbuement(const uint8_t slot, const uint32_t imbuementId, const bool protectionCharm);
- void clearImbuement(const uint8_t slot);
+ void applyImbuement(uint8_t slot, uint32_t imbuementId, bool protectionCharm);
+ void clearImbuement(uint8_t slot);
void closeImbuingWindow();
void imbuementDurations(bool isOpen = false);
- void enableTileThingLuaCallback(bool value) { m_tileThingsLuaCallback = value; }
+ void enableTileThingLuaCallback(const bool value) { m_tileThingsLuaCallback = value; }
bool isTileThingLuaCallbackEnabled() { return m_tileThingsLuaCallback; }
- void stashWithdraw(const uint16_t itemId, const uint32_t count, const uint8_t stackpos);
+ void stashWithdraw(uint16_t itemId, uint32_t count, uint8_t stackpos);
// highscore related
- void requestHighscore(const uint8_t action, const uint8_t category, const uint32_t vocation, const std::string_view world, const uint8_t worldType, const uint8_t battlEye, const uint16_t page, const uint8_t totalPages);
- void processHighscore(const std::string_view serverName, const std::string_view world, const uint8_t worldType, const uint8_t battlEye,
- const std::vector>& vocations,
- const std::vector>& categories,
- const uint16_t page, const uint16_t totalPages,
- const std::vector>& highscores, const uint32_t entriesTs);
+ void requestHighscore(uint8_t action, uint8_t category, uint32_t vocation, std::string_view world, uint8_t worldType, uint8_t battlEye, uint16_t page, uint8_t totalPages);
+ void processHighscore(std::string_view serverName, std::string_view world, uint8_t worldType, uint8_t battlEye,
+ const std::vector>& vocations,
+ const std::vector>& categories,
+ uint16_t page, uint16_t totalPages,
+ const std::vector>& highscores, uint32_t entriesTs);
void requestBless();
- void requestQuickLootBlackWhiteList(const uint8_t filter, const uint16_t size, const std::vector& listedItems);
- void openContainerQuickLoot(const uint8_t action, const uint8_t category, const Position& pos, const uint16_t itemId, const uint8_t stackpos, const bool useMainAsFallback);
+ void requestQuickLootBlackWhiteList(uint8_t filter, uint16_t size, const std::vector& listedItems);
+ void openContainerQuickLoot(uint8_t action, uint8_t category, const Position& pos, uint16_t itemId, uint8_t stackpos, bool useMainAsFallback);
void sendGmTeleport(const Position& pos);
// cyclopedia related
void inspectionNormalObject(const Position& position);
- void inspectionObject(const Otc::InspectObjectTypes inspectionType, const uint16_t itemId, const uint8_t itemCount);
+ void inspectionObject(Otc::InspectObjectTypes inspectionType, uint16_t itemId, uint8_t itemCount);
void requestBestiary();
- void requestBestiaryOverview(const std::string_view catName);
- void requestBestiarySearch(const uint16_t raceId);
- void requestSendBuyCharmRune(const uint8_t runeId, const uint8_t action, const uint16_t raceId);
- void requestSendCharacterInfo(const uint32_t playerId, const Otc::CyclopediaCharacterInfoType_t characterInfoType, const uint16_t entriesPerPage = 0, const uint16_t page = 0);
+ void requestBestiaryOverview(std::string_view catName);
+ void requestBestiarySearch(uint16_t raceId);
+ void requestSendBuyCharmRune(uint8_t runeId, uint8_t action, uint16_t raceId);
+ void requestSendCharacterInfo(uint32_t playerId, Otc::CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage = 0, uint16_t page = 0);
void requestBosstiaryInfo();
void requestBossSlootInfo();
- void requestBossSlotAction(const uint8_t action, const uint32_t raceId);
- void sendStatusTrackerBestiary(const uint16_t raceId, const bool status);
+ void requestBossSlotAction(uint8_t action, uint32_t raceId);
+ void sendStatusTrackerBestiary(uint16_t raceId, bool status);
protected:
void enableBotCall() { m_denyBotCall = false; }
void disableBotCall() { m_denyBotCall = true; }
diff --git a/src/client/gameconfig.cpp b/src/client/gameconfig.cpp
index 41cf818d52..60142e52c1 100644
--- a/src/client/gameconfig.cpp
+++ b/src/client/gameconfig.cpp
@@ -21,9 +21,9 @@
*/
#include "gameconfig.h"
-#include
-#include
#include
+#include
+#include
GameConfig g_gameConfig;
@@ -31,9 +31,6 @@ static constexpr bool LOAD_SETUP = true;
void GameConfig::init()
{
- if (!LOAD_SETUP)
- return;
-
const std::string& fileName = "/data/setup";
try {
diff --git a/src/client/gameconfig.h b/src/client/gameconfig.h
index 37240e9f15..db05b94216 100644
--- a/src/client/gameconfig.h
+++ b/src/client/gameconfig.h
@@ -24,8 +24,8 @@
#include "declarations.h"
-#include
#include
+#include
// @bindclass
class GameConfig
diff --git a/src/client/item.cpp b/src/client/item.cpp
index b0fab796b3..be7d8b8a24 100644
--- a/src/client/item.cpp
+++ b/src/client/item.cpp
@@ -36,7 +36,7 @@
#include
#include
-ItemPtr Item::create(int id)
+ItemPtr Item::create(const int id)
{
const auto& item = std::make_shared- ();
item->setId(id);
@@ -44,7 +44,7 @@ ItemPtr Item::create(int id)
return item;
}
-void Item::draw(const Point& dest, bool drawThings, const LightViewPtr& lightView)
+void Item::draw(const Point& dest, const bool drawThings, const LightViewPtr& lightView)
{
if (!canDraw(m_color) || isHided())
return;
@@ -60,7 +60,7 @@ void Item::draw(const Point& dest, bool drawThings, const LightViewPtr& lightVie
internalDraw(animationPhase, dest, getHighlightColor(), drawThings, true);
}
-void Item::internalDraw(int animationPhase, const Point& dest, const Color& color, bool drawThings, bool replaceColorShader, const LightViewPtr& lightView)
+void Item::internalDraw(const int animationPhase, const Point& dest, const Color& color, const bool drawThings, const bool replaceColorShader, const LightViewPtr& lightView)
{
if (replaceColorShader)
g_drawPool.setShaderProgram(g_painter->getReplaceColorShader(), true);
@@ -95,14 +95,14 @@ void Item::setConductor()
{
if (isSingleGround()) {
m_drawConductor.agroup = true;
- m_drawConductor.order = DrawOrder::FIRST;
+ m_drawConductor.order = FIRST;
} else if (isSingleGroundBorder() && !hasElevation()) {
m_drawConductor.agroup = true;
- m_drawConductor.order = DrawOrder::SECOND;
+ m_drawConductor.order = SECOND;
}
}
-void Item::setPosition(const Position& position, uint8_t stackPos, bool hasElevation)
+void Item::setPosition(const Position& position, const uint8_t stackPos, const bool hasElevation)
{
Thing::setPosition(position, stackPos);
diff --git a/src/client/item.h b/src/client/item.h
index 4ea75b5739..67580a6e50 100644
--- a/src/client/item.h
+++ b/src/client/item.h
@@ -22,9 +22,9 @@
#pragma once
-#include
#include "effect.h"
#include "thing.h"
+#include
enum ItemAttr : uint8_t
{
@@ -71,7 +71,7 @@ enum ItemAttr : uint8_t
// @bindclass
#pragma pack(push,1) // disable memory alignment
-class Item : public Thing
+class Item final : public Thing
{
public:
static ItemPtr create(int id);
@@ -81,9 +81,9 @@ class Item : public Thing
void setId(uint32_t id) override;
- void setCountOrSubType(int value) { m_countOrSubType = value; updatePatterns(); }
- void setCount(int count) { m_countOrSubType = count; updatePatterns(); }
- void setSubType(int subType) { m_countOrSubType = subType; updatePatterns(); }
+ void setCountOrSubType(const int value) { m_countOrSubType = value; updatePatterns(); }
+ void setCount(const int count) { m_countOrSubType = count; updatePatterns(); }
+ void setSubType(const int subType) { m_countOrSubType = subType; updatePatterns(); }
void setColor(const Color& c) { if (m_color != c) m_color = c; }
void setPosition(const Position& position, uint8_t stackPos = 0, bool hasElevation = false) override;
void setTooltip(const std::string& str) { m_tooltip = str; }
@@ -101,7 +101,7 @@ class Item : public Thing
bool isValid() { return getThingType() != nullptr; }
- void setAsync(bool enable) { m_async = enable; }
+ void setAsync(const bool enable) { m_async = enable; }
ItemPtr clone();
ItemPtr asItem() { return static_self_cast
- (); }
@@ -109,7 +109,7 @@ class Item : public Thing
void updatePatterns();
int calculateAnimationPhase();
- int getExactSize(int layer = 0, int /*xPattern*/ = 0, int /*yPattern*/ = 0, int /*zPattern*/ = 0, int /*animationPhase*/ = 0) override {
+ int getExactSize(const int layer = 0, int /*xPattern*/ = 0, int /*yPattern*/ = 0, int /*zPattern*/ = 0, int /*animationPhase*/ = 0) override {
return Thing::getExactSize(layer, m_numPatternX, m_numPatternY, m_numPatternZ, calculateAnimationPhase());
}
diff --git a/src/client/lightview.cpp b/src/client/lightview.cpp
index ce93428a07..15ab19bea5 100644
--- a/src/client/lightview.cpp
+++ b/src/client/lightview.cpp
@@ -25,8 +25,8 @@
#include "mapview.h"
#include "spritemanager.h"
-#include
#include
+#include
#include
LightView::LightView(const Size& size) : m_pool(g_drawPool.get(DrawPoolType::LIGHT)) {
@@ -54,7 +54,7 @@ void LightView::resize(const Size& size, const uint16_t tileSize) {
m_texture->setupSize(m_mapSize);
}
-void LightView::addLightSource(const Point& pos, const Light& light, float brightness)
+void LightView::addLightSource(const Point& pos, const Light& light, const float brightness)
{
if (!isDark() || light.intensity == 0)
return;
@@ -82,7 +82,7 @@ void LightView::addLightSource(const Point& pos, const Light& light, float brigh
void LightView::resetShade(const Point& pos)
{
- size_t index = (pos.y / m_tileSize) * m_mapSize.width() + (pos.x / m_tileSize);
+ const size_t index = (pos.y / m_tileSize) * m_mapSize.width() + (pos.x / m_tileSize);
if (index >= m_lightData.tiles.size()) return;
m_lightData.tiles[index] = m_lightData.lights.size();
}
diff --git a/src/client/lightview.h b/src/client/lightview.h
index 79b11c0f08..2e93eaded5 100644
--- a/src/client/lightview.h
+++ b/src/client/lightview.h
@@ -22,16 +22,16 @@
#pragma once
-#include
-#include
#include "declarations.h"
#include "thingtype.h"
+#include
+#include
-class LightView : public LuaObject
+class LightView final : public LuaObject
{
public:
LightView(const Size& size);
- ~LightView() { m_texture = nullptr; }
+ ~LightView() override { m_texture = nullptr; }
void resize(const Size& size, uint16_t tileSize);
void draw(const Rect& dest, const Rect& src);
@@ -48,15 +48,15 @@ class LightView : public LuaObject
bool isDark() const { return m_isDark; }
bool isEnabled() const { return m_pool->isEnabled(); }
- void setEnabled(bool v) { m_pool->setEnable(v); }
+ void setEnabled(const bool v) { m_pool->setEnable(v); }
private:
- struct TileLight : public Light
+ struct TileLight : Light
{
Point pos;
float brightness{ 1.f };
- TileLight(const Point& pos, uint8_t intensity, uint8_t color, float brightness) : Light(intensity, color), pos(pos), brightness(brightness) {}
+ TileLight(const Point& pos, const uint8_t intensity, const uint8_t color, const float brightness) : Light(intensity, color), pos(pos), brightness(brightness) {}
};
struct LightData
diff --git a/src/client/localplayer.cpp b/src/client/localplayer.cpp
index c01dccde50..82ff76128a 100644
--- a/src/client/localplayer.cpp
+++ b/src/client/localplayer.cpp
@@ -21,17 +21,17 @@
*/
#include "localplayer.h"
-#include
#include "game.h"
#include "map.h"
#include "tile.h"
+#include
-void LocalPlayer::lockWalk(uint16_t millis)
+void LocalPlayer::lockWalk(const uint16_t millis)
{
m_walkLockExpiration = std::max(m_walkLockExpiration, g_clock.millis() + millis);
}
-bool LocalPlayer::canWalk(Otc::Direction dir, bool ignoreLock)
+bool LocalPlayer::canWalk(const Otc::Direction dir, const bool ignoreLock)
{
// paralyzed
if (isDead())
@@ -59,7 +59,7 @@ void LocalPlayer::walk(const Position& oldPos, const Position& newPos)
Creature::walk(oldPos, newPos);
}
-void LocalPlayer::preWalk(Otc::Direction direction)
+void LocalPlayer::preWalk(const Otc::Direction direction)
{
// avoid reanimating prewalks
if (m_preWalking)
@@ -96,7 +96,7 @@ bool LocalPlayer::retryAutoWalk()
return false;
}
-void LocalPlayer::cancelWalk(Otc::Direction direction)
+void LocalPlayer::cancelWalk(const Otc::Direction direction)
{
// only cancel client side walks
if (m_walking && m_preWalking)
@@ -114,7 +114,7 @@ void LocalPlayer::cancelWalk(Otc::Direction direction)
callLuaField("onCancelWalk", direction);
}
-bool LocalPlayer::autoWalk(const Position& destination, bool retry)
+bool LocalPlayer::autoWalk(const Position& destination, const bool retry)
{
// reset state
m_autoWalkDestination = {};
@@ -184,7 +184,7 @@ void LocalPlayer::stopWalk()
m_lastPrewalkDestination = {};
}
-void LocalPlayer::updateWalkOffset(uint8_t totalPixelsWalked)
+void LocalPlayer::updateWalkOffset(const uint8_t totalPixelsWalked)
{
if (!m_preWalking) {
Creature::updateWalkOffset(totalPixelsWalked);
@@ -220,7 +220,7 @@ void LocalPlayer::onPositionChange(const Position& newPos, const Position& oldPo
autoWalk(m_autoWalkDestination);
}
-void LocalPlayer::setStates(uint32_t states)
+void LocalPlayer::setStates(const uint32_t states)
{
if (m_states == states)
return;
@@ -234,7 +234,7 @@ void LocalPlayer::setStates(uint32_t states)
callLuaField("onStatesChange", states, oldStates);
}
-void LocalPlayer::setSkill(Otc::Skill skillId, uint16_t level, uint16_t levelPercent)
+void LocalPlayer::setSkill(const Otc::Skill skillId, const uint16_t level, const uint16_t levelPercent)
{
if (skillId >= Otc::LastSkill) {
g_logger.traceError("invalid skill");
@@ -255,7 +255,7 @@ void LocalPlayer::setSkill(Otc::Skill skillId, uint16_t level, uint16_t levelPer
callLuaField("onSkillChange", skillId, level, levelPercent, oldLevel, oldLevelPercent);
}
-void LocalPlayer::setBaseSkill(Otc::Skill skill, uint16_t baseLevel)
+void LocalPlayer::setBaseSkill(const Otc::Skill skill, const uint16_t baseLevel)
{
if (skill >= Otc::LastSkill) {
g_logger.traceError("invalid skill");
@@ -271,7 +271,7 @@ void LocalPlayer::setBaseSkill(Otc::Skill skill, uint16_t baseLevel)
callLuaField("onBaseSkillChange", skill, baseLevel, oldBaseLevel);
}
-void LocalPlayer::setHealth(uint32_t health, uint32_t maxHealth)
+void LocalPlayer::setHealth(const uint32_t health, const uint32_t maxHealth)
{
if (m_health != health || m_maxHealth != maxHealth) {
const uint32_t oldHealth = m_health;
@@ -289,7 +289,7 @@ void LocalPlayer::setHealth(uint32_t health, uint32_t maxHealth)
}
}
-void LocalPlayer::setFreeCapacity(uint32_t freeCapacity)
+void LocalPlayer::setFreeCapacity(const uint32_t freeCapacity)
{
if (m_freeCapacity == freeCapacity)
return;
@@ -300,7 +300,7 @@ void LocalPlayer::setFreeCapacity(uint32_t freeCapacity)
callLuaField("onFreeCapacityChange", freeCapacity, oldFreeCapacity);
}
-void LocalPlayer::setTotalCapacity(uint32_t totalCapacity)
+void LocalPlayer::setTotalCapacity(const uint32_t totalCapacity)
{
if (m_totalCapacity == totalCapacity)
return;
@@ -311,7 +311,7 @@ void LocalPlayer::setTotalCapacity(uint32_t totalCapacity)
callLuaField("onTotalCapacityChange", totalCapacity, oldTotalCapacity);
}
-void LocalPlayer::setExperience(uint64_t experience)
+void LocalPlayer::setExperience(const uint64_t experience)
{
if (m_experience == experience)
return;
@@ -322,7 +322,7 @@ void LocalPlayer::setExperience(uint64_t experience)
callLuaField("onExperienceChange", experience, oldExperience);
}
-void LocalPlayer::setLevel(uint16_t level, uint8_t levelPercent)
+void LocalPlayer::setLevel(const uint16_t level, const uint8_t levelPercent)
{
if (m_level == level && m_levelPercent == levelPercent)
return;
@@ -336,7 +336,7 @@ void LocalPlayer::setLevel(uint16_t level, uint8_t levelPercent)
callLuaField("onLevelChange", level, levelPercent, oldLevel, oldLevelPercent);
}
-void LocalPlayer::setMana(uint32_t mana, uint32_t maxMana)
+void LocalPlayer::setMana(const uint32_t mana, const uint32_t maxMana)
{
if (m_mana == mana && m_maxMana == maxMana)
return;
@@ -349,13 +349,13 @@ void LocalPlayer::setMana(uint32_t mana, uint32_t maxMana)
callLuaField("onManaChange", mana, maxMana, oldMana, oldMaxMana);
}
-void LocalPlayer::setMagicLevel(uint8_t magicLevel, uint8_t magicLevelPercent)
+void LocalPlayer::setMagicLevel(const uint16_t magicLevel, const uint16_t magicLevelPercent)
{
if (m_magicLevel == magicLevel && m_magicLevelPercent == magicLevelPercent)
return;
- const uint8_t oldMagicLevel = m_magicLevel;
- const uint8_t oldMagicLevelPercent = m_magicLevelPercent;
+ const uint16_t oldMagicLevel = m_magicLevel;
+ const uint16_t oldMagicLevelPercent = m_magicLevelPercent;
m_magicLevel = magicLevel;
m_magicLevelPercent = magicLevelPercent;
@@ -363,18 +363,18 @@ void LocalPlayer::setMagicLevel(uint8_t magicLevel, uint8_t magicLevelPercent)
callLuaField("onMagicLevelChange", magicLevel, magicLevelPercent, oldMagicLevel, oldMagicLevelPercent);
}
-void LocalPlayer::setBaseMagicLevel(uint8_t baseMagicLevel)
+void LocalPlayer::setBaseMagicLevel(const uint16_t baseMagicLevel)
{
if (m_baseMagicLevel == baseMagicLevel)
return;
- const uint8_t oldBaseMagicLevel = m_baseMagicLevel;
+ const uint16_t oldBaseMagicLevel = m_baseMagicLevel;
m_baseMagicLevel = baseMagicLevel;
callLuaField("onBaseMagicLevelChange", baseMagicLevel, oldBaseMagicLevel);
}
-void LocalPlayer::setSoul(uint8_t soul)
+void LocalPlayer::setSoul(const uint8_t soul)
{
if (m_soul == soul)
return;
@@ -385,7 +385,7 @@ void LocalPlayer::setSoul(uint8_t soul)
callLuaField("onSoulChange", soul, oldSoul);
}
-void LocalPlayer::setStamina(uint16_t stamina)
+void LocalPlayer::setStamina(const uint16_t stamina)
{
if (m_stamina == stamina)
return;
@@ -396,7 +396,7 @@ void LocalPlayer::setStamina(uint16_t stamina)
callLuaField("onStaminaChange", stamina, oldStamina);
}
-void LocalPlayer::setInventoryItem(Otc::InventorySlot inventory, const ItemPtr& item)
+void LocalPlayer::setInventoryItem(const Otc::InventorySlot inventory, const ItemPtr& item)
{
if (inventory >= Otc::LastInventorySlot) {
g_logger.traceError("invalid slot");
@@ -412,7 +412,7 @@ void LocalPlayer::setInventoryItem(Otc::InventorySlot inventory, const ItemPtr&
callLuaField("onInventoryChange", inventory, item, oldItem);
}
-void LocalPlayer::setVocation(uint8_t vocation)
+void LocalPlayer::setVocation(const uint8_t vocation)
{
if (m_vocation == vocation)
return;
@@ -423,7 +423,7 @@ void LocalPlayer::setVocation(uint8_t vocation)
callLuaField("onVocationChange", vocation, oldVocation);
}
-void LocalPlayer::setPremium(bool premium)
+void LocalPlayer::setPremium(const bool premium)
{
if (m_premium == premium)
return;
@@ -433,7 +433,7 @@ void LocalPlayer::setPremium(bool premium)
callLuaField("onPremiumChange", premium);
}
-void LocalPlayer::setRegenerationTime(uint16_t regenerationTime)
+void LocalPlayer::setRegenerationTime(const uint16_t regenerationTime)
{
if (m_regenerationTime == regenerationTime)
return;
@@ -444,7 +444,7 @@ void LocalPlayer::setRegenerationTime(uint16_t regenerationTime)
callLuaField("onRegenerationChange", regenerationTime, oldRegenerationTime);
}
-void LocalPlayer::setOfflineTrainingTime(uint16_t offlineTrainingTime)
+void LocalPlayer::setOfflineTrainingTime(const uint16_t offlineTrainingTime)
{
if (m_offlineTrainingTime == offlineTrainingTime)
return;
@@ -466,7 +466,7 @@ void LocalPlayer::setSpells(const std::vector& spells)
callLuaField("onSpellsChange", spells, oldSpells);
}
-void LocalPlayer::setBlessings(uint16_t blessings)
+void LocalPlayer::setBlessings(const uint16_t blessings)
{
if (blessings == m_blessings)
return;
@@ -477,12 +477,12 @@ void LocalPlayer::setBlessings(uint16_t blessings)
callLuaField("onBlessingsChange", blessings, oldBlessings);
}
-void LocalPlayer::takeScreenshot(uint8_t type)
+void LocalPlayer::takeScreenshot(const uint8_t type)
{
g_lua.callGlobalField("LocalPlayer", "onTakeScreenshot", type);
}
-void LocalPlayer::setResourceBalance(Otc::ResourceTypes_t type, uint64_t value)
+void LocalPlayer::setResourceBalance(const Otc::ResourceTypes_t type, const uint64_t value)
{
const uint64_t oldBalance = getResourceBalance(type);
if (value == oldBalance)
diff --git a/src/client/localplayer.h b/src/client/localplayer.h
index eaf37ab5c9..503d487b71 100644
--- a/src/client/localplayer.h
+++ b/src/client/localplayer.h
@@ -25,7 +25,7 @@
#include "player.h"
// @bindclass
-class LocalPlayer : public Player
+class LocalPlayer final : public Player
{
public:
void unlockWalk() { m_walkLockExpiration = 0; }
@@ -45,12 +45,12 @@ class LocalPlayer : public Player
void setExperience(uint64_t experience);
void setLevel(uint16_t level, uint8_t levelPercent);
void setMana(uint32_t mana, uint32_t maxMana);
- void setMagicLevel(uint8_t magicLevel, uint8_t magicLevelPercent);
- void setBaseMagicLevel(uint8_t baseMagicLevel);
+ void setMagicLevel(uint16_t magicLevel, uint16_t magicLevelPercent);
+ void setBaseMagicLevel(uint16_t baseMagicLevel);
void setSoul(uint8_t soul);
void setStamina(uint16_t stamina);
- void setKnown(bool known) { m_known = known; }
- void setPendingGame(bool pending) { m_pending = pending; }
+ void setKnown(const bool known) { m_known = known; }
+ void setPendingGame(const bool pending) { m_pending = pending; }
void setInventoryItem(Otc::InventorySlot inventory, const ItemPtr& item);
void setVocation(uint8_t vocation);
void setPremium(bool premium);
@@ -65,16 +65,16 @@ class LocalPlayer : public Player
uint32_t getTotalCapacity() { return m_totalCapacity; }
uint8_t getVocation() { return m_vocation; }
- uint8_t getMagicLevel() { return m_magicLevel; }
- uint8_t getMagicLevelPercent() { return m_magicLevelPercent; }
- uint8_t getBaseMagicLevel() { return m_baseMagicLevel; }
+ uint16_t getMagicLevel() { return m_magicLevel; }
+ uint16_t getMagicLevelPercent() { return m_magicLevelPercent; }
+ uint16_t getBaseMagicLevel() { return m_baseMagicLevel; }
uint8_t getSoul() { return m_soul; }
uint8_t getLevelPercent() { return m_levelPercent; }
uint16_t getLevel() { return m_level; }
- uint16_t getSkillLevel(Otc::Skill skill) { return m_skills[skill].level; }
- uint16_t getSkillBaseLevel(Otc::Skill skill) { return m_skills[skill].baseLevel; }
- uint16_t getSkillLevelPercent(Otc::Skill skill) { return m_skills[skill].levelPercent; }
+ uint16_t getSkillLevel(const Otc::Skill skill) { return m_skills[skill].level; }
+ uint16_t getSkillBaseLevel(const Otc::Skill skill) { return m_skills[skill].baseLevel; }
+ uint16_t getSkillLevelPercent(const Otc::Skill skill) { return m_skills[skill].levelPercent; }
uint16_t getStamina() { return m_stamina; }
uint16_t getBlessings() { return m_blessings; }
uint16_t getRegenerationTime() { return m_regenerationTime; }
@@ -88,9 +88,9 @@ class LocalPlayer : public Player
uint64_t getExperience() { return m_experience; }
const std::vector& getSpells() { return m_spells; }
- ItemPtr getInventoryItem(Otc::InventorySlot inventory) { return m_inventoryItems[inventory]; }
+ ItemPtr getInventoryItem(const Otc::InventorySlot inventory) { return m_inventoryItems[inventory]; }
- uint64_t getResourceBalance(Otc::ResourceTypes_t type)
+ uint64_t getResourceBalance(const Otc::ResourceTypes_t type)
{
const auto it = m_resourcesBalance.find(type);
return it != m_resourcesBalance.end() ? it->second : 0;
@@ -175,9 +175,9 @@ class LocalPlayer : public Player
uint8_t m_levelPercent{ 0 };
uint32_t m_mana{ 0 };
uint32_t m_maxMana{ 0 };
- uint8_t m_magicLevel{ 0 };
- uint8_t m_magicLevelPercent{ 0 };
- uint8_t m_baseMagicLevel{ 0 };
+ uint16_t m_magicLevel{ 0 };
+ uint16_t m_magicLevelPercent{ 0 };
+ uint16_t m_baseMagicLevel{ 0 };
uint8_t m_soul{ 0 };
uint16_t m_stamina{ 0 };
uint16_t m_regenerationTime{ 0 };
diff --git a/src/client/luafunctions.cpp b/src/client/luafunctions.cpp
index 8942bc1d45..46c4891a27 100644
--- a/src/client/luafunctions.cpp
+++ b/src/client/luafunctions.cpp
@@ -22,6 +22,7 @@
#include "animatedtext.h"
#include "attachedeffect.h"
+#include "attachedeffectmanager.h"
#include "client.h"
#include "container.h"
#include "creature.h"
@@ -37,7 +38,6 @@
#include "outfit.h"
#include "player.h"
#include "protocolgame.h"
-#include "attachedeffectmanager.h"
#include "spriteappearances.h"
#include "spritemanager.h"
#include "statictext.h"
@@ -45,17 +45,17 @@
#include "tile.h"
#include "towns.h"
#include "uicreature.h"
-#include "uiitem.h"
#include "uieffect.h"
+#include "uiitem.h"
#include "uimissile.h"
+#include "attachableobject.h"
+#include "uigraph.h"
#include "uimap.h"
#include "uimapanchorlayout.h"
#include "uiminimap.h"
#include "uiprogressrect.h"
#include "uisprite.h"
-#include "uigraph.h"
-#include "attachableobject.h"
#ifdef FRAMEWORK_EDITOR
#include "houses.h"
diff --git a/src/client/luavaluecasts_client.cpp b/src/client/luavaluecasts_client.cpp
index dda6fb325a..8bde115671 100644
--- a/src/client/luavaluecasts_client.cpp
+++ b/src/client/luavaluecasts_client.cpp
@@ -49,7 +49,7 @@ int push_luavalue(const Outfit& outfit)
return 1;
}
-bool luavalue_cast(int index, Outfit& outfit)
+bool luavalue_cast(const int index, Outfit& outfit)
{
if (!g_lua.isTable(index))
return false;
@@ -104,7 +104,7 @@ int push_luavalue(const Position& pos)
return 1;
}
-bool luavalue_cast(int index, Position& pos)
+bool luavalue_cast(const int index, Position& pos)
{
if (!g_lua.isTable(index))
return false;
@@ -140,7 +140,7 @@ int push_luavalue(const std::vector& data) {
return 1;
}
-bool luavalue_cast(int index, std::vector& data)
+bool luavalue_cast(const int index, std::vector& data)
{
if (!g_lua.isTable(index))
return false;
@@ -187,7 +187,7 @@ int push_luavalue(const MarketData& data)
return 1;
}
-bool luavalue_cast(int index, MarketData& data)
+bool luavalue_cast(const int index, MarketData& data)
{
if (!g_lua.isTable(index))
return false;
@@ -219,7 +219,7 @@ int push_luavalue(const Light& light)
return 1;
}
-bool luavalue_cast(int index, Light& light)
+bool luavalue_cast(const int index, Light& light)
{
if (!g_lua.isTable(index))
return false;
@@ -315,7 +315,7 @@ int push_luavalue(const ImbuementTrackerItem& i)
return 1;
}
-bool luavalue_cast(int index, UnjustifiedPoints& unjustifiedPoints)
+bool luavalue_cast(const int index, UnjustifiedPoints& unjustifiedPoints)
{
if (!g_lua.isTable(index))
return false;
@@ -396,7 +396,7 @@ int push_luavalue(const BlessDialogData& data) {
g_lua.rawSeti(i + 1);
}
g_lua.setField("logs");
-
+
return 1;
}
@@ -749,7 +749,7 @@ int push_luavalue(const BestiaryMonsterData& data) {
}
return 1;
-}
+}
int push_luavalue(const CharmData& charm) {
g_lua.createTable(0, 7);
@@ -971,7 +971,7 @@ int push_luavalue(const BosstiarySlotsData& data) {
g_lua.rawSeti(i + 1);
}
g_lua.setField("bossesUnlockedData");
- return 1;
+ return 1;
}
int push_luavalue(const ItemSummary& item) {
@@ -1124,4 +1124,4 @@ int push_luavalue(const CharacterInfoFamiliar& familiar) {
g_lua.pushInteger(familiar.isCurrent);
g_lua.setField("isCurrent");
return 1;
-}
+}
\ No newline at end of file
diff --git a/src/client/map.cpp b/src/client/map.cpp
index b770ccc0cd..dab8f13bcb 100644
--- a/src/client/map.cpp
+++ b/src/client/map.cpp
@@ -30,9 +30,10 @@
#include "statictext.h"
#include "tile.h"
+#include
#include
-#include
#include
+#include
#include
#include
@@ -69,7 +70,7 @@ void Map::addMapView(const MapViewPtr& mapView) { m_mapViews.push_back(mapView);
void Map::removeMapView(const MapViewPtr& mapView)
{
- const auto it = std::find(m_mapViews.begin(), m_mapViews.end(), mapView);
+ const auto it = std::ranges::find(m_mapViews, mapView);
if (it != m_mapViews.end())
m_mapViews.erase(it);
}
@@ -147,7 +148,7 @@ void Map::cleanDynamicThings()
cleanTexts();
}
-void Map::addThing(const ThingPtr& thing, const Position& pos, int16_t stackPos)
+void Map::addThing(const ThingPtr& thing, const Position& pos, const int16_t stackPos)
{
if (!thing)
return;
@@ -225,7 +226,7 @@ void Map::addAnimatedText(const AnimatedTextPtr& txt, const Position& pos) {
});
}
-ThingPtr Map::getThing(const Position& pos, int16_t stackPos)
+ThingPtr Map::getThing(const Position& pos, const int16_t stackPos)
{
if (const auto& tile = getTile(pos))
return tile->getThing(stackPos);
@@ -240,7 +241,7 @@ bool Map::removeThing(const ThingPtr& thing)
if (thing->isMissile()) {
auto& missiles = m_floors[thing->getPosition().z].missiles;
- const auto it = std::find(missiles.begin(), missiles.end(), thing->static_self_cast());
+ const auto it = std::ranges::find(missiles, thing->static_self_cast());
if (it == missiles.end())
return false;
@@ -258,7 +259,7 @@ bool Map::removeThing(const ThingPtr& thing)
return false;
}
-bool Map::removeThingByPos(const Position& pos, int16_t stackPos)
+bool Map::removeThingByPos(const Position& pos, const int16_t stackPos)
{
if (const auto& tile = getTile(pos))
return removeThing(tile->getThing(stackPos));
@@ -267,7 +268,7 @@ bool Map::removeThingByPos(const Position& pos, int16_t stackPos)
}
bool Map::removeStaticText(const StaticTextPtr& txt) {
- const auto it = std::find(m_staticTexts.begin(), m_staticTexts.end(), txt);
+ const auto it = std::ranges::find(m_staticTexts, txt);
if (it == m_staticTexts.end())
return false;
@@ -276,7 +277,7 @@ bool Map::removeStaticText(const StaticTextPtr& txt) {
}
bool Map::removeAnimatedText(const AnimatedTextPtr& txt) {
- const auto it = std::find(m_animatedTexts.begin(), m_animatedTexts.end(), txt);
+ const auto it = std::ranges::find(m_animatedTexts, txt);
if (it == m_animatedTexts.end())
return false;
@@ -361,7 +362,7 @@ const TilePtr& Map::getTile(const Position& pos)
return m_nulltile;
}
-TileList Map::getTiles(int8_t floor/* = -1*/)
+TileList Map::getTiles(const int8_t floor/* = -1*/)
{
TileList tiles;
if (floor > g_gameConfig.getMapMaxZ())
@@ -472,10 +473,10 @@ void Map::setShowAnimations(bool show)
}
#endif
-void Map::beginGhostMode(float opacity) { g_painter->setOpacity(opacity); }
+void Map::beginGhostMode(const float opacity) { g_painter->setOpacity(opacity); }
void Map::endGhostMode() { g_painter->resetOpacity(); }
-stdext::map Map::findItemsById(uint16_t clientId, uint32_t max)
+stdext::map Map::findItemsById(const uint16_t clientId, const uint32_t max)
{
stdext::map ret;
uint32_t count = 0;
@@ -498,14 +499,14 @@ stdext::map Map::findItemsById(uint16_t cli
return ret;
}
-CreaturePtr Map::getCreatureById(uint32_t id)
+CreaturePtr Map::getCreatureById(const uint32_t id)
{
const auto it = m_knownCreatures.find(id);
return it != m_knownCreatures.end() ? it->second : nullptr;
}
void Map::addCreature(const CreaturePtr& creature) { m_knownCreatures[creature->getId()] = creature; }
-void Map::removeCreatureById(uint32_t id)
+void Map::removeCreatureById(const uint32_t id)
{
if (id == 0)
return;
@@ -539,7 +540,7 @@ void Map::removeUnawareThings()
for (auto z = -1; ++z <= g_gameConfig.getMapMaxZ();) {
auto& tileBlocks = m_floors[z].tileBlocks;
for (auto it = tileBlocks.begin(); it != tileBlocks.end();) {
- auto& block = (*it).second;
+ auto& block = it->second;
bool blockEmpty = true;
for (const auto& tile : block.getTiles()) {
if (!tile) continue;
@@ -610,7 +611,7 @@ void Map::setLight(const Light& light)
mapView->onGlobalLightChange(m_light);
}
-std::vector Map::getSpectatorsInRangeEx(const Position& centerPos, bool multiFloor, int32_t minXRange, int32_t maxXRange, int32_t minYRange, int32_t maxYRange)
+std::vector Map::getSpectatorsInRangeEx(const Position& centerPos, const bool multiFloor, const int32_t minXRange, const int32_t maxXRange, const int32_t minYRange, const int32_t maxYRange)
{
std::vector creatures;
uint8_t minZRange = 0;
@@ -643,7 +644,7 @@ bool Map::isLookPossible(const Position& pos)
return tile && tile->isLookPossible();
}
-bool Map::isCovered(const Position& pos, uint8_t firstFloor)
+bool Map::isCovered(const Position& pos, const uint8_t firstFloor)
{
// check for tiles on top of the postion
Position tilePos = pos;
@@ -663,7 +664,7 @@ bool Map::isCovered(const Position& pos, uint8_t firstFloor)
return false;
}
-bool Map::isCompletelyCovered(const Position& pos, uint8_t firstFloor)
+bool Map::isCompletelyCovered(const Position& pos, const uint8_t firstFloor)
{
const auto& checkTile = getTile(pos);
Position tilePos = pos;
@@ -741,10 +742,10 @@ void Map::setAwareRange(const AwareRange& range)
void Map::resetAwareRange() {
setAwareRange({
- static_cast(g_gameConfig.getMapViewPort().width()) ,
- static_cast(g_gameConfig.getMapViewPort().height()),
- static_cast(g_gameConfig.getMapViewPort().width() + 1),
- static_cast(g_gameConfig.getMapViewPort().height() + 1)
+ .left = static_cast(g_gameConfig.getMapViewPort().width()) ,
+ .top = static_cast(g_gameConfig.getMapViewPort().height()),
+ .right = static_cast(g_gameConfig.getMapViewPort().width() + 1),
+ .bottom = static_cast(g_gameConfig.getMapViewPort().height() + 1)
});
}
@@ -764,23 +765,24 @@ uint8_t Map::getLastAwareFloor() const
return std::min(m_centralPosition.z + g_gameConfig.getMapAwareUndergroundFloorRange(), g_gameConfig.getMapMaxZ());
}
-std::tuple, Otc::PathFindResult> Map::findPath(const Position& startPos, const Position& goalPos, int maxComplexity, int flags)
+std::tuple, Otc::PathFindResult> Map::findPath(const Position& startPos, const Position& goalPos, const int maxComplexity, const int flags)
{
// pathfinding using dijkstra search algorithm
struct SNode
{
- SNode(const Position& pos) : cost(0), totalCost(0), pos(pos), prev(nullptr), dir(Otc::InvalidDirection) {}
- float cost;
- float totalCost;
+ SNode(const Position& pos) :
+ pos(pos) {}
+ float cost{ 0 };
+ float totalCost{ 0 };
Position pos;
- SNode* prev;
- Otc::Direction dir;
+ SNode* prev{ nullptr };
+ Otc::Direction dir{ Otc::InvalidDirection };
};
struct LessNode
{
- bool operator()(std::pair a, std::pair b) const
+ bool operator()(const std::pair a, const std::pair b) const
{
return b.second < a.second;
}
@@ -910,7 +912,7 @@ std::tuple, Otc::PathFindResult> Map::findPath(const
neighborNode->cost = cost;
neighborNode->totalCost = neighborNode->cost + neighborPos.distance(goalPos);
neighborNode->dir = walkDir;
- searchList.push(std::make_pair(neighborNode, neighborNode->totalCost));
+ searchList.emplace(neighborNode, neighborNode->totalCost);
}
}
@@ -928,7 +930,7 @@ std::tuple, Otc::PathFindResult> Map::findPath(const
currentNode = currentNode->prev;
}
dirs.pop_back();
- std::reverse(dirs.begin(), dirs.end());
+ std::ranges::reverse(dirs);
result = Otc::PathFindResultOk;
}
@@ -975,7 +977,7 @@ PathFindResult_ptr Map::newFindPath(const Position& start, const Position& goal,
struct LessNode
{
- bool operator()(Node const* a, Node const* b) const
+ bool operator()(const Node* a, const Node* b) const
{
return b->totalCost < a->totalCost;
}
@@ -989,14 +991,14 @@ PathFindResult_ptr Map::newFindPath(const Position& start, const Position& goal,
nodes.emplace(node->pos, node);
}
- const auto& initNode = new Node{ 1, 0, start, nullptr, 0, 0 };
+ const auto& initNode = new Node{ .cost = 1, .totalCost = 0, .pos = start, .prev = nullptr, .distance = 0, .unseen = 0 };
nodes[start] = initNode;
searchList.push(initNode);
int limit = 50000;
const float distance = start.distance(goal);
- Node* dstNode = nullptr;
+ const Node* dstNode = nullptr;
while (!searchList.empty() && --limit) {
Node* node = searchList.top();
searchList.pop();
@@ -1025,7 +1027,9 @@ PathFindResult_ptr Map::newFindPath(const Position& start, const Position& goal,
} else {
if (!wasSeen)
speed = 2000;
- it = nodes.emplace(neighbor, new Node{ speed, 10000000.0f, neighbor, node, node->distance + 1, wasSeen ? 0 : 1 }).first;
+ it = nodes.emplace(neighbor, new Node{ .cost = speed, .totalCost = 10000000.0f, .pos = neighbor, .prev =
+ node,
+ .distance = node->distance + 1, .unseen = wasSeen ? 0 : 1 }).first;
}
}
if (!it->second) // no way
@@ -1081,9 +1085,14 @@ void Map::findPathAsync(const Position& start, const Position& goal, const std::
const bool isNotPathable = !tile->isPathable();
const float speed = tile->getGroundSpeed();
if ((isNotWalkable || isNotPathable) && tile->getPosition() != goal) {
- visibleNodes->push_back(new Node{ speed, 0, tile->getPosition(), nullptr, 0, 0 });
+ visibleNodes->push_back(new Node{ .cost = speed, .totalCost = 0, .pos = tile->getPosition(), .prev = nullptr, .distance =
+ 0,
+ .unseen = 0
+ });
} else {
- visibleNodes->push_back(new Node{ speed, 10000000.0f, tile->getPosition(), nullptr, 0, 0 });
+ visibleNodes->push_back(new Node{ .cost = speed, .totalCost = 10000000.0f, .pos = tile->getPosition(), .prev =
+ nullptr, .distance = 0, .unseen = 0
+ });
}
}
@@ -1113,19 +1122,19 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos)
}
Position start(fromPos.z > toPos.z ? toPos : fromPos);
- Position destination(fromPos.z > toPos.z ? fromPos : toPos);
+ const Position destination(fromPos.z > toPos.z ? fromPos : toPos);
const int8_t mx = start.x < destination.x ? 1 : start.x == destination.x ? 0 : -1;
const int8_t my = start.y < destination.y ? 1 : start.y == destination.y ? 0 : -1;
- int32_t A = destination.y - start.y;
- int32_t B = start.x - destination.x;
- int32_t C = -(A * destination.x + B * destination.y);
+ const int32_t A = destination.y - start.y;
+ const int32_t B = start.x - destination.x;
+ const int32_t C = -(A * destination.x + B * destination.y);
while (start.x != destination.x || start.y != destination.y) {
- int32_t move_hor = std::abs(A * (start.x + mx) + B * (start.y) + C);
- int32_t move_ver = std::abs(A * (start.x) + B * (start.y + my) + C);
- int32_t move_cross = std::abs(A * (start.x + mx) + B * (start.y + my) + C);
+ const int32_t move_hor = std::abs(A * (start.x + mx) + B * (start.y) + C);
+ const int32_t move_ver = std::abs(A * (start.x) + B * (start.y + my) + C);
+ const int32_t move_cross = std::abs(A * (start.x + mx) + B * (start.y + my) + C);
if (start.y != destination.y && (start.x == destination.x || move_hor > move_ver || move_hor > move_cross)) {
start.y += my;
@@ -1135,14 +1144,14 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos)
start.x += mx;
}
- auto tile = getTile(Position(start.x, start.y, start.z));
+ const auto tile = getTile(Position(start.x, start.y, start.z));
if (tile && !tile->isLookPossible()) {
return false;
}
}
while (start.z != destination.z) {
- auto tile = getTile(Position(start.x, start.y, start.z));
+ const auto tile = getTile(Position(start.x, start.y, start.z));
if (tile && tile->getThingCount() > 0) {
return false;
}
@@ -1153,7 +1162,7 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos)
}
bool Map::isWidgetAttached(const UIWidgetPtr& widget) const {
- return m_attachedObjectWidgetMap.find(widget) != m_attachedObjectWidgetMap.end();
+ return m_attachedObjectWidgetMap.contains(widget);
}
void Map::addAttachedWidgetToObject(const UIWidgetPtr& widget, const AttachableObjectPtr& object) {
diff --git a/src/client/map.h b/src/client/map.h
index e51255aaa8..5124438d50 100644
--- a/src/client/map.h
+++ b/src/client/map.h
@@ -155,7 +155,7 @@ class Map
void addMapView(const MapViewPtr& mapView);
void removeMapView(const MapViewPtr& mapView);
- MapViewPtr getMapView(size_t i) { return i < m_mapViews.size() ? m_mapViews[i] : nullptr; }
+ MapViewPtr getMapView(const size_t i) { return i < m_mapViews.size() ? m_mapViews[i] : nullptr; }
void notificateTileUpdate(const Position& pos, const ThingPtr& thing, Otc::Operation operation);
void notificateCameraMove(const Point& offset) const;
@@ -197,8 +197,8 @@ class Map
void setShowAnimations(bool show);
#endif
- void setWidth(uint16_t w) { m_width = w; }
- void setHeight(uint16_t h) { m_height = h; }
+ void setWidth(const uint16_t w) { m_width = w; }
+ void setHeight(const uint16_t h) { m_height = h; }
Size getSize() { return { m_width, m_height }; }
void clean();
@@ -245,17 +245,17 @@ class Map
void addCreature(const CreaturePtr& creature);
void removeCreatureById(uint32_t id);
- std::vector getSpectators(const Position& centerPos, bool multiFloor)
+ std::vector getSpectators(const Position& centerPos, const bool multiFloor)
{
return getSpectatorsInRangeEx(centerPos, multiFloor, m_awareRange.left, m_awareRange.right, m_awareRange.top, m_awareRange.bottom);
}
- std::vector getSightSpectators(const Position& centerPos, bool multiFloor)
+ std::vector getSightSpectators(const Position& centerPos, const bool multiFloor)
{
return getSpectatorsInRangeEx(centerPos, multiFloor, m_awareRange.left - 1, m_awareRange.right - 2, m_awareRange.top - 1, m_awareRange.bottom - 2);
}
- std::vector getSpectatorsInRange(const Position& centerPos, bool multiFloor, int32_t xRange, int32_t yRange)
+ std::vector getSpectatorsInRange(const Position& centerPos, const bool multiFloor, const int32_t xRange, const int32_t yRange)
{
return getSpectatorsInRangeEx(centerPos, multiFloor, xRange, xRange, yRange, yRange);
}
@@ -281,7 +281,7 @@ class Map
Position getCentralPosition() { return m_centralPosition; }
uint8_t getFirstAwareFloor() const;
uint8_t getLastAwareFloor() const;
- const std::vector& getFloorMissiles(uint8_t z) { return m_floors[z].missiles; }
+ const std::vector& getFloorMissiles(const uint8_t z) { return m_floors[z].missiles; }
std::vector getAnimatedTexts() { return m_animatedTexts; }
std::vector getStaticTexts() { return m_staticTexts; }
@@ -292,7 +292,7 @@ class Map
void findPathAsync(const Position& start, const Position& goal,
const std::function& callback);
- void setFloatingEffect(bool enable) { m_floatingEffect = enable; }
+ void setFloatingEffect(const bool enable) { m_floatingEffect = enable; }
bool isDrawingFloatingEffects() { return m_floatingEffect; }
#ifndef BOT_PROTECTION
diff --git a/src/client/mapview.cpp b/src/client/mapview.cpp
index 2e5f29c1ec..0c2c0916c7 100644
--- a/src/client/mapview.cpp
+++ b/src/client/mapview.cpp
@@ -23,6 +23,7 @@
#include "mapview.h"
#include "animatedtext.h"
+#include "client.h"
#include "creature.h"
#include "game.h"
#include "lightview.h"
@@ -30,17 +31,18 @@
#include "missile.h"
#include "statictext.h"
#include "tile.h"
-#include "client.h"
+#include "framework/graphics/texturemanager.h"
#include
#include
#include
#include
#include
-#include "framework/graphics/texturemanager.h"
#include
#include
+#include
+
MapView::MapView() : m_lightView(std::make_unique(Size())), m_pool(g_drawPool.get(DrawPoolType::MAP))
{
m_floors.resize(g_gameConfig.getMapMaxZ() + 1);
@@ -120,7 +122,7 @@ void MapView::drawFloor()
{
const auto& cameraPosition = m_posInfo.camera;
- uint32_t flags = Otc::DrawThings;
+ const uint32_t flags = Otc::DrawThings;
for (int_fast8_t z = m_floorMax; z >= m_floorMin; --z) {
const float fadeLevel = getFadeLevel(z);
@@ -315,20 +317,20 @@ void MapView::updateVisibleTiles()
if (!m_lastCameraPosition.isValid() || m_lastCameraPosition.z != m_posInfo.camera.z || m_lastCameraPosition.distance(m_posInfo.camera) >= 3) {
m_fadeType = FadeType::NONE$;
for (int iz = m_cachedLastVisibleFloor; iz >= cachedFirstVisibleFloor; --iz) {
- m_floors[iz].fadingTimers.restart(m_floorFading * 1000);
+ m_floors[iz].fadingTimers.restart(m_floorFading);
}
} else if (prevFirstVisibleFloor < m_cachedFirstVisibleFloor) { // hiding new floor
m_fadeType = FadeType::OUT$;
for (int iz = prevFirstVisibleFloor; iz < m_cachedFirstVisibleFloor; ++iz) {
- const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.elapsed_millis());
- m_floors[iz].fadingTimers.restart(shift * 1000);
+ const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.ticksElapsed());
+ m_floors[iz].fadingTimers.restart(shift);
}
} else if (prevFirstVisibleFloor > m_cachedFirstVisibleFloor) { // showing floor
m_fadeType = FadeType::IN$;
m_fadeFinish = false;
for (int iz = m_cachedFirstVisibleFloor; iz < prevFirstVisibleFloor; ++iz) {
- const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.elapsed_millis());
- m_floors[iz].fadingTimers.restart(shift * 1000);
+ const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.ticksElapsed());
+ m_floors[iz].fadingTimers.restart(shift);
}
}
@@ -450,16 +452,16 @@ void MapView::updateGeometry(const Size& visibleDimension)
m_lightView->resize(lightSize, tileSize);
}
- g_mainDispatcher.addEvent([this, bufferSize]() {
+ g_mainDispatcher.addEvent([this, bufferSize] {
m_pool->getFrameBuffer()->resize(bufferSize);
});
const uint8_t left = std::min(g_map.getAwareRange().left, (m_drawDimension.width() / 2) - 1);
const uint8_t top = std::min(g_map.getAwareRange().top, (m_drawDimension.height() / 2) - 1);
- const uint8_t right = static_cast(left + 1);
- const uint8_t bottom = static_cast(top + 1);
+ const auto right = static_cast(left + 1);
+ const auto bottom = static_cast(top + 1);
- m_posInfo.awareRange = { left, top, right, bottom };
+ m_posInfo.awareRange = { .left = left, .top = top, .right = right, .bottom = bottom };
updateViewportDirectionCache();
updateViewport();
@@ -536,7 +538,7 @@ void MapView::onMapCenterChange(const Position& /*newPos*/, const Position& /*ol
requestUpdateVisibleTiles();
}
-void MapView::lockFirstVisibleFloor(uint8_t firstVisibleFloor)
+void MapView::lockFirstVisibleFloor(const uint8_t firstVisibleFloor)
{
m_lockedFirstVisibleFloor = firstVisibleFloor;
requestUpdateVisibleTiles();
@@ -575,7 +577,7 @@ void MapView::setVisibleDimension(const Size& visibleDimension)
updateGeometry(visibleDimension);
}
-void MapView::setFloorViewMode(FloorViewMode floorViewMode)
+void MapView::setFloorViewMode(const FloorViewMode floorViewMode)
{
m_floorViewMode = floorViewMode;
@@ -587,7 +589,7 @@ void MapView::setAntiAliasingMode(const AntialiasingMode mode)
{
m_antiAliasingMode = mode;
- g_mainDispatcher.addEvent([=, this]() {
+ g_mainDispatcher.addEvent([=, this] {
m_pool->getFrameBuffer()->setSmooth(mode != ANTIALIASING_DISABLED);
});
@@ -612,7 +614,7 @@ void MapView::setCameraPosition(const Position& pos)
Position MapView::getPosition(const Point& mousePos)
{
- auto newMousePos = mousePos * g_window.getDisplayDensity();
+ const auto newMousePos = mousePos * g_window.getDisplayDensity();
if (!m_posInfo.rect.contains(newMousePos))
return {};
@@ -647,7 +649,7 @@ Position MapView::getPosition(const Point& point, const Size& mapSize)
return position;
}
-void MapView::move(int32_t x, int32_t y)
+void MapView::move(const int32_t x, const int32_t y)
{
m_moveOffset.x += x;
m_moveOffset.y += y;
@@ -693,7 +695,7 @@ Rect MapView::calcFramebufferSource(const Size& destSize)
return Rect(drawOffset, srcSize);
}
-uint8_t MapView::calcFirstVisibleFloor(bool checkLimitsFloorsView) const
+uint8_t MapView::calcFirstVisibleFloor(const bool checkLimitsFloorsView) const
{
uint8_t z = g_gameConfig.getMapSeaFloor();
// return forced first visible floor
@@ -792,7 +794,7 @@ TilePtr MapView::getTopTile(Position tilePos) const
return nullptr;
}
-void MapView::setShader(const std::string_view name, float fadein, float fadeout)
+void MapView::setShader(const std::string_view name, const float fadein, const float fadeout)
{
const auto& shader = g_shaders.getShader(name);
@@ -817,7 +819,7 @@ void MapView::setShader(const std::string_view name, float fadein, float fadeout
});
}
-void MapView::setDrawLights(bool enable)
+void MapView::setDrawLights(const bool enable)
{
m_drawingLight = enable;
@@ -877,12 +879,12 @@ void MapView::updateViewportDirectionCache()
}
Position MapView::getCameraPosition() { return isFollowingCreature() ? m_followingCreature->getPosition() : m_customCameraPosition; }
-std::vector MapView::getSightSpectators(bool multiFloor)
+std::vector MapView::getSightSpectators(const bool multiFloor)
{
return g_map.getSpectatorsInRangeEx(getCameraPosition(), multiFloor, m_posInfo.awareRange.left - 1, m_posInfo.awareRange.right - 2, m_posInfo.awareRange.top - 1, m_posInfo.awareRange.bottom - 2);
}
-std::vector MapView::getSpectators(bool multiFloor)
+std::vector MapView::getSpectators(const bool multiFloor)
{
return g_map.getSpectatorsInRangeEx(getCameraPosition(), multiFloor, m_posInfo.awareRange.left, m_posInfo.awareRange.right, m_posInfo.awareRange.top, m_posInfo.awareRange.bottom);
}
@@ -909,12 +911,12 @@ void MapView::destroyHighlightTile() {
void MapView::addForegroundTile(const TilePtr& tile) {
std::scoped_lock l(g_drawPool.get(DrawPoolType::FOREGROUND_MAP)->getMutex());
- if (std::find(m_foregroundTiles.begin(), m_foregroundTiles.end(), tile) == m_foregroundTiles.end())
+ if (std::ranges::find(m_foregroundTiles, tile) == m_foregroundTiles.end())
m_foregroundTiles.emplace_back(tile);
}
void MapView::removeForegroundTile(const TilePtr& tile) {
std::scoped_lock l(g_drawPool.get(DrawPoolType::FOREGROUND_MAP)->getMutex());
- const auto it = std::find(m_foregroundTiles.begin(), m_foregroundTiles.end(), tile);
+ const auto it = std::ranges::find(m_foregroundTiles, tile);
if (it == m_foregroundTiles.end())
return;
diff --git a/src/client/mapview.h b/src/client/mapview.h
index 8105e47248..123eecdc6b 100644
--- a/src/client/mapview.h
+++ b/src/client/mapview.h
@@ -22,11 +22,11 @@
#pragma once
+#include "lightview.h"
#include
#include
#include
#include
-#include "lightview.h"
struct AwareRange
{
@@ -50,12 +50,12 @@ struct MapPosInfo
float verticalStretchFactor;
float scaleFactor;
- bool isInRange(const Position& pos, bool ignoreZ = false) const
+ bool isInRange(const Position& pos, const bool ignoreZ = false) const
{
return camera.isInRange(pos, awareRange.left - 1, awareRange.right - 2, awareRange.top - 1, awareRange.bottom - 2, ignoreZ);
}
- bool isInRangeEx(const Position& pos, bool ignoreZ = false) const
+ bool isInRangeEx(const Position& pos, const bool ignoreZ = false) const
{
return camera.isInRange(pos, awareRange.left, awareRange.right, awareRange.top, awareRange.bottom, ignoreZ);
}
@@ -68,7 +68,7 @@ struct MapPosInfo
};
// @bindclass
-class MapView : public LuaObject
+class MapView final : public LuaObject
{
public:
enum FloorViewMode
@@ -118,30 +118,30 @@ class MapView : public LuaObject
Position getCameraPosition();
void setCameraPosition(const Position& pos);
- void setMinimumAmbientLight(float intensity) { m_minimumAmbientLight = intensity; updateLight(); }
+ void setMinimumAmbientLight(const float intensity) { m_minimumAmbientLight = intensity; updateLight(); }
float getMinimumAmbientLight() const { return m_minimumAmbientLight; }
- void setShadowFloorIntensity(float intensity) { m_shadowFloorIntensity = intensity; updateLight(); }
+ void setShadowFloorIntensity(const float intensity) { m_shadowFloorIntensity = intensity; updateLight(); }
float getShadowFloorIntensity() const { return m_shadowFloorIntensity; }
- void setDrawNames(bool enable) { m_drawNames = enable; }
+ void setDrawNames(const bool enable) { m_drawNames = enable; }
bool isDrawingNames() const { return m_drawNames; }
- void setDrawHealthBars(bool enable) { m_drawHealthBars = enable; }
+ void setDrawHealthBars(const bool enable) { m_drawHealthBars = enable; }
bool isDrawingHealthBars() const { return m_drawHealthBars; }
void setDrawLights(bool enable);
bool isDrawingLights() const { return m_drawingLight && m_lightView->isDark(); }
- void setLimitVisibleDimension(bool v) { m_limitVisibleDimension = v; }
+ void setLimitVisibleDimension(const bool v) { m_limitVisibleDimension = v; }
bool isLimitedVisibleDimension() const { return m_limitVisibleDimension; }
- void setDrawManaBar(bool enable) { m_drawManaBar = enable; }
+ void setDrawManaBar(const bool enable) { m_drawManaBar = enable; }
bool isDrawingManaBar() const { return m_drawManaBar; }
void move(int32_t x, int32_t y);
- void setShader(const std::string_view name, float fadein, float fadeout);
+ void setShader(std::string_view name, float fadein, float fadeout);
PainterShaderProgramPtr getShader() { return m_shader; }
Position getPosition(const Point& point, const Size& mapSize);
@@ -155,12 +155,12 @@ class MapView : public LuaObject
std::vector getSpectators(bool multiFloor = false);
std::vector getSightSpectators(bool multiFloor = false);
- bool isInRange(const Position& pos, bool ignoreZ = false)
+ bool isInRange(const Position& pos, const bool ignoreZ = false)
{
return getCameraPosition().isInRange(pos, m_posInfo.awareRange.left - 1, m_posInfo.awareRange.right - 2, m_posInfo.awareRange.top - 1, m_posInfo.awareRange.bottom - 2, ignoreZ);
}
- bool isInRangeEx(const Position& pos, bool ignoreZ = false)
+ bool isInRangeEx(const Position& pos, const bool ignoreZ = false)
{
return getCameraPosition().isInRange(pos, m_posInfo.awareRange.left, m_posInfo.awareRange.right, m_posInfo.awareRange.top, m_posInfo.awareRange.bottom, ignoreZ);
}
@@ -178,7 +178,7 @@ class MapView : public LuaObject
void setDrawHighlightTarget(const bool enable) { m_drawHighlightTarget = enable; }
- void setFloorFading(uint16_t value) { m_floorFading = value; }
+ void setFloorFading(const uint16_t value) { m_floorFading = value; }
PainterShaderProgramPtr getNextShader() { return m_nextShader; }
bool isSwitchingShader() { return !m_shaderSwitchDone; }
@@ -215,7 +215,7 @@ class MapView : public LuaObject
struct FloorData
{
MapObject cachedVisibleTiles;
- stdext::timer fadingTimers;
+ Timer fadingTimers;
};
struct Crosshair
@@ -247,11 +247,11 @@ class MapView : public LuaObject
bool canFloorFade() const { return m_floorViewMode == FADE && m_floorFading; }
- float getFadeLevel(uint8_t z) const
+ float getFadeLevel(const uint8_t z) const
{
if (!canFloorFade()) return 1.f;
- float fading = std::clamp(static_cast(m_floors[z].fadingTimers.elapsed_millis()) / static_cast