Files
bilicraft-bot/src/ActionExecutor.cpp
T

728 lines
32 KiB
C++

#include "ActionExecutor.h"
#include "ActionFile.h"
#include "BilicraftClient.h"
#include "BucketAim.h"
#include "EntityInteraction.h"
#include <chrono>
#include <cmath>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "botcraft/AI/Tasks/DigTask.hpp"
#include "botcraft/AI/Tasks/InventoryTasks.hpp"
#include "botcraft/AI/Tasks/PathfindingTask.hpp"
#include "botcraft/Game/AssetsManager.hpp"
#include "botcraft/Game/Entities/LocalPlayer.hpp"
#include "botcraft/Game/Entities/EntityManager.hpp"
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
#include "botcraft/Game/Inventory/InventoryManager.hpp"
#include "botcraft/Game/Inventory/Window.hpp"
#include "botcraft/Game/World/Blockstate.hpp"
#include "botcraft/Game/World/World.hpp"
#include "botcraft/Network/NetworkManager.hpp"
#include "botcraft/Utilities/Logger.hpp"
namespace Bilicraft
{
namespace
{
using Botcraft::Status;
using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals;
void Require(bool condition, const std::string &message)
{
if (!condition)
throw std::runtime_error(message);
}
void CheckConnection(BilicraftClient &client)
{
Require(!client.WasDisconnected(), "disconnected while executing action");
Require(client.HasEnteredPlay() && client.GetNetworkManager() &&
client.GetNetworkManager()->GetConnectionState() == ProtocolCraft::ConnectionState::Play,
"client is not in Play state");
}
template <typename Predicate>
void Await(BilicraftClient &client, Predicate ready, std::chrono::milliseconds timeout, const char *description)
{
const auto deadline = Clock::now() + timeout;
while (!ready())
{
CheckConnection(client);
Require(Clock::now() < deadline, std::string("timeout waiting for ") + description);
client.Yield();
}
CheckConnection(client);
}
void WaitForManagers(BilicraftClient &client)
{
Await(client,
[&] {
if (!client.GetWorld() || !client.GetLocalPlayer() || !client.GetPhysicsManager() ||
!client.GetInventoryManager() || !client.GetInventoryManager()->GetPlayerInventory())
return false;
// Botcraft initializes local Y to NaN until PlayerPosition is
// processed under the player's mutex. Non-null managers alone
// are not sufficient to begin pathfinding or block interaction.
const auto position = client.GetLocalPlayer()->GetPosition();
return std::isfinite(position.x) && std::isfinite(position.y) && std::isfinite(position.z);
},
10s, "world/player/physics/inventory managers and spawn position");
}
struct SneakContext
{
BilicraftClient *client;
std::shared_ptr<Botcraft::LocalPlayer> player;
};
thread_local SneakContext *activeSneak = nullptr;
void SendSneak(const std::shared_ptr<Botcraft::NetworkManager> &network, bool sneak)
{
// Since 1.21.6 shift is sent via PlayerInput, not PlayerCommand. Send
// explicitly as well as setting the input so the immediately following
// UseItemOn cannot overtake the physics tick that presses shift. Actions
// are sequential and stationary here; all movement keys remain released.
auto packet = std::make_shared<ProtocolCraft::ServerboundPlayerInputPacket>();
packet->SetShift(sneak);
network->Send(packet);
}
class ScopedSneak
{
public:
ScopedSneak(BilicraftClient &client, bool enabled)
: context{&client, client.GetLocalPlayer()}, network(client.GetNetworkManager()), enabled(enabled)
{
Require(!enabled || activeSneak == nullptr, "nested shifted actions are unsupported");
if (!enabled)
return;
// .act owns the inputs exclusively and has no persistent sneak mode.
// Do not snapshot delayed server metadata: it can still say 'sneaking'
// from the previous command and accidentally latch shift after this one.
// Publish the thread-local context only after initialization succeeds;
// constructor failure must leave no dangling pointer.
try
{
context.player->SetInputsSneak(true);
SendSneak(network, true);
activeSneak = &context;
}
catch (...)
{
Restore();
throw;
}
}
~ScopedSneak() noexcept
{
if (enabled)
{
activeSneak = nullptr;
Restore();
}
}
ScopedSneak(const ScopedSneak &) = delete;
ScopedSneak &operator=(const ScopedSneak &) = delete;
private:
void Restore() noexcept
{
// Never yield in an unwinding destructor. Captured shared_ptrs remain
// valid even if connection teardown has begun.
try
{
context.player->SetInputsSneak(false);
if (network && network->GetConnectionState() == ProtocolCraft::ConnectionState::Play)
SendSneak(network, false);
}
catch (...)
{
// Best effort only: a dead connection cannot accept a release.
}
}
SneakContext context;
std::shared_ptr<Botcraft::NetworkManager> network;
bool enabled;
};
Botcraft::Vector3<double> BlockCenter(const ActionCommand &command)
{
return Botcraft::Vector3<double>(command.x + 0.5, command.y + 0.5, command.z + 0.5);
}
const Botcraft::Blockstate &CheckTarget(BilicraftClient &client, const ActionCommand &command)
{
const Botcraft::Position pos(command.x, command.y, command.z);
Await(client, [&] { return client.GetWorld()->GetBlock(pos) != nullptr; }, 5s, "target chunk to load");
const auto *block = client.GetWorld()->GetBlock(pos);
Require(block && !block->IsAir(), "target is air or is no longer loaded");
const auto player = client.GetLocalPlayer();
const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0.0, player->GetEyeHeight(), 0.0);
const double range = player->GetAttributePlayerBlockInteractionRangeValue();
// Conservative center test: no hidden automatic navigation, including at
// reach boundaries. This does not claim to implement server line of sight.
Require(range > 0 && eyes.SqrDist(BlockCenter(command)) < range * range,
"target is outside block interaction reach; use goto explicitly");
return *block;
}
void Swing(BilicraftClient &client)
{
auto packet = std::make_shared<ProtocolCraft::ServerboundSwingPacket>();
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
client.GetNetworkManager()->Send(packet);
}
bool IsWaterSource(const Botcraft::Blockstate &block)
{
return block.GetName() == "minecraft:water" && block.GetVariableValue("level") == "0";
}
bool HoldsEmptyBucket(const ProtocolCraft::Slot &hand)
{
static const auto bucket = Botcraft::AssetsManager::getInstance().GetItemID("minecraft:bucket");
return !hand.IsEmptySlot() && hand.GetItemId() == bucket;
}
std::string DescribeBlock(const Botcraft::Blockstate *block)
{
if (!block) return "unloaded";
std::string description = block->GetName();
for (const auto &[key, value] : block->GetVariables())
description += " " + key + "=" + value;
return description;
}
Status ClickBlock(BilicraftClient &client, const ActionCommand &command)
{
CheckTarget(client, command);
if (Botcraft::LookAt(client, BlockCenter(command), true, true) != Status::Success)
return Status::Failure;
const auto &block = CheckTarget(client, command); // The world/player may have changed during Yield.
ScopedSneak sneak(client, command.shift);
const Botcraft::Position pos(command.x, command.y, command.z);
if (command.kind == ActionKind::LeftClick)
{
if (command.destroy)
return Botcraft::Dig(client, pos, true, Botcraft::PlayerDiggingFace::Up, false);
// Never send StartDigging: creative and instant-break blocks could be
// destroyed by that packet alone, even if immediately cancelled.
Swing(client);
return Status::Success;
}
const auto player = client.GetLocalPlayer();
const auto inventory = client.GetInventoryManager();
const auto window = inventory->GetPlayerInventory();
const auto slot = Botcraft::Window::INVENTORY_HOTBAR_START + inventory->GetIndexHotbarSelected();
const auto hand = window->GetSlot(slot);
const bool emptyBucket = HoldsEmptyBucket(hand);
const bool pickup = emptyBucket && (block.IsWaterlogged() || IsWaterSource(block));
const int waterBucketsBefore = pickup ? CountWaterBuckets(*window) : 0;
const auto world = client.GetWorld();
if (pickup)
{
const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0, player->GetEyeHeight(), 0);
const auto aim = FindBucketAim(*world, eyes, pos, player->GetAttributePlayerBlockInteractionRangeValue());
Require(aim.has_value(), "no visible point for bucket pickup at (" + std::to_string(pos.x) + "," +
std::to_string(pos.y) + "," + std::to_string(pos.z) + "); change standing position");
if (Botcraft::LookAt(client, *aim, true, true) != Status::Success) return Status::Failure;
Require(&CheckTarget(client, command) == &block && inventory->GetIndexHotbarSelected() ==
slot - Botcraft::Window::INVENTORY_HOTBAR_START && HoldsEmptyBucket(window->GetSlot(slot)),
"target or main hand changed while aiming for bucket pickup");
}
const auto yaw = player->GetYaw();
const auto pitch = player->GetPitch();
auto packet = MakeBlockRightClickPacket(command, block, hand, yaw, pitch, world->GetNextWorldInteractionSequenceId());
if (emptyBucket || block.IsWaterlogged() || IsWaterSource(block))
{
const auto *item = hand.IsEmptySlot() ? nullptr : Botcraft::AssetsManager::getInstance().GetItem(hand.GetItemId());
LOG_INFO("rclick (" << pos.x << "," << pos.y << "," << pos.z << ") " << DescribeBlock(&block)
<< "; main hand=" << (hand.IsEmptySlot() ? "empty" :
(item ? item->GetName() : std::to_string(hand.GetItemId())))
<< "; " << (pickup ? "bucket pickup" : "block interaction"));
}
client.GetNetworkManager()->Send(packet);
Swing(client);
if (pickup)
{
try
{
Await(client, [&] {
Require(client.GetWorld() == world && inventory->GetPlayerInventory() == window,
"world or inventory changed during bucket pickup");
if (CountWaterBuckets(*window) > waterBucketsBefore) return true;
// Creative may keep an empty bucket even after successfully draining a block.
const auto *now = world->GetBlock(pos);
return player->GetInstabuild() && now && !now->IsWaterlogged() && !IsWaterSource(*now);
}, 5s, "server confirmation of bucket pickup (not retried)");
}
catch (const std::exception &error)
{
throw std::runtime_error(std::string(error.what()) + "; target=(" + std::to_string(pos.x) + "," +
std::to_string(pos.y) + "," + std::to_string(pos.z) + ") " + DescribeBlock(world->GetBlock(pos)) +
"; water buckets before=" + std::to_string(waterBucketsBefore) +
", now=" + std::to_string(CountWaterBuckets(*window)));
}
}
return Status::Success;
}
Status ClickItemFrame(BilicraftClient &client, const ActionCommand &command)
{
Await(client, [&] { return client.GetEntityManager() != nullptr; }, 5s, "entity manager");
const auto manager = client.GetEntityManager();
std::shared_ptr<Botcraft::ItemFrameEntity> frame;
try
{
Await(client, [&] { frame = FindItemFrame(*manager, command); return frame != nullptr; },
5s, "a unique item frame on the requested block face(s)");
}
catch (const std::exception &error)
{
throw std::runtime_error(std::string(error.what()) + "; " + DescribeItemFrameTargets(*manager, command));
}
const auto id = frame->GetEntityID();
const auto uuid = frame->GetUUID();
const auto sameFrame = [&] {
return manager->GetEntity(id) == frame && frame->GetUUID() == uuid;
};
const auto checkTarget = [&] {
CheckConnection(client);
Require(client.GetEntityManager() == manager, "entity manager changed during frame interaction");
Require(sameFrame(), "item frame disappeared or was replaced (not retried)");
Require(MatchesItemFrame(*frame, command), "item frame moved or changed its attached face");
// Recheck uniqueness after LookAt/Yield, not just when first selected.
Require(FindItemFrame(*manager, command) == frame, "item frame selection changed");
const auto player = client.GetLocalPlayer();
const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0, player->GetEyeHeight(), 0);
const double range = player->GetAttributeEntityInteractionRangeValue();
const auto center = ItemFrameCenter(*frame);
Require(std::isfinite(range) && range > 0 && eyes.SqrDist(center) < range * range,
"item frame is outside entity interaction reach; use goto explicitly");
};
checkTarget();
if (Botcraft::LookAt(client, ItemFrameCenter(*frame), true, true) != Status::Success)
return Status::Failure;
checkTarget();
ScopedSneak sneak(client, command.shift);
if (command.kind == ActionKind::RightClick)
{
client.GetNetworkManager()->Send(MakeEntityInteractionPacket(id, false, command.shift));
Swing(client);
return Status::Success; // Like block right click: sent once, no generic server acknowledgement.
}
const auto plan = [&] {
const auto player = client.GetLocalPlayer();
return PlanFrameAttack(command.destroy, !frame->GetDataItem().IsEmptySlot(),
player->GetInstabuild() || player->GetGameMode() == Botcraft::GameType::Creative);
};
const auto intent = plan();
if (intent == FrameAttackIntent::None)
{
Swing(client); // Known-empty frame: keep it, and never send Attack.
return Status::Success;
}
const auto attack = [&](FrameAttackIntent expected) {
checkTarget();
const auto player = client.GetLocalPlayer();
ValidateFrameAttack(expected, command.destroy, !frame->GetDataItem().IsEmptySlot(),
player->GetInstabuild() || player->GetGameMode() == Botcraft::GameType::Creative);
client.GetNetworkManager()->Send(MakeEntityInteractionPacket(id, true, command.shift));
Swing(client);
};
if (intent == FrameAttackIntent::TakeItem)
{
// Abort a changed plan before sending, rather than treating a removal
// attack as a successful take-item phase and sending a duplicate attack.
attack(FrameAttackIntent::TakeItem);
Await(client, [&] {
Require(client.GetEntityManager() == manager, "entity manager changed while taking frame item");
if (!sameFrame())
{
Require(command.destroy, "item frame was removed/replaced while taking its item (not retried)");
return true;
}
return frame->GetDataItem().IsEmptySlot();
}, 5s, "frame item removal (not retried)");
if (!command.destroy || !sameFrame()) return Status::Success;
// A second attack is a distinct, explicitly requested removal phase,
// not a retry. Never attack a newly inserted item or a replacement frame.
checkTarget();
Require(frame->GetDataItem().IsEmptySlot(), "frame was refilled before removal; not attacking again");
}
attack(FrameAttackIntent::RemoveFrame);
Await(client, [&] {
Require(client.GetEntityManager() == manager, "entity manager changed while removing frame");
return !sameFrame();
}, 5s, "item frame removal (not retried)");
return Status::Success;
}
Status ClickGui(BilicraftClient &client, const ActionCommand &command)
{
const auto inventory = client.GetInventoryManager();
Await(client, [&] { return inventory->GetFirstOpenedWindowId() > 0; }, 5s, "an open container GUI");
const short id = inventory->GetFirstOpenedWindowId();
const auto window = inventory->GetWindow(id);
Require(window != nullptr, "container closed before GUI click");
const short slot = ActionGuiSlot(window->GetType(), command.row, command.col);
Await(client, [&] { return window->GetSlots().contains(slot); }, 5s, "container contents");
Require(inventory->GetFirstOpenedWindowId() == id && inventory->GetWindow(id) == window,
"container changed before GUI click");
return Botcraft::ClickSlotInContainer(client, id, slot, 0, command.kind == ActionKind::GuiRightClick ? 1 : 0);
}
std::vector<unsigned char> SlotBytes(const ProtocolCraft::Slot &slot)
{
std::vector<unsigned char> bytes;
slot.Write(bytes);
return bytes;
}
std::string SlotDescription(const ProtocolCraft::Slot &slot)
{
return slot.IsEmptySlot() ? "empty" : "item=" + std::to_string(slot.GetItemId()) +
",count=" + std::to_string(slot.GetItemCount());
}
std::string WindowSlotDescription(const Botcraft::Window &window, short index)
{
const auto slots = window.GetSlots();
const auto found = slots.find(index);
return std::to_string(index) + "=" + (found == slots.end() ? "missing" : SlotDescription(found->second));
}
Status SwapBackpack(BilicraftClient &client, const ActionCommand &command)
{
const short from = ActionBackpackSlot(command.row, command.col);
const short hotbar = ActionHotbarIndex(command.slot);
const short to = Botcraft::Window::INVENTORY_HOTBAR_START + hotbar;
const auto inventory = client.GetInventoryManager();
Require(inventory->GetFirstOpenedWindowId() < 0, "swb requires all container GUIs to be closed");
Require(inventory->GetCursor().IsEmptySlot(), "swb requires an empty cursor");
const auto window = inventory->GetPlayerInventory();
Await(client,
[&] {
const auto slots = window->GetSlots();
return slots.contains(from) && slots.contains(to);
},
5s, "player inventory contents");
Require(inventory->GetFirstOpenedWindowId() < 0, "a GUI opened while waiting for player inventory");
Require(inventory->GetCursor().IsEmptySlot(), "cursor changed while waiting for player inventory");
const auto before = window->GetSlots();
Require(before.contains(from) && before.contains(to), "inventory reset before swb");
const auto first = SlotBytes(before.at(from));
const auto second = SlotBytes(before.at(to));
if (first == second)
return Status::Success;
// Upstream's three-click SwapItemsInContainer merges equal item stacks,
// and its InventoryManager rejects click type 2. Send a real number-key
// SWAP instead, with no optimistic local mutation. An intentionally stale
// state id requests a full authoritative resync after the server action.
client.GetNetworkManager()->Send(MakeBackpackSwapPacket(command.row, command.col, command.slot));
try
{
Await(client,
[&] {
Require(inventory->GetFirstOpenedWindowId() < 0, "a GUI opened during swb");
Require(inventory->GetCursor().IsEmptySlot(), "cursor changed during swb");
Require(inventory->GetPlayerInventory() == window, "inventory replaced during swb");
const auto current = window->GetSlots();
Require(current.contains(from) && current.contains(to), "inventory reset during swb");
return SlotBytes(current.at(from)) == second && SlotBytes(current.at(to)) == first;
},
5s, "server confirmation of backpack/hotbar swap (not retried)");
}
catch (const std::exception &error)
{
throw std::runtime_error(std::string(error.what()) + "; before: " + SlotDescription(before.at(from)) +
" <-> " + SlotDescription(before.at(to)) + "; now: " +
WindowSlotDescription(*window, from) + ", " + WindowSlotDescription(*window, to));
}
return Status::Success;
}
Status DropHotbar(BilicraftClient &client, const ActionCommand &command)
{
const auto inventory = client.GetInventoryManager();
const short hotbarSlot = ActionDropSlot(command.slot, inventory->GetIndexHotbarSelected());
const short slot = Botcraft::Window::INVENTORY_HOTBAR_START + ActionHotbarIndex(hotbarSlot);
const auto window = inventory->GetPlayerInventory();
const auto checkInventory = [&] {
Require(inventory->GetFirstOpenedWindowId() < 0, "drop requires all container GUIs to be closed");
Require(inventory->GetCursor().IsEmptySlot(), "drop requires an empty cursor");
Require(inventory->GetPlayerInventory() == window, "player inventory changed during drop");
};
checkInventory();
Await(client, [&] { return window->GetSlots().contains(slot); }, 5s, "hotbar contents before drop");
checkInventory();
const auto before = ReadDropSlot(*window, slot);
if (before.IsEmptySlot())
return Status::Success; // Empty slots are harmless no-ops; do not send THROW.
const auto expected = RemainingAfterDrop(before, command.all);
const auto expectedBytes = SlotBytes(expected);
// A single mode-4 THROW avoids picking the stack onto the cursor, repeated
// outside clicks, or temporarily selecting a different item. Like swb, use
// server resync rather than optimistic local mutations. Never retry a drop:
// a lost/delayed update must not cause extra items to be discarded.
client.GetNetworkManager()->Send(MakeHotbarDropPacket(hotbarSlot, command.all));
try
{
Await(client,
[&] {
checkInventory();
const auto actual = ReadDropSlot(*window, slot);
return expected.IsEmptySlot() ? actual.IsEmptySlot() : SlotBytes(actual) == expectedBytes;
},
5s, "server confirmation of drop (not retried)");
}
catch (const std::exception &error)
{
throw std::runtime_error(std::string(error.what()) + "; before: " + SlotDescription(before) +
"; expected: " + SlotDescription(expected) + "; now: " +
WindowSlotDescription(*window, slot));
}
return Status::Success;
}
} // namespace
int CountWaterBuckets(const Botcraft::Window &window)
{
static const auto waterBucket = Botcraft::AssetsManager::getInstance().GetItemID("minecraft:water_bucket");
int count = 0;
const auto slots = window.GetLockedSlots();
for (const auto &[index, stack] : *slots)
if (index >= Botcraft::Window::INVENTORY_STORAGE_START && index <= Botcraft::Window::INVENTORY_OFFHAND_INDEX &&
!stack.IsEmptySlot() && stack.GetItemId() == waterBucket)
count += stack.GetItemCount();
return count;
}
std::shared_ptr<ProtocolCraft::Packet> MakeBlockRightClickPacket(const ActionCommand &command,
const Botcraft::Blockstate &block, const ProtocolCraft::Slot &mainHand, float yaw, float pitch, int sequence)
{
if ((block.IsWaterlogged() || IsWaterSource(block)) && HoldsEmptyBucket(mainHand))
{
// The server raycasts from the player's eyes along this rotation.
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemPacket>();
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
packet->SetSequence(sequence);
packet->SetYRot(yaw);
packet->SetXRot(pitch);
return packet;
}
const Botcraft::Position pos(command.x, command.y, command.z);
// InteractWithBlock unconditionally pathfinds when its own range check
// fails. Use its verified packet layout directly to guarantee no movement.
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemOnPacket>();
packet->SetLocation(pos.ToNetworkPosition());
packet->SetDirection(static_cast<int>(Botcraft::PlayerDiggingFace::Up));
packet->SetCursorPositionX(0.5f);
packet->SetCursorPositionY(1.0f);
packet->SetCursorPositionZ(0.5f);
packet->SetInside(false);
packet->SetWorldBorderHit(false);
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
packet->SetSequence(sequence);
return packet;
}
void ValidateActionPosition(int x, int y, int z)
{
// NetworkPosition packs signed 26/12/26-bit coordinates. Restrict X/Z to
// the vanilla world boundary too, preventing pathfinding arithmetic on
// arbitrary int-range user input. Dimension-specific Y limits vary.
Require(x >= -29999984 && x <= 29999984 && z >= -29999984 && z <= 29999984 &&
y >= -2048 && y <= 2047,
"coordinates exceed supported Minecraft world/protocol bounds");
}
FrameAttackIntent PlanFrameAttack(bool destroy, bool hasItem, bool creative)
{
if (!destroy && !hasItem) return FrameAttackIntent::None;
Require(destroy || !creative, "item-only frame left click is unsafe in creative/instabuild mode; use destory explicitly to remove the frame");
return hasItem ? FrameAttackIntent::TakeItem : FrameAttackIntent::RemoveFrame;
}
void ValidateFrameAttack(FrameAttackIntent expected, bool destroy, bool hasItem, bool creative)
{
Require(expected != FrameAttackIntent::None && PlanFrameAttack(destroy, hasItem, creative) == expected,
"frame contents or game mode changed before attack; not sending/retrying");
}
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col)
{
int rows = 0;
switch (type)
{
case Botcraft::InventoryType::Generic9x1: rows = 1; break;
case Botcraft::InventoryType::Generic9x2: rows = 2; break;
case Botcraft::InventoryType::Generic9x3: rows = 3; break;
case Botcraft::InventoryType::Generic9x4: rows = 4; break;
case Botcraft::InventoryType::Generic9x5: rows = 5; break;
case Botcraft::InventoryType::Generic9x6: rows = 6; break;
case Botcraft::InventoryType::ShulkerBox: rows = 3; break;
default: throw std::runtime_error("GUI type is unsupported: only generic 9-column containers and shulker boxes are supported");
}
Require(row >= 1 && row <= rows && col >= 1 && col <= 9, "GUI row/column is outside the container area");
return static_cast<short>((row - 1) * 9 + col - 1);
}
short ActionBackpackSlot(int row, int col)
{
Require(row >= 1 && row <= 3 && col >= 1 && col <= 9, "backpack requires row 1..3 and column 1..9");
return static_cast<short>(Botcraft::Window::INVENTORY_STORAGE_START + (row - 1) * 9 + col - 1);
}
short ActionHotbarIndex(int slot)
{
Require(slot >= 1 && slot <= 9, "hotbar slot must be in 1..9");
return static_cast<short>(slot - 1);
}
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeBackpackSwapPacket(int row, int col, int slot)
{
const short from = ActionBackpackSlot(row, col);
const short hotbar = ActionHotbarIndex(slot);
auto packet = std::make_shared<ProtocolCraft::ServerboundContainerClickPacket>();
packet->SetContainerId(Botcraft::Window::PLAYER_INVENTORY_INDEX);
packet->SetStateId(-1);
packet->SetSlotNum(from);
packet->SetButtonNum(static_cast<char>(hotbar));
packet->SetClickType(2);
packet->SetChangedSlots({});
packet->SetCarriedItem(ProtocolCraft::HashedSlot(ProtocolCraft::Slot()));
return packet;
}
short ActionDropSlot(int requestedSlot, int selectedHotbarIndex)
{
if (requestedSlot == 0)
{
Require(selectedHotbarIndex >= 0 && selectedHotbarIndex < 9, "invalid current hotbar selection for drop");
return static_cast<short>(selectedHotbarIndex + 1);
}
return static_cast<short>(ActionHotbarIndex(requestedSlot) + 1);
}
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeHotbarDropPacket(int slot, bool all)
{
const short hotbar = ActionHotbarIndex(slot);
auto packet = std::make_shared<ProtocolCraft::ServerboundContainerClickPacket>();
packet->SetContainerId(Botcraft::Window::PLAYER_INVENTORY_INDEX);
packet->SetStateId(-1); // Request an authoritative resync, as with swb.
packet->SetSlotNum(Botcraft::Window::INVENTORY_HOTBAR_START + hotbar);
packet->SetButtonNum(all ? 1 : 0); // THROW: 0 = one item, 1 = entire stack.
packet->SetClickType(4);
packet->SetChangedSlots({});
packet->SetCarriedItem(ProtocolCraft::HashedSlot(ProtocolCraft::Slot()));
return packet;
}
ProtocolCraft::Slot RemainingAfterDrop(const ProtocolCraft::Slot &before, bool all)
{
if (before.IsEmptySlot() || all || before.GetItemCount() == 1)
return ProtocolCraft::Slot();
auto remaining = before;
remaining.SetItemCount(before.GetItemCount() - 1);
return remaining;
}
ProtocolCraft::Slot ReadDropSlot(const Botcraft::Window &window, short slot)
{
// Window::Init can clear slots without replacing the window object (e.g.
// plugin-driven inventory resets). GetSlot would silently return an empty
// slot, falsely confirming a whole-stack drop. Read one coherent snapshot.
const auto slots = window.GetSlots();
const auto found = slots.find(slot);
Require(found != slots.end(), "hotbar contents disappeared/reset during drop");
return found->second;
}
void MaintainActionInputs(BilicraftClient &client)
{
if (activeSneak && activeSneak->client == &client)
activeSneak->player->SetInputsSneak(true);
}
Status ExecuteAction(BilicraftClient &client, const ActionCommand &command)
{
const std::string location = command.source.string() + ":" + std::to_string(command.line);
try
{
Require(command.kind != ActionKind::Wait, "wait must be handled by the action scheduler");
if (command.kind == ActionKind::Goto || command.kind == ActionKind::RightClick || command.kind == ActionKind::LeftClick)
ValidateActionPosition(command.x, command.y, command.z);
CheckConnection(client);
Status result = Status::Failure;
if (command.kind == ActionKind::SendCommand)
{
const std::string text = !command.text.empty() && command.text.front() == '/' ? command.text.substr(1) : command.text;
Require(!text.empty(), "empty chat command");
client.SendChatCommand(text);
result = Status::Success;
}
else if (command.kind == ActionKind::SendMessage)
{
Require(!command.text.empty(), "empty chat message");
if (command.recipient.empty())
client.SendChatMessage(command.text);
else
client.SendChatCommand("msg " + command.recipient + " " + command.text);
result = Status::Success;
}
else
{
WaitForManagers(client);
switch (command.kind)
{
case ActionKind::Goto:
result = Botcraft::GoTo(client, Botcraft::Position(command.x, command.y, command.z));
break;
case ActionKind::RightClick:
case ActionKind::LeftClick:
result = command.entity ? ClickItemFrame(client, command) : ClickBlock(client, command);
break;
case ActionKind::GuiRightClick:
case ActionKind::GuiLeftClick:
result = ClickGui(client, command);
break;
case ActionKind::SelectHotbar:
result = Botcraft::SelectHotbarSlot(client, ActionHotbarIndex(command.slot));
break;
case ActionKind::SwapBackpack:
result = SwapBackpack(client, command);
break;
case ActionKind::Drop:
result = DropHotbar(client, command);
break;
default: throw std::runtime_error("unknown action kind");
}
}
if (result != Status::Success)
LOG_ERROR(location << ": action failed");
return result;
}
catch (const std::exception &error)
{
throw std::runtime_error(location + ": " + error.what());
}
}
} // namespace Bilicraft