221 lines
9.2 KiB
C++
221 lines
9.2 KiB
C++
#include "AppConfig.h"
|
|
#include "ActionFile.h"
|
|
#include "ActionExecutor.h"
|
|
#include "ActionScheduler.h"
|
|
#include "ConsoleCommand.h"
|
|
#include "BilicraftClient.h"
|
|
#include "TerminalConsole.h"
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <csignal>
|
|
#include <cstdio>
|
|
#include <exception>
|
|
#include <iostream>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <stdexcept>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
#include "botcraft/Utilities/Logger.hpp"
|
|
|
|
namespace
|
|
{
|
|
volatile std::sig_atomic_t stopRequested = 0;
|
|
void RequestStop(int) { stopRequested = 1; }
|
|
} // namespace
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
using namespace Bilicraft;
|
|
using namespace std::chrono_literals;
|
|
using Clock = ActionScheduler::Clock;
|
|
try
|
|
{
|
|
std::vector<std::string_view> arguments;
|
|
for (int i = 1; i < argc; ++i) arguments.emplace_back(argv[i]);
|
|
const auto config = ParseArguments(arguments);
|
|
if (config.help)
|
|
{
|
|
std::cout << Usage();
|
|
return 0;
|
|
}
|
|
// Validate the entire initial import graph before authentication/effects.
|
|
std::optional<ActionProgram> program;
|
|
if (!config.actionFile.empty())
|
|
{
|
|
program = LoadActionFile(config.actionFile);
|
|
if (config.checkAction)
|
|
{
|
|
std::cout << "Action '" << program->name << "': " << program->commands.size()
|
|
<< " commands validated (including imports).\n";
|
|
return 0;
|
|
}
|
|
}
|
|
std::signal(SIGINT, RequestStop);
|
|
std::signal(SIGTERM, RequestStop);
|
|
// Declared before the client: join network/physics logging before the
|
|
// console restores the terminal. A weak callback cannot outlive it.
|
|
auto console = std::make_shared<TerminalConsole>();
|
|
Botcraft::Logger::GetInstance().SetLogFunc([weak = std::weak_ptr<TerminalConsole>(console)](const std::string &message) {
|
|
if (const auto output = weak.lock())
|
|
output->WriteLog(message);
|
|
else
|
|
{
|
|
std::fwrite(message.data(), 1, message.size(), stdout);
|
|
std::fflush(stdout);
|
|
}
|
|
});
|
|
console->Out() << "bilicraft-bot | Minecraft Java " << kGameVersion << " | " << config.server << '\n';
|
|
BilicraftClient client;
|
|
if (stopRequested) return 0;
|
|
client.ConnectMicrosoft(config.server, config.account);
|
|
if (stopRequested) return 0;
|
|
// Authentication is synchronous upstream. Only the subsequent login wait
|
|
// and game execution can cooperate with cancellation.
|
|
const auto loginDeadline = Clock::now() + 60s;
|
|
while (!stopRequested && !client.WasDisconnected() && !client.HasEnteredPlay())
|
|
{
|
|
if (Clock::now() >= loginDeadline)
|
|
throw std::runtime_error("Timed out waiting to enter the game (60 seconds)");
|
|
std::this_thread::sleep_for(50ms);
|
|
}
|
|
if (stopRequested || client.WasDisconnected())
|
|
{
|
|
client.Disconnect();
|
|
return stopRequested ? 0 : 1;
|
|
}
|
|
|
|
ConsoleCommandParser commandParser;
|
|
ActionScheduler scheduler;
|
|
if (program) scheduler.Enqueue(std::move(*program));
|
|
console->Start();
|
|
bool eofReported = false;
|
|
bool actionFailed = false;
|
|
std::optional<Clock::time_point> drainedSince;
|
|
console->Out() << "Entered game. " << ConsoleHelp();
|
|
const auto printEvents = [&] {
|
|
for (const auto &event : scheduler.DrainEvents()) console->Out() << event << '\n';
|
|
console->Out().flush();
|
|
};
|
|
const auto pumpConsole = [&] {
|
|
scheduler.WakeReady(Clock::now());
|
|
console->SetInputEnabled(!scheduler.InteractivePending() && !console->IsEof() && !stopRequested);
|
|
console->Tick();
|
|
if (scheduler.InteractivePending() || console->IsEof() || stopRequested) return;
|
|
try
|
|
{
|
|
const auto line = console->PollLine();
|
|
if (!line) return;
|
|
const auto request = commandParser.Parse(*line);
|
|
switch (request.kind)
|
|
{
|
|
case ConsoleKind::Empty: break;
|
|
case ConsoleKind::Display: console->Out() << request.argument; break;
|
|
case ConsoleKind::Help: console->Out() << ConsoleHelp(); break;
|
|
case ConsoleKind::Quit: stopRequested = 1; break;
|
|
case ConsoleKind::Run:
|
|
scheduler.Enqueue(LoadActionFile(request.argument, commandParser.GetBindings()));
|
|
break;
|
|
case ConsoleKind::Tasks:
|
|
{
|
|
const auto now = Clock::now();
|
|
const auto tasks = scheduler.Tasks();
|
|
if (tasks.empty()) console->Out() << "No queued actions.\n";
|
|
for (const auto &task : tasks)
|
|
{
|
|
console->Out() << '#' << task.id << " '" << task.name << "' "
|
|
<< (task.state == ActionScheduler::State::Blocked ? "blocked" :
|
|
task.state == ActionScheduler::State::Running ? "running" : "ready")
|
|
<< " command " << task.nextCommand << '/' << task.commandCount;
|
|
if (task.state == ActionScheduler::State::Blocked)
|
|
console->Out() << " remaining=" << std::max<std::int64_t>(0,
|
|
std::chrono::duration_cast<std::chrono::milliseconds>(task.wakeAt - now).count())
|
|
<< "ms";
|
|
console->Out() << '\n';
|
|
}
|
|
break;
|
|
}
|
|
case ConsoleKind::Action:
|
|
scheduler.SubmitInteractive(*request.action);
|
|
console->SetInputEnabled(false);
|
|
console->Out() << "Interactive command pending (runs at the next action boundary).\n";
|
|
break;
|
|
}
|
|
printEvents();
|
|
}
|
|
catch (const std::exception &error)
|
|
{
|
|
console->Err() << "Console: " << error.what() << '\n';
|
|
}
|
|
};
|
|
printEvents();
|
|
while (!stopRequested && !client.WasDisconnected())
|
|
{
|
|
pumpConsole();
|
|
if (stopRequested) break;
|
|
const auto work = scheduler.Next(Clock::now());
|
|
printEvents();
|
|
if (work)
|
|
{
|
|
drainedSince.reset();
|
|
const auto commandDeadline = Clock::now() + 60s;
|
|
client.SetActionYieldHandler([&client, &pumpConsole, commandDeadline] {
|
|
pumpConsole();
|
|
if (stopRequested) throw std::runtime_error("Action cancelled");
|
|
if (client.WasDisconnected()) throw std::runtime_error("Server disconnected during action");
|
|
if (Clock::now() >= commandDeadline)
|
|
throw std::runtime_error("Action command timed out (60 seconds)");
|
|
std::this_thread::sleep_for(10ms);
|
|
});
|
|
try
|
|
{
|
|
client.Yield();
|
|
if (ExecuteAction(client, work->command) != Botcraft::Status::Success)
|
|
throw std::runtime_error(work->command.source.string() + ":" +
|
|
std::to_string(work->command.line) + ": action command failed");
|
|
scheduler.Finish(true);
|
|
}
|
|
catch (const std::exception &error)
|
|
{
|
|
console->Err() << "Execution failed: " << error.what() << '\n';
|
|
scheduler.Finish(false);
|
|
if (!work->interactive) actionFailed = true;
|
|
}
|
|
client.SetActionYieldHandler({});
|
|
printEvents();
|
|
continue;
|
|
}
|
|
if (console->IsEof() && !eofReported)
|
|
{
|
|
console->Out() << "Console input closed; draining queued actions before disconnect.\n";
|
|
eofReported = true;
|
|
}
|
|
if (console->IsEof() && !scheduler.HasWork())
|
|
{
|
|
// Best-effort grace for upstream's asynchronous send queue; it
|
|
// provides no flush API. Do not disconnect on the last Send().
|
|
if (!drainedSince) drainedSince = Clock::now();
|
|
if (Clock::now() - *drainedSince >= 500ms) break;
|
|
}
|
|
auto sleep = 50ms;
|
|
if (const auto wake = scheduler.NextWake())
|
|
sleep = std::clamp(std::chrono::duration_cast<std::chrono::milliseconds>(*wake - Clock::now()),
|
|
0ms, sleep);
|
|
std::this_thread::sleep_for(sleep);
|
|
}
|
|
const bool disconnected = client.WasDisconnected();
|
|
client.SetActionYieldHandler({});
|
|
client.Disconnect();
|
|
return stopRequested ? 0 : (disconnected || actionFailed ? 1 : 0);
|
|
}
|
|
catch (const std::exception &error)
|
|
{
|
|
std::cerr << "bilicraft-bot failed: " << error.what() << '\n';
|
|
return stopRequested ? 0 : 1;
|
|
}
|
|
}
|