Merge pull request #1043 from ostermine/feat/hotbar-control

make hotbar size and layout configurable
This commit is contained in:
MihailRis 2026-10-18 11:38:10 +03:00 • committed by GitHub
commit bb73e3f354
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 188 additions and 20 deletions

27
dev/tests/hotbar.lua Normal file
View file

@ -0,0 +1,27 @@
local util = require "core:tests_util"
util.create_demo_world("core:default")
local pid = player.create("Xerxes")
local function selected_slot()
local _, slot = player.get_inventory(pid)
return slot
end
util.check_int(10, player.get_hotbar_size(pid), "default hotbar size")
player.set_selected_slot(pid, 12)
util.check_int(2, selected_slot(), "selected slot")
player.set_selected_slot(pid, 8)
player.set_hotbar_size(pid, 5)
util.check_int(5, player.get_hotbar_size(pid), "hotbar size")
util.check_int(4, selected_slot(), "clamped selected slot")
player.set_selected_slot(pid, 7)
util.check_int(2, selected_slot(), "selected slot")
player.set_hotbar_size(pid, 0)
util.check_int(1, player.get_hotbar_size(pid), "min hotbar size")
util.check_int(0, selected_slot(), "selected slot")

View file

@ -82,6 +82,12 @@ hud.is_player_inventory_open() -> boolean
-- Sets whether to allow pausing. If false, the pause menu will not pause the game. -- Sets whether to allow pausing. If false, the pause menu will not pause the game.
hud.set_allow_pause(flag: bool) hud.set_allow_pause(flag: bool)
-- Returns true if the hotbar is not hidden with hud.set_hotbar_visible.
hud.is_hotbar_visible() -> bool
-- Shows or hides the hotbar. Selecting a slot with the mouse wheel and number keys keeps working.
hud.set_hotbar_visible(flag: bool)
-- Function that controls the named skeleton 'hand' (see gfx.skeletons) -- Function that controls the named skeleton 'hand' (see gfx.skeletons)
hud.hand_controller: function() hud.hand_controller: function()
``` ```

View file

@ -142,7 +142,14 @@ Switches the player's camera. See [cameras](libcameras.md).
player.set_selected_slot(playerid: int, slotid: int) player.set_selected_slot(playerid: int, slotid: int)
``` ```
Sets the selected slot index Sets the selected slot index. The index wraps around the hotbar size.
```lua
player.get_hotbar_size(playerid: int) -> int
player.set_hotbar_size(playerid: int, size: int)
```
Hotbar size getter and setter: the number of first player inventory slots that can be selected. `player.set_selected_slot` wraps the index by it, and the selected slot is moved into the range when the size decreases. Default value is `hotbar-size` from `config/defaults.toml` (10); the value is not saved with the world. On the client these slots are shown in the hotbar and selected with the mouse wheel and number keys.
```lua ```lua
player.get_selected_block(playerid: int) -> x,y,z player.get_selected_block(playerid: int) -> x,y,z

View file

@ -218,6 +218,8 @@ Element is a container. Does not have specific attributes.
> [!WARNING] > [!WARNING]
> Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory) > Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory)
A pack can replace the player inventory screen and the hotbar with its own layouts using `inventory-layout` (`"core:inventory"` by default) and `hotbar-layout` in `config/defaults.toml`. The root element of such a layout must be `inventory`, it is bound to the player inventory. The hotbar layout is placed at the bottom center of the screen unless it has `position-func`.
## *slot* ## *slot*
Element must be a direct sub-element of *inventory*. Element must be a direct sub-element of *inventory*.

View file

@ -84,6 +84,12 @@ hud.is_player_inventory_open() -> boolean
-- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру. -- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру.
hud.set_allow_pause(flag: boolean) hud.set_allow_pause(flag: boolean)
-- Возвращает true, если хотбар не скрыт через hud.set_hotbar_visible.
hud.is_hotbar_visible() -> boolean
-- Показывает или скрывает хотбар. Выбор слота колесом мыши и цифровыми клавишами продолжает работать.
hud.set_hotbar_visible(flag: boolean)
-- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons) -- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons)
hud.hand_controller: function() hud.hand_controller: function()
``` ```

View file

@ -95,9 +95,17 @@ player.get_interaction_distance(playerid: int) -> number
-- Возвращает ID инвентаря и индекс выбранного слота -- Возвращает ID инвентаря и индекс выбранного слота
player.get_inventory(playerid: int) -> int, int player.get_inventory(playerid: int) -> int, int
-- Устанавливает выбранный слот -- Устанавливает выбранный слот (индекс берётся по модулю размера хотбара)
player.set_selected_slot(playerid: int, slotid: int) player.set_selected_slot(playerid: int, slotid: int)
-- Возвращает / устанавливает размер хотбара - число первых слотов инвентаря игрока,
-- доступных для выбора. player.set_selected_slot берёт индекс по модулю этого числа,
-- а при уменьшении размера выбранный слот сдвигается в допустимый диапазон.
-- По умолчанию - `hotbar-size` из `config/defaults.toml` (10), в мире не сохраняется.
-- На клиенте эти слоты показывает хотбар, они выбираются колесом мыши и цифровыми клавишами.
player.get_hotbar_size(playerid: int) -> int
player.set_hotbar_size(playerid: int, size: int)
-- Возвращает позицию выбранного блока -- Возвращает позицию выбранного блока
player.get_selected_block(playerid: int) -> x,y,z player.get_selected_block(playerid: int) -> x,y,z

View file

@ -219,6 +219,8 @@
> [!WARNING] > [!WARNING]
> Слоты без привязки к инвентарю не будут отображаться. Под привязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory) > Слоты без привязки к инвентарю не будут отображаться. Под привязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory)
Пак может заменить экран инвентаря игрока и хотбар своими макетами через ключи `inventory-layout` (по умолчанию `"core:inventory"`) и `hotbar-layout` в `config/defaults.toml`. Корневой элемент такого макета - `inventory`, он привязывается к инвентарю игрока. Макет хотбара ставится внизу по центру экрана, если у него нет `position-func`.
## Одиночный слот - *slot* ## Одиночный слот - *slot*
Элемент должен находиться внутри `inventory` элемента, без посредников. Элемент должен находиться внутри `inventory` элемента, без посредников.

View file

@ -1,2 +1,4 @@
generator = "core:default" generator = "core:default"
player-entity = "" player-entity = ""
hotbar-size = 10
inventory-layout = "core:inventory"

View file

@ -2,7 +2,9 @@ local M = {}
function M.share_default_func(invid, slotid) function M.share_default_func(invid, slotid)
local blockinv = hud.get_block_inventory() local blockinv = hud.get_block_inventory()
local playerinv = player.get_inventory(hud.get_player()) local pid = hud.get_player()
local playerinv = player.get_inventory(pid)
local hotbar_size = player.get_hotbar_size(pid)
if blockinv ~= 0 then if blockinv ~= 0 then
if invid == blockinv then if invid == blockinv then
inventory.move(blockinv, slotid, playerinv) inventory.move(blockinv, slotid, playerinv)
@ -11,10 +13,10 @@ function M.share_default_func(invid, slotid)
end end
elseif rules.get("allow-content-access") then elseif rules.get("allow-content-access") then
inventory.set(invid, slotid, 0, 0) inventory.set(invid, slotid, 0, 0)
elseif slotid < 10 then elseif slotid < hotbar_size then
inventory.move_range(invid, slotid, invid, 10) inventory.move_range(invid, slotid, invid, hotbar_size)
else else
inventory.move_range(invid, slotid, invid, 0, 9) inventory.move_range(invid, slotid, invid, 0, hotbar_size - 1)
end end
end end

View file

@ -43,7 +43,8 @@ function on_hud_open()
end end
local id = block.get_picking_item(block.get(x, y, z)) local id = block.get_picking_item(block.get(x, y, z))
local inv, cur_slot = player.get_inventory(pid) local inv, cur_slot = player.get_inventory(pid)
local slot = inventory.find_by_item(inv, id, 0, 9) local hotbar_size = player.get_hotbar_size(pid)
local slot = inventory.find_by_item(inv, id, 0, hotbar_size)
if slot then if slot then
player.set_selected_slot(pid, slot) player.set_selected_slot(pid, slot)
return return
@ -51,7 +52,7 @@ function on_hud_open()
if not rules.get("allow-content-access") then if not rules.get("allow-content-access") then
return return
end end
slot = inventory.find_by_item(inv, 0, 0, 9) slot = inventory.find_by_item(inv, 0, 0, hotbar_size)
if slot then if slot then
cur_slot = slot cur_slot = slot
end end

View file

@ -143,9 +143,11 @@ std::shared_ptr<InventoryView> Hud::createHotbar() {
auto inventory = player.getInventory(); auto inventory = player.getInventory();
auto& content = frontend.getLevel().content; auto& content = frontend.getLevel().content;
int size = player.getHotbarSize();
SlotLayout slotLayout(-1, glm::vec2(), false, false, nullptr, nullptr, nullptr); SlotLayout slotLayout(-1, glm::vec2(), false, false, nullptr, nullptr, nullptr);
InventoryBuilder builder(gui); InventoryBuilder builder(gui);
builder.addGrid(10, 10, glm::vec2(), glm::vec4(4), true, slotLayout); builder.addGrid(size, size, glm::vec2(), glm::vec4(4), true, slotLayout);
auto view = builder.build(); auto view = builder.build();
view->setId("hud.hotbar"); view->setId("hud.hotbar");
view->setOrigin(glm::vec2(view->getSize().x/2, 0)); view->setOrigin(glm::vec2(view->getSize().x/2, 0));
@ -177,7 +179,25 @@ Hud::Hud(Engine& engine, LevelFrontend& frontend, Player& player)
contentAccessPanel->setScrollable(true); contentAccessPanel->setScrollable(true);
contentAccessPanel->setId("hud.content-access-panel"); contentAccessPanel->setId("hud.content-access-panel");
hotbarView = createHotbar(); auto hotbarLayout =
frontend.getLevel().content.getDefaults()["hotbar-layout"].asString("");
if (hotbarLayout.empty()) {
hotbarView = createHotbar();
} else {
hotbarDocument = &assets.require<UiDocument>(hotbarLayout);
hotbarView =
std::dynamic_pointer_cast<InventoryView>(hotbarDocument->getRoot());
if (hotbarView == nullptr) {
throw std::runtime_error(
"hotbar UI root element must be 'inventory'"
);
}
hotbarView->bind(player.getInventory(), &frontend.getLevel().content);
hotbarView->setInteractive(false);
if (hotbarView->getPositionFunc() == nullptr) {
hotbarView->setOrigin(glm::vec2(hotbarView->getSize().x / 2, 0));
}
}
darkOverlay = guiutil::create( darkOverlay = guiutil::create(
gui, gui,
"<container size='4000' color='#00000080' z-index='-1' visible='false'/>" "<container size='4000' color='#00000080' z-index='-1' visible='false'/>"
@ -229,6 +249,7 @@ Hud::~Hud() {
for (auto& element : elements) { for (auto& element : elements) {
onRemove(element); onRemove(element);
} }
hotbarView->unbind();
gui.remove(hotbarView); gui.remove(hotbarView);
gui.remove(darkOverlay); gui.remove(darkOverlay);
gui.remove(inventoryDropArea); gui.remove(inventoryDropArea);
@ -263,12 +284,13 @@ void Hud::processInput(bool visible) {
} }
void Hud::updateHotbarControl() { void Hud::updateHotbarControl() {
int size = player.getHotbarSize();
int scroll = input.getScroll(); int scroll = input.getScroll();
if (!inventoryOpen && scroll) { if (!inventoryOpen && scroll) {
int slot = player.getChosenSlot(); int slot = player.getChosenSlot();
slot = (slot - scroll) % 10; slot = (slot - scroll) % size;
if (slot < 0) { if (slot < 0) {
slot += 10; slot += size;
} }
player.setChosenSlot(slot); player.setChosenSlot(slot);
} }
@ -277,11 +299,12 @@ void Hud::updateHotbarControl() {
i <= static_cast<int>(Keycode::NUM_9); i <= static_cast<int>(Keycode::NUM_9);
i++ i++
) { ) {
if (input.jpressed(static_cast<Keycode>(i))) { int slot = i - static_cast<int>(Keycode::NUM_1);
player.setChosenSlot(i - static_cast<int>(Keycode::NUM_1)); if (slot < size && input.jpressed(static_cast<Keycode>(i))) {
player.setChosenSlot(slot);
} }
} }
if (input.jpressed(Keycode::NUM_0)) { if (size > 9 && input.jpressed(Keycode::NUM_0)) {
player.setChosenSlot(9); player.setChosenSlot(9);
} }
} }
@ -375,7 +398,16 @@ void Hud::update(bool visible) {
contentAccessPanel->setVisible(inventoryView != nullptr && showContentPanel); contentAccessPanel->setVisible(inventoryView != nullptr && showContentPanel);
contentAccessPanel->setSize(glm::vec2(caSize.x, windowSize.y)); contentAccessPanel->setSize(glm::vec2(caSize.x, windowSize.y));
contentAccess->setMinSize(glm::vec2(1, windowSize.y)); contentAccess->setMinSize(glm::vec2(1, windowSize.y));
hotbarView->setVisible(visible && !(secondUI && !inventoryView)); if (hotbarDocument == nullptr &&
static_cast<int>(hotbarView->getSlotsCount()) !=
player.getHotbarSize()) {
gui.remove(hotbarView);
hotbarView = createHotbar();
gui.add(hotbarView);
}
hotbarView->setVisible(
visible && hotbarVisible && !(secondUI && !inventoryView)
);
darkOverlay->setVisible(isMenuOpen); darkOverlay->setVisible(isMenuOpen);
inventoryDropArea->setVisible(inventoryOpen); inventoryDropArea->setVisible(inventoryOpen);
menu.setVisible(isMenuOpen); menu.setVisible(isMenuOpen);
@ -404,8 +436,16 @@ void Hud::openInventory(bool playerInventory) {
if (playerInventory) { if (playerInventory) {
auto& content = frontend.getLevel().content; auto& content = frontend.getLevel().content;
auto inventory = player.getInventory(); auto inventory = player.getInventory();
auto inventoryDocument = assets.get<UiDocument>("core:inventory"); auto layout = content.getDefaults()["inventory-layout"].asString(
"core:inventory"
);
auto inventoryDocument = &assets.require<UiDocument>(layout);
inventoryView = std::dynamic_pointer_cast<InventoryView>(inventoryDocument->getRoot()); inventoryView = std::dynamic_pointer_cast<InventoryView>(inventoryDocument->getRoot());
if (inventoryView == nullptr) {
throw std::runtime_error(
"player inventory UI root element must be 'inventory'"
);
}
inventoryView->bind(inventory, &content); inventoryView->bind(inventory, &content);
add(HudElement(HudElementMode::INVENTORY, inventoryDocument, inventoryView, false)); add(HudElement(HudElementMode::INVENTORY, inventoryDocument, inventoryView, false));
} }
@ -700,7 +740,9 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) {
if (exchangeSlot != nullptr) { if (exchangeSlot != nullptr) {
exchangeSlot->setPos(input.getCursor().pos); exchangeSlot->setPos(input.getCursor().pos);
} }
hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); if (hotbarView->getPositionFunc() == nullptr) {
hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65));
}
hotbarView->setSelected(player.getChosenSlot()); hotbarView->setSelected(player.getChosenSlot());
} }
@ -790,6 +832,14 @@ void Hud::setAllowPause(bool flag) {
allowPause = flag; allowPause = flag;
} }
void Hud::setHotbarVisible(bool flag) {
hotbarVisible = flag;
}
bool Hud::isHotbarVisible() const {
return hotbarVisible;
}
bool Hud::isOpen(const std::string& layoutid) const { bool Hud::isOpen(const std::string& layoutid) const {
for (const auto& element : elements) { for (const auto& element : elements) {
auto doc = element.getDocument(); auto doc = element.getDocument();

View file

@ -89,6 +89,10 @@ class Hud : public util::ObjectsKeeper {
std::shared_ptr<gui::InventoryView> contentAccess; std::shared_ptr<gui::InventoryView> contentAccess;
/// @brief Player inventory hotbar /// @brief Player inventory hotbar
std::shared_ptr<gui::InventoryView> hotbarView; std::shared_ptr<gui::InventoryView> hotbarView;
/// @brief Hotbar layout set by 'hotbar-layout', nullptr for built-in
UiDocument* hotbarDocument = nullptr;
/// @brief Hotbar is not hidden by scripts
bool hotbarVisible = true;
/// @brief Debug info and control panel (F3 key) /// @brief Debug info and control panel (F3 key)
std::shared_ptr<gui::UINode> debugPanel; std::shared_ptr<gui::UINode> debugPanel;
/// @brief Overlay used in pause mode /// @brief Overlay used in pause mode
@ -219,6 +223,10 @@ public:
void setAllowPause(bool flag); void setAllowPause(bool flag);
void setHotbarVisible(bool flag);
bool isHotbarVisible() const;
bool isOpen(const std::string& layoutid) const; bool isOpen(const std::string& layoutid) const;
static bool showGeneratorMinimap; static bool showGeneratorMinimap;

View file

@ -194,6 +194,15 @@ static int l_set_allow_pause(lua::State* L) {
return 0; return 0;
} }
static int l_is_hotbar_visible(lua::State* L) {
return lua::pushboolean(L, hud->isHotbarVisible());
}
static int l_set_hotbar_visible(lua::State* L) {
hud->setHotbarVisible(lua::toboolean(L, 1));
return 0;
}
static int l_reload_script(lua::State* L) { static int l_reload_script(lua::State* L) {
auto packid = lua::require_string(L, 1); auto packid = lua::require_string(L, 1);
if (content == nullptr) { if (content == nullptr) {
@ -237,6 +246,8 @@ const luaL_Reg hudlib[] = {
{"_set_content_access", wrap_hud<l_set_content_access>}, {"_set_content_access", wrap_hud<l_set_content_access>},
{"_set_debug_cheats", wrap_hud<l_set_debug_cheats>}, {"_set_debug_cheats", wrap_hud<l_set_debug_cheats>},
{"set_allow_pause", wrap_hud<l_set_allow_pause>}, {"set_allow_pause", wrap_hud<l_set_allow_pause>},
{"is_hotbar_visible", wrap_hud<l_is_hotbar_visible>},
{"set_hotbar_visible", wrap_hud<l_set_hotbar_visible>},
{"reload_script", wrap_hud<l_reload_script>}, {"reload_script", wrap_hud<l_reload_script>},
{"is_open", wrap_hud<l_is_open>}, {"is_open", wrap_hud<l_is_open>},
{nullptr, nullptr} {nullptr, nullptr}

View file

@ -121,7 +121,21 @@ static int l_get_inv(lua::State* L) {
static int l_set_selected_slot(lua::State* L) { static int l_set_selected_slot(lua::State* L) {
if (auto player = get_player(L, 1)) { if (auto player = get_player(L, 1)) {
player->setChosenSlot(lua::tointeger(L, 2) % 10); player->setChosenSlot(lua::tointeger(L, 2) % player->getHotbarSize());
}
return 0;
}
static int l_get_hotbar_size(lua::State* L) {
if (auto player = get_player(L, 1)) {
return lua::pushinteger(L, player->getHotbarSize());
}
return 0;
}
static int l_set_hotbar_size(lua::State* L) {
if (auto player = get_player(L, 1)) {
player->setHotbarSize(lua::tointeger(L, 2));
} }
return 0; return 0;
} }
@ -401,6 +415,8 @@ const luaL_Reg playerlib[] = {
{"get_interaction_distance", lua::wrap<l_get_interaction_distance>}, {"get_interaction_distance", lua::wrap<l_get_interaction_distance>},
{"set_interaction_distance", lua::wrap<l_set_interaction_distance>}, {"set_interaction_distance", lua::wrap<l_set_interaction_distance>},
{"set_selected_slot", lua::wrap<l_set_selected_slot>}, {"set_selected_slot", lua::wrap<l_set_selected_slot>},
{"get_hotbar_size", lua::wrap<l_get_hotbar_size>},
{"set_hotbar_size", lua::wrap<l_set_hotbar_size>},
{"get_selected_block", lua::wrap<l_get_selected_block>}, {"get_selected_block", lua::wrap<l_get_selected_block>},
{"get_selected_entity", lua::wrap<l_get_selected_entity>}, {"get_selected_entity", lua::wrap<l_get_selected_entity>},
{"set_spawnpoint", lua::wrap<l_set_spawnpoint>}, {"set_spawnpoint", lua::wrap<l_set_spawnpoint>},

View file

@ -41,6 +41,12 @@ Player::Player(
name(name), name(name),
speed(speed), speed(speed),
chosenSlot(0), chosenSlot(0),
hotbarSize(glm::max(
1,
static_cast<int>(
level.content.getDefaults()["hotbar-size"].asInteger(10)
)
)),
position(position), position(position),
inventory(std::move(inv)), inventory(std::move(inv)),
eid(eid), eid(eid),
@ -153,13 +159,22 @@ void Player::attemptToChooseSpawnpoint() {
} }
void Player::setChosenSlot(int index) { void Player::setChosenSlot(int index) {
chosenSlot = index; chosenSlot = glm::clamp(index, 0, hotbarSize - 1);
} }
int Player::getChosenSlot() const { int Player::getChosenSlot() const {
return chosenSlot; return chosenSlot;
} }
void Player::setHotbarSize(int size) {
hotbarSize = glm::max(1, size);
setChosenSlot(chosenSlot);
}
int Player::getHotbarSize() const {
return hotbarSize;
}
float Player::getSpeed() const { float Player::getSpeed() const {
return speed; return speed;
} }

View file

@ -49,6 +49,7 @@ class Player : public Serializable {
float speed; float speed;
int chosenSlot; int chosenSlot;
int hotbarSize;
glm::vec3 position; glm::vec3 position;
glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")};
std::shared_ptr<Inventory> inventory; std::shared_ptr<Inventory> inventory;
@ -96,6 +97,10 @@ public:
int getChosenSlot() const; int getChosenSlot() const;
void setHotbarSize(int size);
int getHotbarSize() const;
float getSpeed() const; float getSpeed() const;
bool isSuspended() const; bool isSuspended() const;