Compare commits
2
Commits
0a6193f68e
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8799a62e7 | ||
|
|
12c7332337 |
No files matched your search
+3
-3
@@ -26,7 +26,7 @@ if(MINGW)
|
||||
set(BOTCRAFT_WINDOWS_BETTER_SLEEP OFF CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
include(cmake/ApplyBotcraftPatches.cmake)
|
||||
add_subdirectory(3rd/Botcraft EXCLUDE_FROM_ALL)
|
||||
add_subdirectory("${BILICRAFT_BOTCRAFT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/_deps/Botcraft-build" EXCLUDE_FROM_ALL)
|
||||
|
||||
# Botcraft's public DLL interfaces exchange STL objects: match its MSVC CRT.
|
||||
if(MSVC)
|
||||
@@ -43,7 +43,7 @@ target_include_directories(bilicraft_bot_actions PUBLIC "${CMAKE_CURRENT_SOURCE_
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(bilicraft_bot_actions PUBLIC Threads::Threads)
|
||||
|
||||
add_library(bilicraft_bot_client STATIC src/BilicraftClient.cpp src/ActionExecutor.cpp src/EntityInteraction.cpp)
|
||||
add_library(bilicraft_bot_client STATIC src/BilicraftClient.cpp src/ActionExecutor.cpp src/EntityInteraction.cpp src/BucketAim.cpp)
|
||||
target_link_libraries(bilicraft_bot_client PUBLIC bilicraft_bot_config bilicraft_bot_actions botcraft)
|
||||
|
||||
add_executable(bilicraft-bot main.cpp)
|
||||
@@ -73,7 +73,7 @@ if(BUILD_TESTING)
|
||||
else()
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
add_subdirectory(3rd/googletest EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(3rd/googletest "${CMAKE_CURRENT_BINARY_DIR}/_deps/googletest-build" EXCLUDE_FROM_ALL)
|
||||
include(GoogleTest)
|
||||
add_executable(app_config_tests tests/AppConfigTests.cpp)
|
||||
target_link_libraries(app_config_tests PRIVATE bilicraft_bot_config GTest::gtest_main)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
基于 [Botcraft](https://github.com/adepierre/Botcraft) 的 Minecraft Java 机器人,默认连接 BiliCraft 服务器。使用 Microsoft 正版账号登录,通过交互终端或 `.act` 操作文件执行移动、方块与展示框交互、背包操作和聊天命令。
|
||||
|
||||
项目使用 C++23 和 CMake,提供离线脚本检查、合作式任务调度及终端命令编辑。机器人收到服务器发来的生命值更新时,如果生命值降至 0 或以下,会自动请求复活,无需输入命令。自主种植和自动重连尚未实现。
|
||||
项目使用 C++23 和 CMake,提供离线脚本检查、合作式任务调度及终端命令编辑。机器人收到服务器发来的生命值更新时,如果生命值降至 0 或以下,会自动请求复活,无需输入命令。
|
||||
|
||||
## 环境要求
|
||||
|
||||
@@ -42,7 +42,7 @@ cmake --build build-custom --config Debug --parallel 2
|
||||
ctest --test-dir build-custom -C Debug --output-on-failure
|
||||
```
|
||||
|
||||
Botcraft 和 GoogleTest 通过 `3rd/` 中的 Git 子模块固定版本。CMake 配置时自动应用 `patches/` 下的背包同步与展示框生成修复;已应用的补丁会跳过,遇到冲突则停止配置。应用补丁后 Botcraft 子模块显示本地修改属于预期行为,请保留这些修改。
|
||||
Botcraft 和 GoogleTest 的版本由 `3rd/` 中的 Git 子模块固定。CMake 在构建目录的 `_deps/` 下创建 Botcraft 副本,背包同步、展示框生成和人物眼高补丁都在副本中应用。构建只需读取已初始化的子模块。
|
||||
|
||||
测试覆盖参数解析、脚本导入、任务调度、终端输入与编辑、客户端生命周期、背包同步和展示框定位。测试不连接服务器,也不进行 Microsoft 授权;实际服务器及插件行为仍需在线验证。
|
||||
|
||||
@@ -118,12 +118,12 @@ bilicraft-bot [--server host:port] [--account cache-key]
|
||||
| `help` | 显示终端帮助 |
|
||||
| `quit` / `exit` | 取消队列并断开连接 |
|
||||
|
||||
终端和脚本都支持[命令别名与参数定义](#命令别名与参数定义)。游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。
|
||||
终端和脚本都支持[命令别名与参数定义](#命令别名与参数定义)。游戏命令与脚本共用下文语法,但 `wait`、`import` 和 `do` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。
|
||||
|
||||
### 调度与退出
|
||||
|
||||
- 游戏操作在主线程串行执行。运行中的脚本会持续执行,直到完成、失败或遇到 `wait`;新任务不会抢占它。
|
||||
- 交互游戏命令在当前脚本完成或等待时优先执行。就绪脚本按最新入队优先(LIFO)选择,持续加入新任务可能推迟旧任务。
|
||||
- 游戏操作在主线程串行执行。脚本在完成、失败、遇到 `wait` 或开始下一轮循环时调度其他任务。
|
||||
- 交互游戏命令在当前脚本完成、等待或开始下一轮循环时优先执行。就绪脚本按最新入队优先(LIFO)选择,持续加入新任务可能推迟旧任务。
|
||||
- `wait` 挂起当前脚本,计时结束后重新入队;`import` 在当前脚本内展开,不创建独立任务。
|
||||
- 等待期间其他任务可能改变位置、手持格或背包;脚本恢复时不会自动还原状态。
|
||||
- 某个脚本失败会丢弃其剩余命令,其他任务和终端仍可继续使用;已完成的操作不回滚,也不自动重试。
|
||||
@@ -208,9 +208,14 @@ home
|
||||
| `sendcmd cmd` | 发送服务器命令,允许带一个开头 `/`,支持空格和参数 |
|
||||
| `sendmsg msg` | 发送公开聊天消息 |
|
||||
| `sendmsg @to msg` | 发送私信,等价于 `/msg to msg` |
|
||||
| `do 次数` / `do always` | 重复一条指令或一个 `begin` / `end` 块,仅操作文件可用 |
|
||||
| `import action` | 执行同目录的 `action.act`,完成后继续当前文件,仅操作文件可用 |
|
||||
|
||||
点击命令不会自动寻路,请先用 `goto` 移到交互距离内。普通方块右击选择上表面;方块与实体点击均未实现完整视线遮挡检测。
|
||||
点击命令不会自动寻路,请先用 `goto` 移到交互距离内。机器人根据服务器同步的人物体型倍率和当前姿势计算眼高,并以此瞄准方块、物品展示框和检查交互距离。
|
||||
|
||||
主手拿空桶且目标是含水方块或普通水源(水位 `level=0`)时,`rclick x y z` 会瞄准目标并使用空桶取水。服务器按视线判定取水目标,请确保中间没有遮挡。目标是流水或主手拿其他物品时,按普通方式右击方块上表面。
|
||||
|
||||
取含水台阶里的水时,请使用台阶自身的方块坐标。调试画面中的“目标液体”可能位于上方或前方的另一格。取水日志会显示实际坐标、方块状态、主手物品和交互类型。生存模式下,机器人等待服务器同步背包中新增的水桶;创造模式下也接受目标已排水的回传。5 秒内未确认时报告错误,不重复发送取水请求。
|
||||
|
||||
### 容器与背包
|
||||
|
||||
@@ -250,6 +255,26 @@ lclick 100 64 200 entry e destory # 拆除展示框
|
||||
|
||||
普通左击仅在本地已知框内有物品时攻击,并等待物品变空;创造模式下拒绝普通取物,以免直接拆框。`destory` 最多攻击两次:先取物,再拆除同一个空框。其他玩家或插件同时改变框状态仍可能影响结果,取下物品也不保证会被机器人拾取。
|
||||
|
||||
### 循环
|
||||
|
||||
`do 次数` 重复执行下一条指令。次数可写为非负十进制整数(最大 `18446744073709551615`),或用 `always` 表示无限循环。`do 0` 跳过循环体,加载时仍会检查其中的语法。
|
||||
|
||||
```text
|
||||
# action: harvest
|
||||
define rounds 3
|
||||
do $rounds begin
|
||||
rclick 100 64 200
|
||||
wait 1 s
|
||||
end
|
||||
|
||||
do 2
|
||||
import collect
|
||||
|
||||
do always wait 5 s
|
||||
```
|
||||
|
||||
单条指令可写在 `do` 同一行或下一行,多条指令用 `begin` 和 `end` 包起来。循环可以嵌套,`import` 算一条指令。每轮按顺序执行,`wait` 结束后从该轮的下一条指令继续。别名和参数仍在加载时按源码顺序定义、展开。使用 `quit` 或 Ctrl+C 可退出无限循环并断开连接。
|
||||
|
||||
### 等待与导入
|
||||
|
||||
```text
|
||||
|
||||
@@ -1,23 +1,44 @@
|
||||
# Keep the pinned upstream revision reproducible while carrying targeted fixes.
|
||||
# Never reset/checkout the submodule: refuse conflicting local edits instead.
|
||||
# Botcraft downloads assets into its source directory. Give each version and
|
||||
# patch set its own build-local checkout, including for out-of-tree builds.
|
||||
find_package(Git REQUIRED)
|
||||
set(_botcraft "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft")
|
||||
foreach(_patch_name Botcraft-inventory-sync.patch Botcraft-item-frame-spawn.patch)
|
||||
set(_patch "${CMAKE_CURRENT_SOURCE_DIR}/patches/${_patch_name}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_patch}")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --reverse --check "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _already_applied OUTPUT_QUIET ERROR_QUIET)
|
||||
if(NOT _already_applied EQUAL 0)
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --check "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _can_apply OUTPUT_QUIET ERROR_VARIABLE _error)
|
||||
if(NOT _can_apply EQUAL 0)
|
||||
message(FATAL_ERROR "Botcraft patch ${_patch_name} conflicts with the checkout; preserve local changes and inspect it manually.\n${_error}")
|
||||
endif()
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply "${_patch}"
|
||||
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _applied ERROR_VARIABLE _error)
|
||||
if(NOT _applied EQUAL 0)
|
||||
message(FATAL_ERROR "Could not apply Botcraft patch ${_patch_name}: ${_error}")
|
||||
endif()
|
||||
message(STATUS "Applied Botcraft patch ${_patch_name}")
|
||||
endif()
|
||||
set(_upstream "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse HEAD WORKING_DIRECTORY "${_upstream}"
|
||||
OUTPUT_VARIABLE _revision OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
|
||||
set(_inputs "${_revision}")
|
||||
set(_patches)
|
||||
foreach(_name inventory-sync item-frame-spawn player-eye-height)
|
||||
set(_patch "${CMAKE_CURRENT_SOURCE_DIR}/patches/Botcraft-${_name}.patch")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_patch}")
|
||||
file(SHA256 "${_patch}" _digest)
|
||||
string(APPEND _inputs " ${_digest}")
|
||||
list(APPEND _patches "${_patch}")
|
||||
endforeach()
|
||||
string(SHA256 _key "${_inputs}")
|
||||
string(SUBSTRING "${_key}" 0 16 _key)
|
||||
set(BILICRAFT_BOTCRAFT_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_deps/Botcraft-${_key}")
|
||||
set(_copy "${BILICRAFT_BOTCRAFT_SOURCE_DIR}")
|
||||
|
||||
if(NOT EXISTS "${_copy}/.git")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" clone --no-checkout --no-hardlinks
|
||||
"${_upstream}" "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
|
||||
endif()
|
||||
if(NOT EXISTS "${_copy}/.git/bilicraft-patched")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" checkout --detach "${_revision}"
|
||||
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" apply ${_patches}
|
||||
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
|
||||
file(TOUCH "${_copy}/.git/bilicraft-patched")
|
||||
endif()
|
||||
|
||||
# Reuse an initialized Asio checkout and downloaded game assets when available.
|
||||
# On a fresh machine Botcraft fetches them in its build-local checkout.
|
||||
if(EXISTS "${_upstream}/3rdparty/asio/.git" AND NOT EXISTS "${_copy}/3rdparty/asio/.git")
|
||||
execute_process(COMMAND "${GIT_EXECUTABLE}" -c protocol.file.allow=always
|
||||
-c "submodule.3rdparty/asio.url=${_upstream}/3rdparty/asio"
|
||||
submodule update --init -- 3rdparty/asio
|
||||
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
|
||||
endif()
|
||||
set(_assets "Assets/${BOTCRAFT_GAME_VERSION}/minecraft")
|
||||
if(IS_DIRECTORY "${_upstream}/${_assets}" AND NOT EXISTS "${_copy}/${_assets}")
|
||||
file(COPY "${_upstream}/${_assets}" DESTINATION "${_copy}/Assets/${BOTCRAFT_GAME_VERSION}")
|
||||
endif()
|
||||
@@ -8,10 +8,12 @@
|
||||
namespace Botcraft
|
||||
{
|
||||
class Window;
|
||||
class Blockstate;
|
||||
}
|
||||
|
||||
namespace ProtocolCraft
|
||||
{
|
||||
class Packet;
|
||||
class ServerboundContainerClickPacket;
|
||||
class Slot;
|
||||
}
|
||||
@@ -35,6 +37,9 @@ void MaintainActionInputs(BilicraftClient &client);
|
||||
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col);
|
||||
short ActionBackpackSlot(int row, int col);
|
||||
short ActionHotbarIndex(int slot);
|
||||
int CountWaterBuckets(const Botcraft::Window &window);
|
||||
std::shared_ptr<ProtocolCraft::Packet> MakeBlockRightClickPacket(const ActionCommand &command,
|
||||
const Botcraft::Blockstate &block, const ProtocolCraft::Slot &mainHand, float yaw, float pitch, int sequence);
|
||||
void ValidateActionPosition(int x, int y, int z);
|
||||
|
||||
enum class FrameAttackIntent { None, TakeItem, RemoveFrame };
|
||||
|
||||
+10
-2
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@@ -24,7 +25,9 @@ enum class ActionKind
|
||||
Drop,
|
||||
SendCommand,
|
||||
SendMessage,
|
||||
Wait
|
||||
Wait,
|
||||
LoopBegin,
|
||||
LoopEnd
|
||||
};
|
||||
|
||||
enum class EntityFace
|
||||
@@ -53,6 +56,9 @@ struct ActionCommand
|
||||
// Click entry: target an item frame; Any searches all six block faces.
|
||||
bool entity = false;
|
||||
EntityFace entityFace = EntityFace::Any;
|
||||
// LoopBegin: nullopt repeats forever. loopEnd indexes the matching LoopEnd.
|
||||
std::optional<std::uint64_t> repetitions;
|
||||
std::size_t loopEnd = 0;
|
||||
};
|
||||
|
||||
struct ActionProgram
|
||||
@@ -68,6 +74,8 @@ struct ActionProgram
|
||||
// must be simple names resolving to same-directory name.act files whose action
|
||||
// headers match. Cycles and symlink escapes are rejected. Limits: 32 active
|
||||
// files, 100000 expanded commands, 4096 file loads, 1 MiB/file and 16 MiB total.
|
||||
// do COUNT executes the next statement, or a begin/end block. COUNT may be
|
||||
// an unsigned decimal integer or always. Loop iterations are scheduled lazily.
|
||||
// Wait syntax: wait digits[.digits] [s|ms|min|h|d], default s. The duration
|
||||
// must be an exact whole number of milliseconds and may not exceed 365 days.
|
||||
// Clicks optionally accept entry [t|b|s|n|w|e] (or full face names), with
|
||||
@@ -76,7 +84,7 @@ struct ActionProgram
|
||||
ActionProgram LoadActionFile(const std::filesystem::path &path, CommandBindings bindings = {});
|
||||
|
||||
// Parse one console game instruction using the .act grammar, without file I/O.
|
||||
// Blank/comment lines return nullopt. Wait/import require `run file.act` instead.
|
||||
// Blank/comment lines return nullopt. Wait/import/loops require `run file.act`.
|
||||
// CR, LF and NUL are rejected; errors throw with <console>:1 context.
|
||||
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text);
|
||||
} // namespace Bilicraft
|
||||
@@ -49,6 +49,11 @@ class ActionScheduler
|
||||
std::vector<std::string> DrainEvents();
|
||||
|
||||
private:
|
||||
struct LoopFrame
|
||||
{
|
||||
std::size_t body;
|
||||
std::optional<std::uint64_t> remaining;
|
||||
};
|
||||
struct Task
|
||||
{
|
||||
TaskId id;
|
||||
@@ -57,6 +62,7 @@ class ActionScheduler
|
||||
State state = State::Ready;
|
||||
Clock::time_point wakeAt{};
|
||||
std::uint64_t readyOrder = 0;
|
||||
std::vector<LoopFrame> loops;
|
||||
};
|
||||
void RemoveActive(bool success);
|
||||
std::map<TaskId, Task> tasks;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "botcraft/Game/Vector3.hpp"
|
||||
#include <optional>
|
||||
|
||||
namespace Botcraft { class World; }
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
std::optional<Botcraft::Vector3<double>> FindBucketAim(const Botcraft::World &world,
|
||||
const Botcraft::Vector3<double> &eyes, const Botcraft::Position &target, double reach);
|
||||
}
|
||||
@@ -96,7 +96,12 @@ int main(int argc, char **argv)
|
||||
bool eofReported = false;
|
||||
bool actionFailed = false;
|
||||
std::optional<Clock::time_point> drainedSince;
|
||||
console->Out() << "Entered game. " << ConsoleHelp();
|
||||
console->Out() << "Entered game.\n"
|
||||
"bilicraft-bot Copyright (C) 2026 Jeffrey Hsu\n"
|
||||
"This is free software. You may redistribute and modify it under the terms of "
|
||||
"the GNU General Public License, version 3.\n"
|
||||
"This program comes with ABSOLUTELY NO WARRANTY. See LICENSE for details.\n\n"
|
||||
"Type 'help' to list the available commands.\n";
|
||||
const auto printEvents = [&] {
|
||||
for (const auto &event : scheduler.DrainEvents()) console->Out() << event << '\n';
|
||||
console->Out().flush();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
diff --git a/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp b/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
|
||||
index c62026d6..f7f4760a 100644
|
||||
--- a/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
|
||||
+++ b/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
|
||||
@@ -376,16 +376,21 @@ namespace Botcraft
|
||||
double PlayerEntity::GetEyeHeightImpl() const
|
||||
{
|
||||
#if PROTOCOL_VERSION > 404 /* > 1.13.2 */
|
||||
+#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
|
||||
+ const double scale = attributes.at(EntityAttribute::Type::Scale).GetValue();
|
||||
+#else
|
||||
+ constexpr double scale = 1.0;
|
||||
+#endif
|
||||
switch (GetDataPoseImpl())
|
||||
{
|
||||
case Pose::Swimming:
|
||||
case Pose::FallFlying:
|
||||
case Pose::SpinAttack:
|
||||
- return 0.4;
|
||||
+ return 0.4 * scale;
|
||||
case Pose::Crouching:
|
||||
- return 1.27;
|
||||
+ return 1.27 * scale;
|
||||
default:
|
||||
- return 1.62;
|
||||
+ return 1.62 * scale;
|
||||
}
|
||||
#else
|
||||
return 1.62;
|
||||
+119
-14
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "ActionFile.h"
|
||||
#include "BilicraftClient.h"
|
||||
#include "BucketAim.h"
|
||||
#include "EntityInteraction.h"
|
||||
|
||||
#include <chrono>
|
||||
@@ -14,6 +15,7 @@
|
||||
#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"
|
||||
@@ -159,7 +161,7 @@ Botcraft::Vector3<double> BlockCenter(const ActionCommand &command)
|
||||
return Botcraft::Vector3<double>(command.x + 0.5, command.y + 0.5, command.z + 0.5);
|
||||
}
|
||||
|
||||
void CheckTarget(BilicraftClient &client, const ActionCommand &command)
|
||||
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");
|
||||
@@ -172,6 +174,7 @@ void CheckTarget(BilicraftClient &client, const ActionCommand &command)
|
||||
// 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)
|
||||
@@ -181,12 +184,32 @@ void Swing(BilicraftClient &client)
|
||||
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;
|
||||
CheckTarget(client, command); // The world/player may have changed during Yield.
|
||||
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)
|
||||
@@ -199,20 +222,60 @@ Status ClickBlock(BilicraftClient &client, const ActionCommand &command)
|
||||
return Status::Success;
|
||||
}
|
||||
|
||||
// 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(client.GetWorld()->GetNextWorldInteractionSequenceId());
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -438,6 +501,48 @@ Status DropHotbar(BilicraftClient &client, const ActionCommand &command)
|
||||
}
|
||||
} // 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
|
||||
|
||||
+97
-22
@@ -284,6 +284,41 @@ struct Loader
|
||||
std::size_t loads = 0;
|
||||
std::size_t total_bytes = 0;
|
||||
|
||||
void Append(ActionCommand command)
|
||||
{
|
||||
if (program.commands.size() >= kMaxCommands)
|
||||
Fail(command.source, command.line, "expanded command limit exceeded (100000)");
|
||||
program.commands.push_back(std::move(command));
|
||||
}
|
||||
|
||||
void LoadInstruction(std::string_view verb, std::string_view line, const std::filesystem::path &source,
|
||||
std::size_t line_number)
|
||||
{
|
||||
if (verb == "import")
|
||||
{
|
||||
const auto name = TakeToken(line);
|
||||
if (!IsSimpleName(name) || !Trim(line).empty())
|
||||
Fail(source, line_number, "import requires exactly one simple action name");
|
||||
const auto imported = source.parent_path() / (std::string(name) + ".act");
|
||||
std::error_code ec;
|
||||
const auto resolved = std::filesystem::canonical(imported, ec);
|
||||
if (ec)
|
||||
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
|
||||
if (resolved.parent_path() != source.parent_path())
|
||||
Fail(source, line_number, "import escapes its action directory");
|
||||
try
|
||||
{
|
||||
Load(resolved, name);
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
|
||||
}
|
||||
return;
|
||||
}
|
||||
Append(ParseCommand(verb, line, source, line_number));
|
||||
}
|
||||
|
||||
void Load(const std::filesystem::path &path, std::string_view expected_name = {})
|
||||
{
|
||||
std::error_code ec;
|
||||
@@ -329,6 +364,23 @@ struct Loader
|
||||
remaining.remove_prefix(3);
|
||||
bool header_seen = false;
|
||||
std::size_t line_number = 0;
|
||||
struct OpenLoop
|
||||
{
|
||||
std::size_t start;
|
||||
bool block;
|
||||
};
|
||||
// Each file must balance its own blocks, including when imported as a single statement.
|
||||
std::vector<OpenLoop> loops;
|
||||
const auto closeLoop = [&] {
|
||||
auto &start = program.commands[loops.back().start];
|
||||
start.loopEnd = program.commands.size();
|
||||
ActionCommand end{};
|
||||
end.kind = ActionKind::LoopEnd;
|
||||
end.source = source;
|
||||
end.line = line_number;
|
||||
Append(std::move(end));
|
||||
loops.pop_back();
|
||||
};
|
||||
while (!remaining.empty())
|
||||
{
|
||||
++line_number;
|
||||
@@ -365,7 +417,10 @@ struct Loader
|
||||
continue;
|
||||
if (!header_seen)
|
||||
Fail(source, line_number, "missing action header before first instruction");
|
||||
// A single-line body may itself begin with another do. Parse it iteratively.
|
||||
std::string expanded;
|
||||
for (;;)
|
||||
{
|
||||
try
|
||||
{
|
||||
expanded = bindings.Expand(line, kMaxFileBytes);
|
||||
@@ -374,38 +429,58 @@ struct Loader
|
||||
{
|
||||
Fail(source, line_number, error.what());
|
||||
}
|
||||
if (expanded.empty()) continue;
|
||||
expandedBytes += expanded.size();
|
||||
if (expandedBytes > kMaxTotalBytes)
|
||||
Fail(source, line_number, "total expanded action text exceeds 16 MiB");
|
||||
line = expanded;
|
||||
const auto verb = TakeToken(line);
|
||||
if (verb == "import")
|
||||
line = Trim(line);
|
||||
if (verb == "do")
|
||||
{
|
||||
const auto name = TakeToken(line);
|
||||
if (!IsSimpleName(name) || !Trim(line).empty())
|
||||
Fail(source, line_number, "import requires exactly one simple action name");
|
||||
const auto imported = source.parent_path() / (std::string(name) + ".act");
|
||||
const auto resolved = std::filesystem::canonical(imported, ec);
|
||||
if (ec)
|
||||
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
|
||||
if (resolved.parent_path() != source.parent_path())
|
||||
Fail(source, line_number, "import escapes its action directory");
|
||||
try
|
||||
ActionCommand start{};
|
||||
start.kind = ActionKind::LoopBegin;
|
||||
start.source = source;
|
||||
start.line = line_number;
|
||||
const auto count = TakeToken(line);
|
||||
if (count != "always")
|
||||
{
|
||||
Load(resolved, name);
|
||||
}
|
||||
catch (const std::runtime_error &error)
|
||||
{
|
||||
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
|
||||
std::uint64_t repetitions = 0;
|
||||
const auto parsed = std::from_chars(count.data(), count.data() + count.size(), repetitions);
|
||||
if (count.empty() || parsed.ec != std::errc{} || parsed.ptr != count.data() + count.size())
|
||||
Fail(source, line_number, "do requires a nonnegative integer or always");
|
||||
start.repetitions = repetitions;
|
||||
}
|
||||
loops.push_back({program.commands.size(), false});
|
||||
Append(std::move(start));
|
||||
line = Trim(line);
|
||||
if (line.empty()) break;
|
||||
continue;
|
||||
}
|
||||
auto command = ParseCommand(verb, line, source, line_number);
|
||||
if (program.commands.size() >= kMaxCommands)
|
||||
Fail(source, line_number, "expanded command limit exceeded (100000)");
|
||||
program.commands.push_back(std::move(command));
|
||||
if (verb == "begin")
|
||||
{
|
||||
if (loops.empty() || loops.back().block || !line.empty())
|
||||
Fail(source, line_number, "expected begin only after do <count>");
|
||||
loops.back().block = true;
|
||||
break;
|
||||
}
|
||||
if (verb == "end")
|
||||
{
|
||||
if (loops.empty() || !loops.back().block || !line.empty())
|
||||
Fail(source, line_number, "end requires a matching do block with a complete body");
|
||||
closeLoop();
|
||||
}
|
||||
else if (!verb.empty()) // alias and define were processed while expanding.
|
||||
LoadInstruction(verb, line, source, line_number);
|
||||
|
||||
// A complete statement also completes enclosing unbracketed loops.
|
||||
while (!loops.empty() && !loops.back().block)
|
||||
closeLoop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!loops.empty())
|
||||
Fail(source, program.commands[loops.back().start].line,
|
||||
loops.back().block ? "missing end for do block" : "missing statement after do");
|
||||
if (!header_seen)
|
||||
Fail(source, line_number == 0 ? 1 : line_number, "missing action header");
|
||||
}
|
||||
@@ -434,7 +509,7 @@ std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text)
|
||||
if (text.empty())
|
||||
return std::nullopt;
|
||||
const auto verb = TakeToken(text);
|
||||
if (verb == "wait" || verb == "import")
|
||||
if (verb == "wait" || verb == "import" || verb == "do" || verb == "begin" || verb == "end")
|
||||
Fail(source, 1, std::string(verb) + " is only available in action files; use run file.act");
|
||||
return ParseCommand(verb, text, source, 1);
|
||||
}
|
||||
|
||||
+62
-3
@@ -10,16 +10,34 @@ ActionScheduler::TaskId ActionScheduler::Enqueue(ActionProgram program, Clock::t
|
||||
{
|
||||
if (tasks.size() >= 128 || program.commands.size() > 1000000 - storedCommands)
|
||||
throw std::runtime_error("action queue limit exceeded (128 tasks / 1000000 commands)");
|
||||
for (const auto &command : program.commands)
|
||||
std::vector<std::size_t> ends;
|
||||
for (std::size_t pc = 0; pc < program.commands.size(); ++pc)
|
||||
{
|
||||
const auto &command = program.commands[pc];
|
||||
if (command.kind == ActionKind::LoopBegin)
|
||||
{
|
||||
if (command.loopEnd <= pc || command.loopEnd >= program.commands.size() ||
|
||||
(!ends.empty() && command.loopEnd >= ends.back()) ||
|
||||
program.commands[command.loopEnd].kind != ActionKind::LoopEnd)
|
||||
throw std::runtime_error("invalid loop end in action program");
|
||||
ends.push_back(command.loopEnd);
|
||||
}
|
||||
if (command.kind == ActionKind::LoopEnd)
|
||||
{
|
||||
if (ends.empty() || pc != ends.back())
|
||||
throw std::runtime_error("unmatched loop end in action program");
|
||||
ends.pop_back();
|
||||
}
|
||||
if (command.kind == ActionKind::Wait &&
|
||||
(command.waitDuration.count() < 0 || command.waitDuration > std::chrono::hours(24 * 365)))
|
||||
throw std::runtime_error("wait duration must be between zero and 365 days");
|
||||
}
|
||||
// An already-expired wait became ready BEFORE this newly submitted task,
|
||||
// even when another action was executing throughout that time.
|
||||
WakeReady(now);
|
||||
const auto id = nextId++;
|
||||
storedCommands += program.commands.size();
|
||||
tasks.emplace(id, Task{id, std::move(program), 0, State::Ready, {}, nextOrder++});
|
||||
tasks.emplace(id, Task{id, std::move(program), 0, State::Ready, {}, nextOrder++, {}});
|
||||
events.push_back("Action #" + std::to_string(id) + " '" + tasks.at(id).program.name + "': queued");
|
||||
return id;
|
||||
}
|
||||
@@ -30,6 +48,8 @@ void ActionScheduler::SubmitInteractive(ActionCommand command)
|
||||
throw std::runtime_error("previous interactive command has not completed");
|
||||
if (command.kind == ActionKind::Wait)
|
||||
throw std::runtime_error("wait is not allowed in the interactive console; use run file.act");
|
||||
if (command.kind == ActionKind::LoopBegin || command.kind == ActionKind::LoopEnd)
|
||||
throw std::runtime_error("do loops are only available in action files");
|
||||
interactive = std::move(command);
|
||||
}
|
||||
|
||||
@@ -55,6 +75,8 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
|
||||
if (inFlight)
|
||||
throw std::logic_error("finish the outstanding command before scheduling another");
|
||||
WakeReady(now);
|
||||
// Empty loops and loops containing only skipped bodies must return to the console pump.
|
||||
unsigned controlSteps = 0;
|
||||
for (;;)
|
||||
{
|
||||
if (!active)
|
||||
@@ -81,7 +103,39 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
|
||||
continue;
|
||||
}
|
||||
const auto &command = task.program.commands[task.pc];
|
||||
if (command.kind == ActionKind::Wait)
|
||||
if (command.kind == ActionKind::LoopBegin)
|
||||
{
|
||||
if (command.repetitions == 0 || (command.repetitions && task.pc + 1 == command.loopEnd))
|
||||
task.pc = command.loopEnd + 1;
|
||||
else
|
||||
{
|
||||
++task.pc;
|
||||
task.loops.push_back({task.pc, command.repetitions});
|
||||
}
|
||||
}
|
||||
else if (command.kind == ActionKind::LoopEnd)
|
||||
{
|
||||
auto &loop = task.loops.back();
|
||||
if (loop.remaining && --*loop.remaining == 0)
|
||||
{
|
||||
task.loops.pop_back();
|
||||
++task.pc;
|
||||
}
|
||||
else
|
||||
{
|
||||
task.pc = loop.body;
|
||||
// At a repeat boundary, pending input and newer ready tasks can run.
|
||||
if (interactive || std::any_of(tasks.begin(), tasks.end(), [&](const auto &entry) {
|
||||
const auto &other = entry.second;
|
||||
return other.state == State::Ready && other.readyOrder > task.readyOrder;
|
||||
}))
|
||||
{
|
||||
task.state = State::Ready;
|
||||
active.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (command.kind == ActionKind::Wait)
|
||||
{
|
||||
if (now > Clock::time_point::max() - command.waitDuration)
|
||||
throw std::overflow_error("wait deadline exceeds steady clock range");
|
||||
@@ -94,10 +148,15 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
|
||||
// Even wait 0 yields once. It is promoted on the next Next() call.
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
inFlight = true;
|
||||
interactiveInFlight = false;
|
||||
return Work{command, task.id, false};
|
||||
}
|
||||
if (++controlSteps == 256)
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
void ActionScheduler::RemoveActive(bool success)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#include "BucketAim.h"
|
||||
#include "botcraft/Game/World/World.hpp"
|
||||
#include "botcraft/Game/World/Blockstate.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
namespace Bilicraft
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using namespace Botcraft;
|
||||
|
||||
bool IntersectsSegment(const AABB &box, const Vector3<double> &start, const Vector3<double> &end)
|
||||
{
|
||||
const auto lo = box.GetMin(), hi = box.GetMax();
|
||||
double enter = 0, leave = 1;
|
||||
for (int axis = 0; axis < 3; ++axis)
|
||||
{
|
||||
const double delta = end[axis] - start[axis];
|
||||
if (delta == 0)
|
||||
{
|
||||
if (start[axis] < lo[axis] || start[axis] > hi[axis]) return false;
|
||||
continue;
|
||||
}
|
||||
const double a = (lo[axis] - start[axis]) / delta;
|
||||
const double b = (hi[axis] - start[axis]) / delta;
|
||||
enter = std::max(enter, std::min(a, b));
|
||||
leave = std::min(leave, std::max(a, b));
|
||||
if (enter > leave) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<Botcraft::Vector3<double>> FindBucketAim(const Botcraft::World &world,
|
||||
const Botcraft::Vector3<double> &eyes, const Botcraft::Position &target, double reach)
|
||||
{
|
||||
// Include the row below the rays because fences and walls can extend above their cell.
|
||||
const Position eyeCell(std::floor(eyes.x), std::floor(eyes.y), std::floor(eyes.z));
|
||||
std::vector<AABB> obstacles;
|
||||
for (int x = std::min(eyeCell.x, target.x); x <= std::max(eyeCell.x, target.x); ++x)
|
||||
for (int y = std::min(eyeCell.y, target.y) - 1; y <= std::max(eyeCell.y, target.y); ++y)
|
||||
for (int z = std::min(eyeCell.z, target.z); z <= std::max(eyeCell.z, target.z); ++z)
|
||||
{
|
||||
const Position cell(x, y, z);
|
||||
if (cell == target) continue;
|
||||
const auto *state = world.GetBlock(cell);
|
||||
if (!state)
|
||||
{
|
||||
obstacles.emplace_back(Vector3<double>(x + 0.5, y + 0.5, z + 0.5), Vector3<double>(0.5));
|
||||
continue;
|
||||
}
|
||||
if (state->IsAir()) continue;
|
||||
const auto boxes = state->GetCollidersAtPos(cell);
|
||||
obstacles.insert(obstacles.end(), boxes.begin(), boxes.end());
|
||||
// Bubble columns also contain source water and have no level property.
|
||||
if (state->IsWaterlogged() || state->GetName() == "minecraft:bubble_column" ||
|
||||
(state->IsFluid() && state->GetVariableValue("level") == "0"))
|
||||
{
|
||||
const auto *above = world.GetBlock(cell + Position(0, 1, 0));
|
||||
const bool continuous = above && ((state->IsWaterOrWaterlogged() && above->IsWaterOrWaterlogged()) ||
|
||||
(state->IsLava() && above->IsLava()));
|
||||
const double halfHeight = (continuous ? 1.0 : state->GetFluidHeight()) / 2;
|
||||
obstacles.emplace_back(Vector3<double>(x + 0.5, y + halfHeight, z + 0.5),
|
||||
Vector3<double>(0.5, halfHeight, 0.5));
|
||||
}
|
||||
}
|
||||
// Try the center first, then points below source-fluid height inside the target cell.
|
||||
for (double x : {0.5, 0.25, 0.75, 0.1, 0.9})
|
||||
for (double y : {0.5, 0.25, 0.75, 0.1, 0.85})
|
||||
for (double z : {0.5, 0.25, 0.75, 0.1, 0.9})
|
||||
{
|
||||
const Vector3<double> point(target.x + x, target.y + y, target.z + z);
|
||||
if (eyes.SqrDist(point) < reach * reach && std::none_of(obstacles.begin(), obstacles.end(),
|
||||
[&](const AABB &box) { return IntersectsSegment(box, eyes, point); })) return point;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,14 @@ std::string CommandBindings::Expand(std::string_view line, std::size_t maxLength
|
||||
throw std::runtime_error("expanded command exceeds length limit");
|
||||
substituted.append(token).append(spaces);
|
||||
rest.remove_prefix(spaces.size());
|
||||
// An inline do body is its own statement, with its own binding expansion.
|
||||
if (verb == "do")
|
||||
{
|
||||
if (substituted.size() + rest.size() > maxLength)
|
||||
throw std::runtime_error("expanded command exceeds length limit");
|
||||
substituted.append(rest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return substituted;
|
||||
}
|
||||
|
||||
@@ -64,8 +64,8 @@ std::string ConsoleHelp()
|
||||
"define [name [value...]]: store session parameters; use $name as a whole argument.\n"
|
||||
"Game commands: goto, rclick, lclick, grclick, glclick, sw, swb, drop, sendcmd, sendmsg\n"
|
||||
"rclick/lclick: add entry [t|b|s|n|w|e] for item frames; omit face to require a unique frame.\n"
|
||||
"A game command waits until the running action finishes or reaches wait.\n"
|
||||
"Only one interactive game command can be pending. wait/import are not allowed here.\n"
|
||||
"A game command waits until completion, wait, or the next loop iteration.\n"
|
||||
"Only one interactive game command can be pending. wait/import/do are only available in action files.\n"
|
||||
"run validates and queues a file immediately; newest ready action runs first.\n"
|
||||
"Native terminal: fixed input bar, Up/Down history, Left/Right/Home/End editing.\n"
|
||||
"Ctrl+C/quit cancels; EOF drains queued tasks, then disconnects.\n";
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#include "ActionExecutor.h"
|
||||
#include "ActionFile.h"
|
||||
#include "BilicraftClient.h"
|
||||
#include "BucketAim.h"
|
||||
#include "botcraft/Game/Entities/LocalPlayer.hpp"
|
||||
#include "botcraft/Game/World/World.hpp"
|
||||
|
||||
#include <climits>
|
||||
#include <stdexcept>
|
||||
@@ -10,12 +13,105 @@
|
||||
|
||||
#include "protocolCraft/Packets/Game/Serverbound/ServerboundContainerClickPacket.hpp"
|
||||
#include "botcraft/Game/Inventory/Window.hpp"
|
||||
#include "botcraft/Game/AssetsManager.hpp"
|
||||
|
||||
namespace
|
||||
{
|
||||
using namespace Bilicraft;
|
||||
using Botcraft::InventoryType;
|
||||
|
||||
TEST(ActionExecutor, EmptyBucketUsesAimedMainHandOnWaterloggedBlocksAndWaterSources)
|
||||
{
|
||||
auto &assets = Botcraft::AssetsManager::getInstance();
|
||||
const Botcraft::Blockstate *wet = nullptr, *dry = nullptr;
|
||||
for (const auto *state : assets.GetBlockstates("minecraft:oak_slab"))
|
||||
(state->IsWaterlogged() ? wet : dry) = state;
|
||||
ASSERT_NE(wet, nullptr);
|
||||
ASSERT_NE(dry, nullptr);
|
||||
const auto command = ParseInteractiveCommand("rclick 1 1 1").value();
|
||||
ProtocolCraft::Slot hand;
|
||||
hand.SetItemCount(1);
|
||||
hand.SetItemId(assets.GetItemID("minecraft:bucket"));
|
||||
const auto click = [&](const Botcraft::Blockstate &state) {
|
||||
return MakeBlockRightClickPacket(command, state, hand, 73.0f, -18.0f, 42);
|
||||
};
|
||||
const auto pickup = std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemPacket>(click(*wet));
|
||||
ASSERT_TRUE(pickup);
|
||||
EXPECT_EQ(pickup->GetHand(), static_cast<int>(Botcraft::Hand::Main));
|
||||
EXPECT_EQ(pickup->GetYRot(), 73.0f);
|
||||
EXPECT_EQ(pickup->GetXRot(), -18.0f);
|
||||
EXPECT_EQ(pickup->GetSequence(), 42);
|
||||
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*dry)));
|
||||
const auto waterStates = assets.GetBlockstates("minecraft:water");
|
||||
ASSERT_EQ(waterStates.size(), 16u);
|
||||
for (const auto *water : waterStates)
|
||||
{
|
||||
const auto &level = water->GetVariableValue("level");
|
||||
SCOPED_TRACE(level);
|
||||
if (level == "0")
|
||||
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemPacket>(click(*water)));
|
||||
else
|
||||
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*water)));
|
||||
}
|
||||
hand.SetItemId(assets.GetItemID("minecraft:water_bucket"));
|
||||
for (const auto *water : waterStates)
|
||||
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*water)));
|
||||
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*wet)));
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, BucketCanReachSourceThroughGapBelowUpperSlab)
|
||||
{
|
||||
auto &assets = Botcraft::AssetsManager::getInstance();
|
||||
Botcraft::World world(false);
|
||||
const std::string dimension = "minecraft:overworld";
|
||||
world.SetDimensionMinY(dimension, 0);
|
||||
world.SetDimensionHeight(dimension, 256);
|
||||
world.LoadChunk(0, 0, dimension);
|
||||
const Botcraft::Position target(5, 93, 5);
|
||||
world.SetBlock({5, 93, 4}, assets.GetBlockstate("minecraft:oak_planks")->GetId());
|
||||
for (const auto *slab : assets.GetBlockstates("minecraft:oak_slab"))
|
||||
if (slab->GetVariableValue("type") == "top")
|
||||
world.SetBlock({5, slab->IsWaterlogged() ? 92 : 94, 5}, slab->GetId());
|
||||
for (const auto *water : assets.GetBlockstates("minecraft:water"))
|
||||
if (water->GetVariableValue("level") == "0") world.SetBlock(target, water->GetId());
|
||||
Botcraft::LocalPlayer player;
|
||||
player.SetPosition({5.438707, 94, 4.368732});
|
||||
for (const double scale : {1.0, 0.58522856})
|
||||
{
|
||||
SCOPED_TRACE(scale);
|
||||
player.SetAttributeBaseValue(Botcraft::EntityAttribute::Type::Scale, scale);
|
||||
const auto eyes = player.GetPosition() + Botcraft::Vector3<double>(0, player.GetEyeHeight(), 0);
|
||||
const auto aim = FindBucketAim(world, eyes, target, 4.5);
|
||||
ASSERT_TRUE(aim);
|
||||
player.LookAt(*aim, true);
|
||||
const auto direction = player.GetFrontVector();
|
||||
const double frontY = 94 + 1.62 * scale + direction.y * (5 - eyes.z) / direction.z;
|
||||
EXPECT_GT(frontY, 94.0);
|
||||
EXPECT_LT(frontY, 94.5);
|
||||
EXPECT_FALSE(FindBucketAim(world, eyes, {5, 92, 5}, 4.5));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, EyeHeightAndLookAtFollowChangesToScaleAndPose)
|
||||
{
|
||||
Botcraft::LocalPlayer player;
|
||||
player.SetPosition({0, 10, 0});
|
||||
for (const double scale : {0.58522856, 2.0, 1.0})
|
||||
{
|
||||
SCOPED_TRACE(scale);
|
||||
player.SetAttributeBaseValue(Botcraft::EntityAttribute::Type::Scale, scale);
|
||||
for (const auto [pose, height] : {std::pair{Botcraft::Pose::Standing, 1.62},
|
||||
std::pair{Botcraft::Pose::Crouching, 1.27},
|
||||
std::pair{Botcraft::Pose::Swimming, 0.4}})
|
||||
{
|
||||
player.SetDataPose(pose);
|
||||
EXPECT_DOUBLE_EQ(player.GetEyeHeight(), height * scale);
|
||||
player.LookAt({0, 10 + height * scale, 2}, true);
|
||||
EXPECT_NEAR(player.GetPitch(), 0, 1e-5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ActionExecutor, MapsEveryGenericContainerSize)
|
||||
{
|
||||
const InventoryType types[] = {InventoryType::Generic9x1, InventoryType::Generic9x2, InventoryType::Generic9x3,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "ActionFile.h"
|
||||
#include "ActionScheduler.h"
|
||||
#include "ConsoleCommand.h"
|
||||
|
||||
#include <atomic>
|
||||
@@ -113,6 +114,81 @@ class ActionFileTest : public ::testing::Test
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ActionFileTest, ExecutesNestedLoopsAndSingleStatementImportsInOrder)
|
||||
{
|
||||
Write("collect.act", "# action: collect\nsw 2\nsw 3\n");
|
||||
auto program = Parse("# action: test\ndefine n 2\nalias pick sw\ndo $n begin\n"
|
||||
" do 0 sw 9\n pick 1\n do 2\n # count the import as one statement\n"
|
||||
" import collect\nend\ndo 2 do 2 pick 4\nsw 5\n");
|
||||
Bilicraft::ActionScheduler queue;
|
||||
queue.Enqueue(std::move(program));
|
||||
for (int expected : {1,2,3,2,3,1,2,3,2,3,4,4,4,4,5})
|
||||
{
|
||||
const auto work = queue.Next({});
|
||||
ASSERT_TRUE(work);
|
||||
EXPECT_EQ(work->command.slot, expected);
|
||||
queue.Finish(true);
|
||||
}
|
||||
EXPECT_FALSE(queue.Next({}));
|
||||
EXPECT_FALSE(queue.HasWork());
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, AlwaysLoopResumesAfterWaitAndStopsOnCommandFailure)
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
auto program = Parse("# action: test\ndo always begin\nsw 3\nwait 2 s\nsw 4\nend\nsw 5");
|
||||
Bilicraft::ActionScheduler queue;
|
||||
Bilicraft::ActionScheduler::Clock::time_point now{};
|
||||
queue.Enqueue(std::move(program), now);
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
const auto first = queue.Next(now);
|
||||
ASSERT_TRUE(first);
|
||||
EXPECT_EQ(first->command.slot, 3);
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.Next(now));
|
||||
now += 2s;
|
||||
const auto second = queue.Next(now);
|
||||
ASSERT_TRUE(second);
|
||||
EXPECT_EQ(second->command.slot, 4);
|
||||
queue.Finish(i < 2);
|
||||
}
|
||||
EXPECT_FALSE(queue.HasWork());
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, EmptyInfiniteLoopReturnsControlAndVeryLargeCountsStayCompact)
|
||||
{
|
||||
Bilicraft::ActionScheduler queue;
|
||||
auto program = Parse("# action: test\ndo 18446744073709551615 begin\nend\n"
|
||||
"do always do 0 sw 9\nsw 5");
|
||||
ASSERT_LT(program.commands.size(), 10u);
|
||||
queue.Enqueue(std::move(program));
|
||||
EXPECT_FALSE(queue.Next({}));
|
||||
ASSERT_TRUE(queue.HasWork());
|
||||
queue.SubmitInteractive(*ParseInteractiveCommand("sw 1"));
|
||||
const auto work = queue.Next({});
|
||||
ASSERT_TRUE(work);
|
||||
EXPECT_TRUE(work->interactive);
|
||||
queue.Finish(true);
|
||||
EXPECT_FALSE(queue.Next({}));
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ValidatesLoopStructureAndSkippedBodiesAtLoadTime)
|
||||
{
|
||||
for (auto count : {"-1", "1.2", "infine", "2x", "18446744073709551616"})
|
||||
Reject(std::string("# action: test\ndo ") + count + " sw 1", "nonnegative integer or always");
|
||||
Reject("# action: test\ndo", "nonnegative integer or always");
|
||||
Reject("# action: test\ndo 1\n# no body", "missing statement");
|
||||
Reject("# action: test\ndo 1 begin\nsw 1", "missing end");
|
||||
Reject("# action: test\ndo 0 invalid", "unknown instruction");
|
||||
Reject("# action: test\nend", "matching do");
|
||||
Reject("# action: test\nbegin", "after do");
|
||||
Reject("# action: test\ndo 1 begin\ndo 2\nend", "complete body", 4);
|
||||
Write("child.act", "# action: child\nend");
|
||||
Reject("# action: test\ndo 1 begin\nimport child\nend", "matching do", 3);
|
||||
RejectInteractive("do always sw 1", "only available in action files");
|
||||
}
|
||||
|
||||
TEST_F(ActionFileTest, ExpandsBindingsInSourceOrderAcrossImports)
|
||||
{
|
||||
Write("child.act", "# action: child\nhome\ndefine pos1 20 64 -8\nalias pause wait 1 s\n");
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "botcraft/Game/AssetsManager.hpp"
|
||||
#include "botcraft/Game/Inventory/InventoryManager.hpp"
|
||||
#include "botcraft/Game/Inventory/Window.hpp"
|
||||
|
||||
@@ -44,6 +45,28 @@ class InventorySync : public testing::Test
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(InventorySync, FilledBucketConfirmationCountsServerUpdatesAcrossInventory)
|
||||
{
|
||||
Full();
|
||||
auto &assets = Botcraft::AssetsManager::getInstance();
|
||||
auto emptyBuckets = Item(2);
|
||||
emptyBuckets.SetItemId(assets.GetItemID("minecraft:bucket"));
|
||||
auto filled = Item(1);
|
||||
filled.SetItemId(assets.GetItemID("minecraft:water_bucket"));
|
||||
PlayerSlot(0, emptyBuckets);
|
||||
PlayerSlot(1, filled);
|
||||
const auto window = inventory.GetPlayerInventory();
|
||||
const auto before = Bilicraft::CountWaterBuckets(*window);
|
||||
ASSERT_EQ(before, 1);
|
||||
emptyBuckets.SetItemCount(1);
|
||||
PlayerSlot(0, emptyBuckets);
|
||||
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before);
|
||||
PlayerSlot(9, filled);
|
||||
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before + 1);
|
||||
PlayerSlot(0, filled);
|
||||
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before + 2);
|
||||
}
|
||||
|
||||
TEST_F(InventorySync, EmptyHotbarUpdateClearsHeldItemInsteadOfCraftingOutput)
|
||||
{
|
||||
Full();
|
||||
|
||||
Reference in new issue
Block a user