added a SHIT ton of modules

This commit is contained in:
st committed 2026-10-14 00:10:39 -05:00
1 parent b1634d195c
commit 361892bf0b
64 files changed
+5327 -463

No files matched your search

+33
View File
@@ -160,8 +160,16 @@
<ClCompile Include="..\vendor\minhook\src\hook.c" />
<ClCompile Include="..\vendor\minhook\src\trampoline.c" />
<ClCompile Include="main.cc" />
<ClCompile Include="font_data.cc" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="game\world.h" />
<ClInclude Include="game\world_math.h" />
<ClInclude Include="game\world_filter.h" />
<ClInclude Include="gui\hud_card.h" />
<ClInclude Include="modules\world_modules.h" />
<ClInclude Include="config\profiles.h" />
<ClInclude Include="config\save_bridge.h" />
<ClInclude Include="game\hook.h" />
<ClInclude Include="game\signatures.h" />
<ClInclude Include="game\sigscan.h" />
@@ -171,10 +179,32 @@
<ClInclude Include="gui\widgets.h" />
<ClInclude Include="input.h" />
<ClInclude Include="modules\crosshair.h" />
<ClInclude Include="modules\crosshair_animation.h" />
<ClInclude Include="modules\fps_counter.h" />
<ClInclude Include="modules\fullbright.h" />
<ClInclude Include="modules\fov_changer.h" />
<ClInclude Include="modules\zoom.h" />
<ClInclude Include="modules\glint_changer.h" />
<ClInclude Include="modules\music_player.h" />
<ClInclude Include="modules\inventory_tools.h" />
<ClInclude Include="modules\anti_afk.h" />
<ClInclude Include="modules\server_hud.h" />
<ClInclude Include="modules\anti_afk_engine.h" />
<ClInclude Include="game\inventory_tools.h" />
<ClInclude Include="game\media.h" />
<ClInclude Include="modules\viewmodel.h" />
<ClInclude Include="modules\toggle_sprint.h" />
<ClInclude Include="modules\cps_counter.h" />
<ClInclude Include="modules\clock.h" />
<ClInclude Include="modules\text_hud.h" />
<ClInclude Include="modules\sprint_latch.h" />
<ClInclude Include="game\viewmodel_math.h" />
<ClInclude Include="modules\keystrokes.h" />
<ClInclude Include="modules\macro.h" />
<ClInclude Include="modules\villager_trade.h" />
<ClInclude Include="modules\trade_io.h" />
<ClInclude Include="modules\trade_profile.h" />
<ClInclude Include="gui\notifications.h" />
<ClInclude Include="modules\module.h" />
<ClInclude Include="modules\module_manager.h" />
<ClInclude Include="modules\optimizations.h" />
@@ -184,4 +214,7 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<ItemGroup>
<ClInclude Include="gui\hud_editor.h" />
</ItemGroup>
</Project>
+34
View File
@@ -53,6 +53,13 @@
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="game\world.h" />
<ClInclude Include="game\world_math.h" />
<ClInclude Include="game\world_filter.h" />
<ClInclude Include="gui\hud_card.h" />
<ClInclude Include="modules\world_modules.h" />
<ClInclude Include="config\profiles.h" />
<ClInclude Include="config\save_bridge.h" />
<ClInclude Include="modules\module.h" />
<ClInclude Include="modules\module_manager.h" />
<ClInclude Include="modules\fps_counter.h" />
@@ -62,14 +69,41 @@
<ClInclude Include="gui\theme.h" />
<ClInclude Include="modules\setting.h" />
<ClInclude Include="modules\crosshair.h" />
<ClInclude Include="modules\crosshair_animation.h" />
<ClInclude Include="gui\fonts.h" />
<ClInclude Include="gui\widgets.h" />
<ClInclude Include="modules\watermark.h" />
<ClInclude Include="modules\optimizations.h" />
<ClInclude Include="modules\macro.h" />
<ClInclude Include="modules\villager_trade.h" />
<ClInclude Include="modules\trade_io.h" />
<ClInclude Include="modules\trade_profile.h" />
<ClInclude Include="gui\notifications.h" />
<ClInclude Include="game\sigscan.h" />
<ClInclude Include="game\hook.h" />
<ClInclude Include="game\signatures.h" />
<ClInclude Include="modules\fullbright.h" />
<ClInclude Include="modules\fov_changer.h" />
<ClInclude Include="modules\zoom.h" />
<ClInclude Include="modules\glint_changer.h" />
<ClInclude Include="modules\music_player.h" />
<ClInclude Include="modules\inventory_tools.h" />
<ClInclude Include="modules\anti_afk.h" />
<ClInclude Include="modules\anti_afk_engine.h" />
<ClInclude Include="game\inventory_tools.h" />
<ClInclude Include="game\media.h" />
<ClInclude Include="modules\viewmodel.h" />
<ClInclude Include="modules\toggle_sprint.h" />
<ClInclude Include="modules\cps_counter.h" />
<ClInclude Include="modules\clock.h" />
<ClInclude Include="modules\text_hud.h" />
<ClInclude Include="modules\sprint_latch.h" />
<ClInclude Include="game\viewmodel_math.h" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="modules\server_hud.h" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="gui\hud_editor.h" />
</ItemGroup>
</Project>
+337
View File
@@ -0,0 +1,337 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <map>
#include <set>
#include <locale>
#include <cmath>
#include <algorithm>
#include "save_bridge.h"
#include "../modules/module_manager.h"
#include "../gui/notifications.h"
#include "../gui/hud_editor.h"
namespace config {
namespace fs = std::filesystem;
struct value {
int type = 0;
double numbers[4]{};
std::string mode;
};
struct module_state {
bool enabled = false;
int key = 0;
float x = 10, y = 10;
std::map<std::string, value> settings;
};
using snapshot = std::map<std::string, module_state>;
inline snapshot capture(module_manager& manager) {
snapshot result;
for (auto& m : manager.all()) {
auto& state = result[m->name()];
state.enabled = m->enabled(); state.key = m->toggle_key();
state.x = m->hud_pos.x; state.y = m->hud_pos.y;
for (auto& s : m->settings()) {
if (s.type == setting_type::action) continue;
auto& v = state.settings[s.name]; v.type = int(s.type);
if (s.type == setting_type::toggle) v.numbers[0] = s.bool_value;
else if (s.type == setting_type::slider_float) v.numbers[0] = s.float_value;
else if (s.type == setting_type::color) std::copy(s.color, s.color + 4, v.numbers);
else if (s.type != setting_type::text) v.numbers[0] = s.int_value;
if (s.type == setting_type::text) v.mode = s.text_value;
if (s.type == setting_type::mode && s.int_value >= 0 && s.int_value < int(s.modes.size()))
v.mode = s.modes[s.int_value];
}
}
auto& editor=result["[hud editor]"];
editor.settings["snap to grid"]={int(setting_type::toggle),{double(hud_editor::options.snap)}};
editor.settings["show grid"]={int(setting_type::toggle),{double(hud_editor::options.show_grid)}};
editor.settings["grid size"]={int(setting_type::slider_int),{double(hud_editor::options.grid_size)}};
return result;
}
inline std::string encode(const snapshot& data) {
std::ostringstream out; out.imbue(std::locale::classic());
out << "AMNESIA_PROFILE 1\n" << std::setprecision(9);
for (auto& entry : data) {
const auto& m = entry.second;
out << "module " << std::quoted(entry.first) << ' ' << m.enabled << ' ' << m.key << ' ' << m.x << ' ' << m.y << '\n';
for (auto& setting : m.settings) {
const auto& v = setting.second;
out << "setting " << std::quoted(entry.first) << ' ' << std::quoted(setting.first) << ' ' << v.type;
for (double number : v.numbers) out << ' ' << number;
out << ' ' << std::quoted(v.mode) << '\n';
}
}
out << "end\n"; return out.str();
}
inline bool decode(const std::string& text, snapshot& result) {
if (text.size() > 2 * 1024 * 1024) return false;
std::istringstream in(text); in.imbue(std::locale::classic());
std::string line; if (!std::getline(in, line) || line != "AMNESIA_PROFILE 1") return false;
snapshot parsed; bool ended = false;
while (std::getline(in, line)) {
if (line == "end") { ended = true; break; }
std::istringstream row(line); row.imbue(std::locale::classic());
std::string kind, name; if (!(row >> kind >> std::quoted(name)) || name.empty() || name.size() > 256) return false;
if (kind == "module") {
module_state state; int enabled;
if (!(row >> enabled >> state.key >> state.x >> state.y) || (enabled != 0 && enabled != 1) ||
state.key < 0 || state.key > 255 || !std::isfinite(state.x) || !std::isfinite(state.y) ||
std::abs(state.x) > 100000 || std::abs(state.y) > 100000 || parsed.count(name)) return false;
state.enabled = enabled != 0; parsed.emplace(name, state);
} else if (kind == "setting") {
std::string key; value v;
if (!(row >> std::quoted(key) >> v.type) || key.empty() || key.size() > 256 || !parsed.count(name) ||
v.type < 0 || v.type > int(setting_type::text) || v.type == int(setting_type::action)) return false;
for (auto& number : v.numbers) if (!(row >> number) || !std::isfinite(number) || std::abs(number) > 1e9) return false;
if (!(row >> std::quoted(v.mode)) || v.mode.size() > 256 || parsed[name].settings.count(key)) return false;
if ((v.type == int(setting_type::toggle) && v.numbers[0] != 0 && v.numbers[0] != 1) ||
((v.type == int(setting_type::slider_int) || v.type == int(setting_type::mode) || v.type == int(setting_type::keybind)) &&
v.numbers[0] != std::floor(v.numbers[0]))) return false;
parsed[name].settings.emplace(key, v);
} else return false;
row >> std::ws; if (!row.eof()) return false;
}
in >> std::ws;
if (!ended || !in.eof()) return false;
result = std::move(parsed); return true;
}
inline void apply(module_manager& manager, const snapshot& defaults, const snapshot& data) {
hud_editor::options={};
auto editor=defaults.find("[hud editor]");
auto loaded_editor=data.find("[hud editor]");
std::map<std::string,value> editor_values;
if(editor!=defaults.end())editor_values=editor->second.settings;
if(loaded_editor!=data.end())for(auto& entry:loaded_editor->second.settings)editor_values[entry.first]=entry.second;
auto toggle=[&](const char* name,bool& target) {
auto found=editor_values.find(name);
if(found!=editor_values.end() && found->second.type==int(setting_type::toggle))target=found->second.numbers[0]!=0;
};
toggle("snap to grid",hud_editor::options.snap);toggle("show grid",hud_editor::options.show_grid);
auto spacing=editor_values.find("grid size");
if(spacing!=editor_values.end() && spacing->second.type==int(setting_type::slider_int))
hud_editor::options.grid_size=int(std::clamp(spacing->second.numbers[0],4.0,64.0));
// Disabling first releases injected input and cancels macro countdowns/runs.
for (auto& m : manager.all()) m->set_enabled(false);
for (auto& m : manager.all()) {
auto original = defaults.find(m->name()); if (original == defaults.end()) continue;
module_state state = original->second;
auto loaded = data.find(m->name());
if (loaded != data.end()) {
state.enabled = loaded->second.enabled; state.key = loaded->second.key;
state.x = loaded->second.x; state.y = loaded->second.y;
for (auto& entry : loaded->second.settings) state.settings[entry.first] = entry.second;
}
m->set_toggle_key(state.key); m->hud_pos = ImVec2(state.x, state.y); m->ui.binding = false;
for (auto& s : m->settings()) {
s.binding = false;
auto found = state.settings.find(s.name);
if (found == state.settings.end() || found->second.type != int(s.type)) continue;
const auto& v = found->second;
switch (s.type) {
case setting_type::text: s.text_value = v.mode.substr(0, s.int_max); break;
case setting_type::toggle: s.bool_value = v.numbers[0] != 0; break;
case setting_type::slider_float: s.float_value = std::clamp(float(v.numbers[0]), s.float_min, s.float_max); break;
case setting_type::slider_int: s.int_value = std::clamp(int(v.numbers[0]), s.int_min, s.int_max); break;
case setting_type::keybind: s.int_value = std::clamp(int(v.numbers[0]), 0, 255); break;
case setting_type::color:
for (int i = 0; i < 4; ++i) s.color[i] = std::clamp(float(v.numbers[i]), 0.f, 1.f);
break;
case setting_type::mode: {
const auto mode = std::find(s.modes.begin(), s.modes.end(), v.mode);
s.int_value = mode != s.modes.end() ? int(mode - s.modes.begin()) : 0; break;
}
default: break;
}
}
}
for (auto& m : manager.all()) {
auto loaded = data.find(m->name()), original = defaults.find(m->name());
if (loaded != data.end()) m->set_enabled(loaded->second.enabled);
else if (original != defaults.end()) m->set_enabled(original->second.enabled);
}
}
inline std::string folded(std::string name) {
for (char& c : name) if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
return name;
}
inline bool valid_name(const std::string& name) {
if (name.empty() || name.size() > 48 || name.front() == ' ' || name.back() == ' ') return false;
for (unsigned char c : name)
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ' ' || c == '_' || c == '-')) return false;
const auto lower = folded(name);
if (lower == "con" || lower == "prn" || lower == "aux" || lower == "nul") return false;
if (lower.size() == 4 && (lower.substr(0, 3) == "com" || lower.substr(0, 3) == "lpt") && lower[3] >= '0' && lower[3] <= '9') return false;
return true;
}
inline fs::path directory() {
HMODULE dll = nullptr; wchar_t name[32768]{};
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&directory), &dll)) return {};
DWORD size = GetModuleFileNameW(dll, name, 32768);
return size && size < 32768 ? fs::path(std::wstring(name, size)).parent_path() / L"profiles" : fs::path{};
}
inline bool atomic_write(const fs::path& path, const std::string& text) {
auto temporary = path; temporary += L".tmp";
HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return false;
DWORD written = 0;
bool ok = WriteFile(file, text.data(), DWORD(text.size()), &written, nullptr) && written == text.size();
if (ok) ok = FlushFileBuffers(file) != FALSE;
if (!CloseHandle(file)) ok = false;
if (ok) ok = MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE;
if (!ok) DeleteFileW(temporary.c_str());
return ok;
}
inline bool read(const fs::path& path, snapshot& result) {
std::error_code ec;
auto size = fs::file_size(path, ec); if (ec || size > 2 * 1024 * 1024) return false;
std::ifstream file(path, std::ios::binary);
std::string text((std::istreambuf_iterator<char>(file)), {});
return file && decode(text, result);
}
class profile_manager {
public:
~profile_manager() { if (owns_bridge_) config_save::request = {}; }
void initialize(module_manager& manager, fs::path root = directory(), bool bridge = true) {
if (ready_) return;
manager_ = &manager; root_ = std::move(root); defaults_ = capture(manager); ready_ = true;
if (bridge) { config_save::request = [this] { return applying_ || closing_ ? true : writable_ && save(false); }; owns_bridge_ = true; }
std::error_code ec;
if (root_.empty()) { error("Could not find the client profile folder."); writable_ = false; return; }
fs::create_directories(root_, ec);
if (ec) { error("Cannot create the profiles folder beside the DLL."); writable_ = false; return; }
std::ifstream index(root_ / L"active.txt"); std::string requested;
if (std::getline(index, requested) && valid_name(requested)) active_ = requested;
refresh();
snapshot loaded;
// A removed last-used profile must not overwrite an existing Default.
if (!fs::exists(file(active_), ec)) active_ = "Default";
if (fs::exists(file(active_), ec)) {
if (read(file(active_), loaded)) {
applying_ = true; apply(manager, defaults_, loaded); applying_ = false;
baseline_ = encode(capture(manager)); observed_ = baseline_;
} else {
writable_ = false; error("Profile is damaged. Choose another profile or create a new one; the damaged file has been preserved.");
}
} else { active_ = "Default"; save(false); }
write_index(); refresh();
}
bool ready() const { return ready_; }
const std::string& active() const { return active_; }
const std::vector<std::string>& names() const { return names_; }
const std::string& last_error() const { return error_; }
bool dirty() const { return manager_ && encode(capture(*manager_)) != baseline_; }
bool blocked() const { return !writable_; }
bool save(bool report = true) {
if (!manager_ || root_.empty() || applying_ || closing_) return false;
const auto current = encode(capture(*manager_));
if (!atomic_write(file(active_), current)) { error("Could not save the profile. Check that the client folder is writable."); return false; }
writable_ = true; baseline_ = observed_ = current; error_.clear(); refresh();
if (report) message("Profile saved", active_);
return true;
}
void tick(double time) {
if (!ready_ || !manager_ || closing_) return;
const auto current = encode(capture(*manager_));
if (current != observed_) {
if (observed_ == baseline_) first_change_ = time;
observed_ = current; changed_at_ = time;
}
if (writable_ && current != baseline_ && time >= retry_at_ &&
(time - changed_at_ >= 0.75 || time - first_change_ >= 5.0)) {
if (!save(false)) retry_at_ = time + 5.0;
}
}
void shutdown() {
if (manager_ && writable_ && dirty()) save(false);
// Module shutdown must not fall back to the legacy macro INI.
closing_ = true;
}
bool create(const std::string& name) {
if (!check_new(name)) return false;
const auto state = encode(capture(*manager_));
if (writable_ && dirty() && !save(false)) return false;
if (!atomic_write(file(name), state)) { error("Could not create the profile."); return false; }
const auto current = capture(*manager_);
applying_ = true; apply(*manager_, defaults_, current); applying_ = false;
active_ = name; writable_ = true; baseline_ = observed_ = state; error_.clear();
write_index(); refresh(); message("Profile created", name); return true;
}
bool switch_to(const std::string& name) {
if (!valid_name(name) || name == active_) return name == active_;
snapshot loaded;
if (!read(file(name), loaded)) { error("Could not load this profile. Its file has been preserved."); return false; }
if (writable_ && dirty() && !save(false)) return false;
applying_ = true; apply(*manager_, defaults_, loaded); applying_ = false;
active_ = name; writable_ = true; baseline_ = observed_ = encode(capture(*manager_)); error_.clear();
write_index(); message("Profile loaded", name); return true;
}
bool rename(const std::string& name) {
if (folded(active_) == "default") { error("The Default profile cannot be renamed."); return false; }
if (!check_new(name) || !save(false)) return false;
if (!MoveFileExW(file(active_).c_str(), file(name).c_str(), MOVEFILE_WRITE_THROUGH)) { error("Could not rename the profile."); return false; }
active_ = name; error_.clear(); write_index(); refresh(); message("Profile renamed", name); return true;
}
bool remove_active() {
if (folded(active_) == "default" || names_.size() < 2) { error("Keep at least one profile. Default cannot be deleted."); return false; }
const auto old = active_;
const auto choices = names_;
for (const auto& name : choices) {
if (name != old && switch_to(name)) {
if (!DeleteFileW(file(old).c_str())) { error("Could not delete the profile."); return false; }
refresh(); message("Profile deleted", old); return true;
}
}
return false;
}
void refresh() {
names_.clear(); std::error_code ec;
fs::directory_iterator it(root_, ec), end;
while (!ec && it != end) {
const auto& path = it->path();
if (it->is_regular_file(ec) && path.extension() == L".profile") {
const auto native = path.stem().wstring();
if (std::all_of(native.begin(), native.end(), [](wchar_t c) { return c > 0 && c < 128; })) {
std::string name;
for (wchar_t c : native) name.push_back(static_cast<char>(c));
if (valid_name(name)) names_.push_back(name);
}
}
it.increment(ec);
}
std::sort(names_.begin(), names_.end(), [](const auto& a, const auto& b) { return folded(a) < folded(b); });
}
private:
module_manager* manager_ = nullptr;
fs::path root_; snapshot defaults_;
std::string active_ = "Default", baseline_, observed_, error_;
std::vector<std::string> names_;
double first_change_ = 0, changed_at_ = 0, retry_at_ = 0;
bool ready_ = false, writable_ = true, applying_ = false, closing_ = false, owns_bridge_ = false;
fs::path file(const std::string& name) const { return root_ / fs::path(name + ".profile"); }
bool check_new(const std::string& name) {
if (!manager_ || root_.empty()) { error("No profile folder is available."); return false; }
if (!valid_name(name)) { error("Use 1-48 letters, numbers, spaces, underscores or hyphens. Reserved Windows names are unavailable."); return false; }
refresh();
for (auto& existing : names_) if (folded(existing) == folded(name)) { error("A profile with that name already exists."); return false; }
return true;
}
void write_index() {
if (!atomic_write(root_ / L"active.txt", active_ + "\n")) error("Profile works now, but the active profile could not be remembered for next launch.");
}
void error(const std::string& text) {
if (error_ != text) notifications::push("Profile error", text, notifications::kind::error, 6, "profiles");
error_ = text;
}
static void message(const std::string& title, const std::string& body) {
notifications::push(title, body, notifications::kind::success, 3, "profiles");
}
};
}
inline config::profile_manager& profiles() { static config::profile_manager instance; return instance; }
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <functional>
// Modules can request a save without depending on the profile manager or GUI.
namespace config_save {
inline std::function<bool()> request;
}
+3
View File
@@ -0,0 +1,3 @@
#include "font_data.h"
const unsigned char* amnesia_fallback_font() { return k_font_data; }
int amnesia_fallback_font_size() { return static_cast<int>(k_font_size); }
+9 -6
View File
@@ -13,11 +13,12 @@ namespace game {
class game_hook {
public:
// creates the hook DISABLED; returns false if the signature is empty or not found
bool install(const char* name, const char* signature, void* detour, void** original) {
bool install(const char* name, const char* signature, void* detour, void** original,
bool require_unique = false) {
if (!signature || !*signature) { log(std::string(name) + ": no signature set"); return false; }
uint8_t* addr = sigscan::find(signature);
if (!addr) { log(std::string(name) + ": signature not found (game updated?)"); return false; }
uint8_t* addr = sigscan::find(signature, require_unique);
if (!addr) { log(std::string(name) + ": signature missing or ambiguous (game updated?)"); return false; }
if (MH_CreateHook(addr, detour, original) != MH_OK) { log(std::string(name) + ": MH_CreateHook failed"); return false; }
@@ -27,10 +28,12 @@ namespace game {
}
bool ok() const { return target_ != nullptr; }
void* target() const { return target_; }
void set_enabled(bool on) {
if (!target_) return;
if (on) MH_EnableHook(target_); else MH_DisableHook(target_);
bool set_enabled(bool on) {
if (!target_) return false;
const MH_STATUS status = on ? MH_EnableHook(target_) : MH_DisableHook(target_);
return status == MH_OK || (on ? status == MH_ERROR_ENABLED : status == MH_ERROR_DISABLED);
}
private:
+220
View File
@@ -0,0 +1,220 @@
#pragma once
#include "world.h"
#include "../gui/notifications.h"
#include <deque>
namespace inventory_tools {
struct panel {std::string group;std::vector<world::item> items;};
struct snapshot {uintptr_t controller=0;uint64_t stamp=0;std::string hover;bool cursor=false,busy=false;world::item held;std::vector<panel> panels;};
enum class action {steal,dump,sort,stop};
struct request {uintptr_t controller;action operation;std::string group;};
inline std::atomic<bool> enabled{false},include_hotbar{false};
inline std::atomic<int> delay{75};
inline std::atomic<uint64_t> epoch{0};
inline std::mutex mutex;
inline snapshot published;
inline std::deque<request> requests;
inline bool ready=false;
using tick_fn=uint32_t(__fastcall*)(uintptr_t);
using item_fn=uintptr_t(__fastcall*)(uintptr_t,const std::string*,int);
using slot_fn=void(__fastcall*)(uintptr_t,const std::string*,int);
using auto_fn=void(__fastcall*)(uintptr_t,int,const std::string*,int);
inline tick_fn original_tick=nullptr;
inline item_fn get_item=nullptr;inline slot_fn swap_cursor=nullptr,place_all=nullptr;inline auto_fn auto_place=nullptr;
inline game::game_hook tick_hook;
inline snapshot latest(){std::lock_guard lock(mutex);return published;}
inline bool fresh(snapshot const& state){return state.controller && GetTickCount64()-state.stamp<150;}
inline void queue(action operation,std::string group="") {
std::lock_guard lock(mutex);
if(fresh(published) && requests.size()<4)requests.push_back({published.controller,operation,std::move(group)});
}
inline void reset(){++epoch;std::lock_guard lock(mutex);requests.clear();published={};}
inline bool playing_ui() {
// Bedrock can draw its own UI cursor while the Windows cursor is hidden.
// The live container tick/snapshot establishes whether a screen is open.
return enabled && !g_menu_open && is_game_focused();
}
inline int view_count(uintptr_t view) {
const auto getter=world::get<uintptr_t>(world::get<uintptr_t>(view)+4*8);
const std::array<uint8_t,7> expected{0x48,0x8b,0x81,0x08,0x01,0,0};
if(world::get<std::array<uint8_t,7>>(getter)!=expected)return -1;
const auto first=world::get<uintptr_t>(view+0x100),last=world::get<uintptr_t>(view+0x108);
if(!first || last<first || last-first>152*256 || (last-first)%152)return -1;
return int((last-first)/152);
}
inline uintptr_t group_view(uintptr_t model,std::string const& group) {
const auto head=world::get<uintptr_t>(model+0x30);
const auto size=world::get<uintptr_t>(model+0x38);if(!head || size>256)return 0;
auto node=world::get<uintptr_t>(head);
for(size_t i=0;i<size && node && node!=head;++i) {
if(world::string(node+0x10)==group) {
const auto holder=world::get<uintptr_t>(node+0x30),control=world::get<uintptr_t>(holder+0x10);
if(!control || world::get<int>(control+8)<=0)return 0;
return world::get<uintptr_t>(holder+8);
}
node=world::get<uintptr_t>(node);
}
return 0;
}
inline int guarded_count(uintptr_t model,const std::string* group){return view_count(group_view(model,*group));}
inline uintptr_t guarded_item(uintptr_t model,const std::string* group,int slot){__try{return get_item(model,group,slot);}__except(EXCEPTION_EXECUTE_HANDLER){return 0;}}
inline bool guarded_action(slot_fn fn,uintptr_t controller,const std::string* group,int slot) {
__try{fn(controller,group,slot);return true;}__except(EXCEPTION_EXECUTE_HANDLER){return false;}
}
inline const panel* find(snapshot const& state,std::string const& group){for(auto const& panel:state.panels)if(panel.group==group)return &panel;return nullptr;}
inline int next_minimum(std::vector<world::item> const& items,int index) {
int best=-1;
for(int i=index;i<int(items.size());++i)if(!items[i].name.empty() && (best<0 || items[i].name<items[best].name))best=i;
return best;
}
inline snapshot capture(uintptr_t controller) {
snapshot state;state.controller=controller;state.stamp=GetTickCount64();state.hover=world::string(controller+0x1098);
const auto model=world::get<uintptr_t>(controller+0x12c0);if(!model)return {};
for(const char* name:{"container_items","inventory_items","hotbar_items"}) {
const std::string group=name;const int count=guarded_count(model,&group);
if(count<=0 || count>54)continue;
panel panel;panel.group=group;
for(int i=0;i<count;++i)panel.items.push_back(world::read_item(guarded_item(model,&group,i)));
state.panels.push_back(std::move(panel));
}
const std::string cursor="cursor_items";
const int cursor_count=guarded_count(model,&cursor);
state.held=world::read_item(guarded_item(model,&cursor,0));
state.cursor=cursor_count!=1 || state.held.count>0;
if(state.panels.empty())return {};
const int hover_slot=world::get<int>(controller+0x10b8);
const auto* hovered=find(state,state.hover);
if(!hovered || hover_slot<0 || hover_slot>=int(hovered->items.size()))state.hover.clear();
return state;
}
struct engine {
uintptr_t controller=0;action operation=action::stop;std::string group;int index=0;
uint64_t due=0,wait_stamp=0;bool hotbar=false,awaiting=false;
std::string wait_group,wait_name;int wait_slot=0,wait_count=0;
enum class phase {idle,pickup,swap,putback,recover};
phase sort_phase=phase::idle;int sort_source=0,sort_destination=0;world::item sort_taken,sort_displaced;
uint64_t phase_stamp=0;
static bool same(world::item const& a,world::item const& b){return a.name==b.name && a.count==b.count;}
enum class stop_reason {none,completed,focus,controller,cursor,timeout,action_failed,requested,disabled};
stop_reason last_stop=stop_reason::none;
void cancel(stop_reason reason=stop_reason::completed){if(active())last_stop=reason;sort_phase=phase::idle;controller=0;operation=action::stop;group.clear();index=0;awaiting=false;}
void start(request const& request){last_stop=stop_reason::none;sort_phase=phase::idle;controller=request.controller;operation=request.operation;group=request.group;index=0;due=0;hotbar=false;awaiting=false;}
bool active() const{return controller && operation!=action::stop;}
void step(snapshot const& state,uint64_t now,bool eligible=playing_ui()) {
if(!active())return;
if(state.controller!=controller || !eligible){cancel(state.controller!=controller ? stop_reason::controller : stop_reason::focus);return;}
if(sort_phase!=phase::idle) {
if(now<due)return;
const auto* panel=find(state,group);
if(!panel || sort_source>=int(panel->items.size()) || sort_destination>=int(panel->items.size())){cancel();return;}
const bool timeout=now-phase_stamp>1500;
if(sort_phase==phase::pickup) {
if(same(state.held,sort_taken) && panel->items[sort_source].count==0) {
if(!guarded_action(place_all,controller,&group,sort_destination)){cancel(stop_reason::action_failed);notifications::push("Sorting stopped","The swap action failed.",notifications::kind::warning);return;}
sort_phase=phase::swap;phase_stamp=now;due=now+std::clamp(delay.load(),30,500);
} else if(timeout){cancel(stop_reason::timeout);notifications::push("Sorting stopped","Pick-up was not confirmed.",notifications::kind::warning);}
} else if(sort_phase==phase::swap) {
if(same(panel->items[sort_destination],sort_taken) && same(state.held,sort_displaced)) {
if(state.held.count) {
if(!guarded_action(place_all,controller,&group,sort_source)){cancel();return;}
sort_phase=phase::putback;phase_stamp=now;due=now+std::clamp(delay.load(),30,500);
} else {sort_phase=phase::idle;++index;}
} else if(timeout) {
if(same(state.held,sort_taken) && panel->items[sort_source].count==0) {
guarded_action(place_all,controller,&group,sort_source);sort_phase=phase::recover;phase_stamp=now;
} else {cancel();notifications::push("Sorting stopped","Place the held stack before trying again.",notifications::kind::warning);}
}
} else if(!state.cursor && same(panel->items[sort_source],sort_phase==phase::recover ? sort_taken : sort_displaced)) {
if(sort_phase==phase::recover){cancel();notifications::push("Sorting stopped","The swap was declined; the stack was returned.",notifications::kind::warning);}
else {sort_phase=phase::idle;++index;}
} else if(timeout){cancel(stop_reason::timeout);notifications::push("Sorting stopped","Place the held stack before trying again.",notifications::kind::warning);}
return;
}
if(state.cursor){cancel(stop_reason::cursor);return;}
if(awaiting) {
const auto* panel=find(state,wait_group);
const bool unchanged=panel && wait_slot<int(panel->items.size()) && panel->items[wait_slot].name==wait_name && panel->items[wait_slot].count>=wait_count;
if(unchanged) {
if(now-wait_stamp>750){cancel();notifications::push("Transfer stopped","The destination may be full, or the server declined the transfer.",notifications::kind::warning);}
return;
}
awaiting=false;
}
if(now<due)return;due=now+std::clamp(delay.load(),30,500);
if(operation!=action::sort) {
group=operation==action::steal ? "container_items" : hotbar ? "hotbar_items" : "inventory_items";
const auto* source=find(state,group);
if(!find(state,"container_items")){cancel();return;}
if(!source || index>=int(source->items.size())) {
if(operation==action::dump && !hotbar && include_hotbar){hotbar=true;index=0;return;}
cancel();return;
}
const int slot=index++;const auto& item=source->items[slot];if(item.name.empty())return;
auto_place(controller,item.count,&group,slot);
awaiting=true;wait_group=group;wait_slot=slot;wait_count=item.count;wait_name=item.name;wait_stamp=now;
} else {
const auto* source=find(state,group);if(!source){cancel();return;}
while(index<int(source->items.size())) {
const int best=next_minimum(source->items,index);
if(best<0){cancel();return;}
if(best==index || source->items[best].name==source->items[index].name){++index;continue;}
// Full pickup and placement are separate native actions.
// Taking onto an occupied cursor cannot replace an unlike stack.
sort_source=best;sort_destination=index;sort_taken=source->items[best];sort_displaced=source->items[index];
if(!guarded_action(swap_cursor,controller,&group,best)){cancel();return;}
sort_phase=phase::pickup;phase_stamp=now;return;
}
cancel();
}
}
};
inline engine current;
inline uint32_t __fastcall tick_detour(uintptr_t controller) {
const auto result=original_tick(controller);
// A screen can tick more than one controller. Only the controller that
// owns the queued operation may advance or replace its snapshot.
if(current.active() && current.controller!=controller) {
const auto owned=latest();
if(owned.controller==current.controller && GetTickCount64()-owned.stamp<500)return result;
current.cancel(engine::stop_reason::controller);
}
static thread_local bool processing=false;
if(processing)return result;
struct processing_guard {bool& flag;processing_guard(bool& value):flag(value){flag=true;}~processing_guard(){flag=false;}} guard(processing);
static uint64_t observed_epoch=0;
const auto generation=epoch.load();if(generation!=observed_epoch){current.cancel();observed_epoch=generation;}
if(!enabled){current.cancel(engine::stop_reason::disabled);reset();return result;}
// Native transactions can stall a tick longer than the display freshness
// limit. The per-phase acknowledgement timeout governs an active sort.
auto state=capture(controller);
if(!playing_ui())current.cancel(engine::stop_reason::focus);
std::deque<request> pending;
{std::lock_guard lock(mutex);pending.swap(requests);}
for(auto const& request:pending)if(request.controller==controller) {
if(request.operation==action::stop)current.cancel(engine::stop_reason::requested);
else if(playing_ui() && !state.cursor && !current.active()) {
auto chosen=request;
if(chosen.operation==action::sort && chosen.group.empty())chosen.group=state.hover;
if(chosen.operation!=action::sort || chosen.group=="container_items" || chosen.group=="inventory_items")current.start(chosen);
}
}
current.step(state,GetTickCount64());state.busy=current.active();
{std::lock_guard lock(mutex);published=std::move(state);}
return result;
}
// Signatures are generated from independently inspected 26.52 functions.
inline constexpr const char* tick_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC C8 00 00 00 48 8D AC 24 80 00 00 00 0F 29 75 30 48 C7 45 28 FE FF FF FF 48 89 CE 48 8D B9 F8 11 00 00 C6 45 F8 00 48 81 C1 38 12 00 00 E8 AF 9F A7 FF 48 8D 4D B0 E8 E6 A1 A6 FF 48 8D 55 B0 48 89 F9 E8 9A 95 A6 FF 83 BE 04 0C 00 00 02 8B 86 30";
inline constexpr const char* item_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 83 EC 38 48 8D 6C 24 30 48 C7 45 00 FE FF FF FF 44 89 C6 48 89 D7 48 8B 5A 10 48 83 7A 18 10 72 03 48 8B 3F 48 85 DB 74 24 89 D8 83 E0 03 48 BA B3 01 00 00 00 01 00 00 48 83 FB 04 73 1E 49 B9 25 23 22 84 E4 9C F2 CB 45 31 C0 EB 62 49 BA 25 23 22 84";
inline constexpr const char* auto_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 48 01 00 00 48 8D AC 24 80 00 00 00 48 C7 85 C0 00 00 00 FE FF FF FF 44 89 CE 4C 89 C7 41 89 D6 48 89 CB 48 8B 01 48 8B 80 38 01 00 00 FF 15 96 05 30 0A 84 C0 0F 84 0F 04 00 00 4C 8D 7D 38 4C 89 F9 48 89 FA 41 89 F0 E8 A4 96 3B FE 48 8B 8B C0 12 00 00 48 8B 01 48 8B 40 40 4C 89 FA FF 15 65";
inline constexpr const char* swap_cursor_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 83 EC 68 48 8D 6C 24 60 48 C7 45 00 FE FF FF FF 44 89 C7 48 89 D3 48 89 CE 48 8B 01 48 8B 80 38 01 00 00 FF 15 52 12 30 0A 84 C0 0F 84 6E 02 00 00 4C 8D B6 48 10 00 00 48 83 BE 58 10 00 00 00 0F 95 C0 44 8B 8E 68 10 00 00 41 83 F9 FF 0F 95 C1 20 C1";
inline constexpr const char* place_signature="55 41 57 41 56 41 54 56 57 53 48 81 EC F0 00 00 00 48 8D AC 24 80 00 00 00 48 C7 45 68 FE FF FF FF 44 89 C7 48 89 D3 48 89 CE 48 8B 01 48 8B 80 38 01 00 00 FF 15 6E 0C 30 0A 84 C0 0F 84 8D 01 00 00 48 83 BE 58 10 00 00 00 74 55 83 BE 68 10 00 00 FF 74 4C 4C 8D B6 20 10 00 00 4C 8B BE 20";
inline void initialize() {
if(ready)return;
get_item=reinterpret_cast<item_fn>(sigscan::find(item_signature,true));
auto_place=reinterpret_cast<auto_fn>(sigscan::find(auto_signature,true));
swap_cursor=reinterpret_cast<slot_fn>(sigscan::find(swap_cursor_signature,true));
place_all=reinterpret_cast<slot_fn>(sigscan::find(place_signature,true));
ready=get_item && swap_cursor && place_all && auto_place &&
tick_hook.install("container tick",tick_signature,reinterpret_cast<void*>(&tick_detour),reinterpret_cast<void**>(&original_tick),true) && tick_hook.set_enabled(true);
}
}
+164
View File
@@ -0,0 +1,164 @@
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Media.Control.h>
#include <winrt/Windows.Storage.Streams.h>
#include <wincodec.h>
#include <wrl/client.h>
#include <memory>
#include <atomic>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <string>
#include <vector>
#include <algorithm>
#pragma comment(lib,"windowsapp.lib")
#pragma comment(lib,"windowscodecs.lib")
#pragma comment(lib,"ole32.lib")
namespace media {
struct artwork {unsigned width=0,height=0;std::vector<unsigned char> rgba;};
inline std::shared_ptr<const artwork> decode_art(std::vector<unsigned char>& bytes) {
using Microsoft::WRL::ComPtr;
if(bytes.empty() || bytes.size()>4*1024*1024)return {};
ComPtr<IWICImagingFactory> factory;ComPtr<IWICStream> stream;ComPtr<IWICBitmapDecoder> decoder;
ComPtr<IWICBitmapFrameDecode> frame;ComPtr<IWICBitmapScaler> scaler;ComPtr<IWICFormatConverter> converter;
if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory))) ||
FAILED(factory->CreateStream(&stream)) || FAILED(stream->InitializeFromMemory(bytes.data(),DWORD(bytes.size()))) ||
FAILED(factory->CreateDecoderFromStream(stream.Get(),nullptr,WICDecodeMetadataCacheOnLoad,&decoder)) ||
FAILED(decoder->GetFrame(0,&frame)))return {};
UINT w=0,h=0;if(FAILED(frame->GetSize(&w,&h)) || !w || !h || w>16384 || h>16384)return {};
const double scale=(std::min)(1.,256./(std::max)(w,h));
w=(std::max)(1u,unsigned(w*scale));h=(std::max)(1u,unsigned(h*scale));
if(FAILED(factory->CreateBitmapScaler(&scaler)) || FAILED(scaler->Initialize(frame.Get(),w,h,WICBitmapInterpolationModeFant)) ||
FAILED(factory->CreateFormatConverter(&converter)) || FAILED(converter->Initialize(scaler.Get(),GUID_WICPixelFormat32bppRGBA,
WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom)))return {};
auto result=std::make_shared<artwork>();result->width=w;result->height=h;result->rgba.resize(w*h*4);
if(FAILED(converter->CopyPixels(nullptr,w*4,UINT(result->rgba.size()),result->rgba.data())))return {};
return result;
}
struct snapshot {
bool available=false,playing=false,previous=false,next=false,pause=false;
std::string title,artist,app,message="Looking for a media player...";
std::vector<std::string> players;
double position=0,duration=0,rate=1;uint64_t stamp=0;
std::shared_ptr<const artwork> art;
};
enum class command {previous,pause,next};
struct request {command action;std::string app;};
class reader {
public:
~reader(){stop();}
void start(){if(worker_.joinable())return;stopping_=false;worker_=std::thread([this]{run();});}
void stop(){stopping_=true;wake_.notify_all();if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_);commands_.clear();state_={};}
snapshot latest(){std::lock_guard lock(mutex_);return state_;}
void prefer(const std::string& app){std::lock_guard lock(mutex_);preferred_=app;}
void send(command action){std::lock_guard lock(mutex_);if(state_.available && commands_.size()<8){commands_.push_back({action,state_.app});wake_.notify_all();}}
private:
std::thread worker_;std::atomic<bool> stopping_{false};std::mutex mutex_;std::condition_variable wake_;
snapshot state_;std::string preferred_;std::deque<request> commands_;
template<class Operation> bool finish(Operation const& op) {
using winrt::Windows::Foundation::AsyncStatus;
const auto deadline=GetTickCount64()+3000;
while(op.Status()==AsyncStatus::Started) {
if(stopping_ || GetTickCount64()>deadline){op.Cancel();return false;}
std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(20),[this]{return stopping_.load();});
}
if(!stopping_ && op.Status()==AsyncStatus::Error)op.GetResults();
return !stopping_ && op.Status()==AsyncStatus::Completed;
}
static std::string utf8(winrt::hstring const& value) {return winrt::to_string(value);}
void publish(snapshot state){std::lock_guard lock(mutex_);state_=std::move(state);}
void run() {
using namespace winrt::Windows::Media::Control;
bool initialized=false;
try {
winrt::init_apartment(winrt::apartment_type::multi_threaded);initialized=true;
{
auto pending=GlobalSystemMediaTransportControlsSessionManager::RequestAsync();
if(!finish(pending))throw winrt::hresult_error(E_ABORT);
auto manager=pending.GetResults();std::string art_key;
std::shared_ptr<const artwork> cover;uint64_t art_attempt=0;
while(!stopping_) {
try {
snapshot result;result.message.clear();std::string preferred;std::deque<request> commands;
{std::lock_guard lock(mutex_);preferred=preferred_;commands.swap(commands_);}
auto sessions=manager.GetSessions();auto selected=manager.GetCurrentSession();
for(auto const& session:sessions) {
const auto app=utf8(session.SourceAppUserModelId());result.players.push_back(app);
if(!preferred.empty() && app==preferred)selected=session;
}
if(!preferred.empty() && (!selected || utf8(selected.SourceAppUserModelId())!=preferred))selected=nullptr;
if(selected) {
result.app=utf8(selected.SourceAppUserModelId());
for(auto const& command:commands) {
// A queued click must never control a different player after a session switch.
if(command.app!=result.app || stopping_)continue;
auto op=command.action==media::command::previous ? selected.TrySkipPreviousAsync() :
command.action==media::command::next ? selected.TrySkipNextAsync() : selected.TryTogglePlayPauseAsync();
if(finish(op) && !op.GetResults())result.message="Player declined that control";
}
auto properties=selected.TryGetMediaPropertiesAsync();
if(!finish(properties))throw winrt::hresult_error(E_ABORT);
auto info=properties.GetResults();
result.title=utf8(info.Title());result.artist=utf8(info.Artist());
const auto key=result.app+"\n"+result.title+"\n"+result.artist+"\n"+utf8(info.AlbumTitle());
if(key!=art_key || (!cover && GetTickCount64()-art_attempt>10000)) {
art_key=key;cover.reset();art_attempt=GetTickCount64();
try {
if(auto thumbnail=info.Thumbnail()) {
auto opening=thumbnail.OpenReadAsync();
if(finish(opening)) {
auto stream=opening.GetResults();const auto size=stream.Size();
if(size>0 && size<=4*1024*1024) {
auto data=winrt::Windows::Storage::Streams::DataReader(stream);
auto loading=data.LoadAsync(uint32_t(size));
if(finish(loading) && loading.GetResults()==size) {
std::vector<unsigned char> bytes(size);data.ReadBytes(bytes);cover=decode_art(bytes);
}
}
}
}
} catch(winrt::hresult_error const&) {cover.reset();}
}
result.art=cover;
auto playback=selected.GetPlaybackInfo();auto controls=playback.Controls();
result.playing=playback.PlaybackStatus()==GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing;
result.previous=controls.IsPreviousEnabled();result.next=controls.IsNextEnabled();
result.pause=controls.IsPlayPauseToggleEnabled();
if(auto rate=playback.PlaybackRate())result.rate=std::clamp(rate.Value(),0.,16.);
const auto time=selected.GetTimelineProperties();
const double start=double(time.StartTime().count())/1e7;
result.duration=(std::max)(0.,double(time.EndTime().count())/1e7-start);
result.position=std::clamp(double(time.Position().count())/1e7-start,0.,result.duration);
if(result.playing) {
const double elapsed=double((winrt::clock::now()-time.LastUpdatedTime()).count())/1e7;
if(elapsed>=0 && elapsed<86400)result.position=std::clamp(result.position+elapsed*result.rate,0.,result.duration);
}
result.available=true;result.stamp=GetTickCount64();
if(result.title.empty())result.title="Untitled track";
} else result.message=preferred.empty() ? "No active media session" : "Selected player is unavailable";
publish(std::move(result));
} catch(winrt::hresult_error const& error) {
if(!stopping_) {snapshot result;result.message="Media unavailable: "+utf8(error.message());publish(std::move(result));}
}
std::unique_lock lock(mutex_);
wake_.wait_for(lock,std::chrono::milliseconds(500),[this]{return stopping_ || !commands_.empty();});
}
}
} catch(winrt::hresult_error const& error) {
if(!stopping_){snapshot result;result.message="Windows media access unavailable: "+utf8(error.message());publish(std::move(result));}
} catch(...) {
snapshot result;result.message="Windows media access unavailable";publish(std::move(result));
}
if(initialized)winrt::uninit_apartment();
}
};
// Explicit lifetime: joining a COM worker from a DLL static destructor
// would run under the loader lock. The exported unload path owns shutdown.
inline reader* instance=nullptr;
inline reader& system(){if(!instance)instance=new reader;return *instance;}
inline void shutdown(){delete instance;instance=nullptr;}
}
+52
View File
@@ -5,6 +5,58 @@
// These are specific to one game version and must be re-found after every update.
namespace sigs {
// CursorRenderer::render in 1.26.5203.0. Identified from the cursor_renderer
// factory/vtable; body constructs "ui_crosshair". Four pointer arguments, void return.
inline constexpr const char* render_native_crosshair =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 18 05 00 00 "
"48 8D AC 24 80 00 00 00 0F 29 BD 80 04 00 00 0F 29 B5 70 04 00 00 "
"48 C7 85 68 04 00 00 FE FF FF FF 4D 89 CE 4C 89 C6 48 89 D3 48 89 CF";
// 26.52 first-person ItemInHandRenderer render entry, RVA 0x47ca240.
inline constexpr const char* render_hands =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 18 02 00 00 "
"48 8D AC 24 80 00 00 00 44 0F 29 BD 80 01 00 00 "
"44 0F 29 B5 70 01 00 00 44 0F 29 AD 60 01 00 00 "
"44 0F 29 A5 50 01 00 00 44 0F 29 9D 40 01 00 00 "
"44 0F 29 95 30 01 00 00 44 0F 29 8D 20 01 00 00 "
"44 0F 29 85 10 01 00 00 0F 29 BD 00 01 00 00 0F 29 B5 F0 00 00 00 "
"48 C7 85 E8 00 00 00 FE FF FF FF 44 88 4D 7F 4D 89 C7 "
"48 89 D3 48 89 CE 48 8B 89 70 01 00 00 48 8B 01 48 8B 80 F8 00 00 00";
// Shared item draw entry, RVA 0x47b5ba0. Filter to the offhand call below.
inline constexpr const char* render_offhand_item =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC D8 03 00 00 "
"48 8D AC 24 80 00 00 00 44 0F 29 8D 40 03 00 00 "
"44 0F 29 85 30 03 00 00 0F 29 BD 20 03 00 00 "
"0F 29 B5 10 03 00 00 48 C7 85 08 03 00 00 FE FF FF FF "
"41 80 79 23 01";
// Offhand item from Player's second hand slot (+0xf0), inside render_hands.
// The E8 is at +13 and its return address is at +18 (RVA 0x47ceee5).
inline constexpr const char* offhand_draw_call =
"48 89 F9 48 8B 55 F8 49 89 F0 4D 89 F1 E8 ?? ?? ?? ?? "
"C6 85 E0 00 00 00 00 C7 85 88 00 00 00 00 00 00 00";
// 1.26.5203.0, RVA 0x46bda60. Sole direct caller is the first-person
// projection path (getFov(..., false)); RDX is a writable float[16], XMM2 is alpha.
inline constexpr const char* hand_bob =
"55 56 57 53 48 81 EC 28 01 00 00 48 8D AC 24 80 00 00 00 "
"44 0F 29 BD 90 00 00 00 44 0F 29 B5 80 00 00 00 "
"44 0F 29 6D 70 44 0F 29 65 60 44 0F 29 5D 50 "
"44 0F 29 55 40 44 0F 29 4D 30 44 0F 29 45 20 "
"0F 29 7D 10 0F 29 75 00 48 C7 45 F8 FE FF FF FF "
"0F 28 FA 48 89 D6 48 8B 89 68 11 00 00";
// GameRenderer::getFov(void* renderer, float frame_alpha, bool world_projection).
// Verified in the running 1.26.5203.0 executable: reads video.fov (option 0x2f),
// returns degrees, and clamps vanilla FOV to [5, 130]. Unique function entry.
inline constexpr const char* get_fov =
"56 57 53 48 83 EC 60 "
"44 0F 29 44 24 50 0F 29 7C 24 40 0F 29 74 24 30 "
"44 89 C3 0F 28 F1 48 89 CE 45 84 C0 "
"0F 84 ?? ?? ?? ?? "
"48 8B 86 88 11 00 00 48 8B 88 F8 03 00 00 "
"48 8B 01 48 8B 80 D8 00 00 00 "
"48 8D 54 24 28 41 B8 2F 00 00 00";
// a function that returns the brightness setting as a float
inline constexpr const char* get_gamma =
"48 8B 49 58 66 66 66 2E 0F 1F 84 00 00 00 00 00 "
+10 -3
View File
@@ -77,7 +77,7 @@ namespace sigscan {
}
// searches the executable sections of the game's main module
inline uint8_t* find(const char* ida_pattern) {
inline uint8_t* find(const char* ida_pattern, bool require_unique = false) {
pattern pat;
if (!parse(ida_pattern, pat)) return nullptr;
@@ -85,6 +85,7 @@ namespace sigscan {
auto* dos = (IMAGE_DOS_HEADER*)base;
auto* nt = (IMAGE_NT_HEADERS*)(base + dos->e_lfanew);
const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
uint8_t* found = nullptr;
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue;
@@ -100,12 +101,18 @@ namespace sigscan {
const bool readable = mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD));
if (readable) {
if (uint8_t* hit = scan_range(p, region_end, pat)) return hit;
uint8_t* next = p;
while (uint8_t* hit = scan_range(next, region_end, pat)) {
if (!require_unique) return hit;
if (found) return nullptr;
found = hit;
next = hit + 1;
}
}
p = region_end;
}
}
return nullptr;
return found;
}
// for patterns that land on a RIP-relative instruction (e.g. a call or lea):
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include <cmath>
#include <cstring>
namespace game {
inline void multiply_matrix(const float* a, const float* b, float* out) {
float result[16]{};
for (int col = 0; col < 4; ++col)
for (int row = 0; row < 4; ++row)
for (int k = 0; k < 4; ++k) result[col*4+row] += a[k*4+row] * b[col*4+k];
std::memcpy(out, result, sizeof(result));
}
inline bool inverse_matrix(const float* matrix, float* inverse) {
double rows[4][8]{};
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
if (!std::isfinite(matrix[c*4+r])) return false;
rows[r][c] = matrix[c*4+r];
}
rows[r][4+r] = 1;
}
for (int col = 0; col < 4; ++col) {
int pivot = col;
for (int r = col+1; r < 4; ++r)
if (std::fabs(rows[r][col]) > std::fabs(rows[pivot][col])) pivot = r;
if (std::fabs(rows[pivot][col]) < 1.e-10) return false;
for (int c = 0; c < 8; ++c) { const double v = rows[col][c]; rows[col][c] = rows[pivot][c]; rows[pivot][c] = v; }
const double divisor = rows[col][col];
for (double& v : rows[col]) v /= divisor;
for (int r = 0; r < 4; ++r) {
if (r == col) continue;
const double factor = rows[r][col];
for (int c = 0; c < 8; ++c) rows[r][c] -= factor * rows[col][c];
}
}
for (int r = 0; r < 4; ++r) for (int c = 0; c < 4; ++c)
inverse[c*4+r] = static_cast<float>(rows[r][4+c]);
return true;
}
// Verified 26.52: BaseActorRenderContext+0x28 -> render context+0x18 ->
// ScreenContext. World MatrixStack has a deque of one matrix per block at +0x80.
inline float* viewmodel_world_matrix(void* actor_context, unsigned char** screen_out = nullptr) {
if (!actor_context) return nullptr;
auto* render = *reinterpret_cast<unsigned char**>(static_cast<unsigned char*>(actor_context) + 0x28);
if (!render) return nullptr;
auto* screen = *reinterpret_cast<unsigned char**>(render + 0x18);
if (!screen) return nullptr;
auto** map = *reinterpret_cast<float***>(screen + 0x88);
const size_t capacity = *reinterpret_cast<size_t*>(screen + 0x90);
const size_t first = *reinterpret_cast<size_t*>(screen + 0x98);
const size_t size = *reinterpret_cast<size_t*>(screen + 0xa0);
if (!map || !capacity || capacity > 65536 || (capacity & (capacity-1)) || !size) return nullptr;
if (screen_out) *screen_out = screen;
return map[(first + size - 1) & (capacity - 1)];
}
class viewmodel_matrix_scope {
public:
explicit viewmodel_matrix_scope(void* context) : matrix(viewmodel_world_matrix(context, &screen_)) {
if (matrix) std::memcpy(saved, matrix, sizeof(saved));
}
~viewmodel_matrix_scope() {
if (matrix) { std::memcpy(matrix, saved, sizeof(saved)); dirty(); }
}
void dirty() { if (screen_) screen_[0xb8] = 1; }
float* matrix;
float saved[16]{};
private:
unsigned char* screen_ = nullptr;
};
// Render matrices are column-major float[16].
inline void transform_viewmodel(float* matrix, const float* translation, const float* rotation) {
if (!matrix) return;
// Translate in the current local basis (M * T).
for (int row = 0; row < 4; ++row)
matrix[12 + row] += matrix[row] * translation[0] +
matrix[4 + row] * translation[1] + matrix[8 + row] * translation[2];
constexpr float radians = 0.017453292519943295f;
// Local pitch, yaw, roll: M * Rx * Ry * Rz. Translation remains the pivot.
const int first[] = {1, 2, 0}, second[] = {2, 0, 1};
for (int axis = 0; axis < 3; ++axis) {
if (rotation[axis] == 0.f) continue;
const float c = std::cos(rotation[axis] * radians), s = std::sin(rotation[axis] * radians);
for (int row = 0; row < 4; ++row) {
const int a = first[axis] * 4 + row, b = second[axis] * 4 + row;
const float old_a = matrix[a], old_b = matrix[b];
matrix[a] = old_a * c + old_b * s;
matrix[b] = old_b * c - old_a * s;
}
}
}
}
+417
View File
@@ -0,0 +1,417 @@
#pragma once
#include <windows.h>
#include <atomic>
#include <memory>
#include <mutex>
#include <vector>
#include <array>
#include <intrin.h>
#include "world_math.h"
#include "hook.h"
#include "../input.h"
// Verified 1.26.5203.0 read-only ECS access. Do not instantiate an external
// EnTT registry: Bedrock uses different sparse/payload page sizes.
namespace world {
inline constexpr const char* client_update_signature =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC F8 04 00 00 48 8D AC 24 80 00 00 00 "
"48 C7 85 70 04 00 00 FE FF FF FF 89 D3 48 89 CE 48 8B 01 48 8B 80 68 0C 00 00";
inline constexpr const char* camera_matrix_signature =
"41 57 41 56 41 54 56 57 53 48 81 EC 08 01 00 00 44 0F 29 AC 24 F0 00 00 00 "
"44 0F 29 A4 24 E0 00 00 00 44 0F 29 9C 24 D0 00 00 00";
inline constexpr const char* active_camera_signature =
"48 8D 7B 30 48 89 F9 BA 2B 77 9E 11 E8 ?? ?? ?? ?? 48 8B 48 20 48 39 48 28 74 74 8B 01";
inline constexpr const char* time_signature =
"48 63 C2 48 69 C8 F1 19 76 05 48 89 CA 48 C1 EA 3F 48 C1 F9 29 01 D1 69 C9 C0 5D 00 00 29 C8 F3 0F 2A C0 F3 0F 58 C2";
inline constexpr const char* name_signature =
"56 48 83 EC 20 48 8B 81 28 01 00 00 48 85 C0 74 4A 8B 50 08 48 8B 08 29 CA "
"81 E2 F8 FF 07 00 48 8D 05 ?? ?? ?? ?? 83 FA 21 72 2A 48 8B 71 20";
inline constexpr const char* fog_signature =
"48 89 D0 41 0F 10 00 0F 11 02 F3 0F 10 05 ?? ?? ?? ?? F3 0F 59 C3 F3 0F 58 05 ?? ?? ?? ?? "
"F3 0F 10 0A F3 0F 59 C8 F3 0F 11 0A F3 0F 59 42 04 F3 0F 11 42 04";
template<class T> inline bool read(uintptr_t address, T& out) {
if (address<0x10000 || address>0x7fffffffffff-sizeof(T)) return false;
__try { memcpy(&out,reinterpret_cast<const void*>(address),sizeof(T));return true; }
__except(EXCEPTION_EXECUTE_HANDLER) {return false;}
}
template<class T> inline T get(uintptr_t address) {T out{};read(address,out);return out;}
template<class T> inline bool write(uintptr_t address,const T& value) {
if(address<0x10000) return false;
__try {memcpy(reinterpret_cast<void*>(address),&value,sizeof(T));return true;}
__except(EXCEPTION_EXECUTE_HANDLER) {return false;}
}
inline constexpr uint32_t hash(const char* name) {
uint32_t value=2166136261u;for(;*name;++name) value=(value^uint8_t(*name))*16777619u;return value;
}
inline uintptr_t pool(uintptr_t registry,uint32_t type) {
const auto buckets=get<uintptr_t>(registry+0x48), bucket_end=get<uintptr_t>(registry+0x50);
const auto begin=get<uintptr_t>(registry+0x68), end=get<uintptr_t>(registry+0x70);
if (!buckets || bucket_end<=buckets || bucket_end-buckets>0x100000 || !begin || end<begin || end-begin>0x100000) return 0;
const size_t count=(bucket_end-buckets)/8, entries=(end-begin)/32;
if (!count || (count&(count-1))) return 0;
auto index=get<uintptr_t>(buckets+(type&(count-1))*8);
for(size_t step=0;step<entries && index<entries;++step) {
const auto entry=begin+index*32;
if(get<uint32_t>(entry+8)==type) return get<uintptr_t>(entry+16);
index=get<uintptr_t>(entry);
}
return 0;
}
inline uintptr_t component_at(uintptr_t storage,uint32_t entity) {
if(!storage) return 0;
const auto sparse=get<uintptr_t>(storage+8), end=get<uintptr_t>(storage+16);
const size_t page=(entity&0x3ffff)>>11;
if(!sparse || end<sparse || end-sparse>0x100000 || page>=(end-sparse)/8) return 0;
const auto data=get<uintptr_t>(sparse+page*8); uint32_t packed;
if(!data || !read(data+(entity&0x7ff)*4,packed) || (packed^(entity&0xfffc0000))>0x3fffe) return 0;
const auto first=get<uintptr_t>(storage+32), last=get<uintptr_t>(storage+40);
const size_t index=packed&0x3ffff;
if(!first || last<first || last-first>0x100000 || index>=(last-first)/4 || get<uint32_t>(first+index*4)!=entity) return 0;
const auto fn=get<uintptr_t>(get<uintptr_t>(storage));
// Slot zero is the native read-only get_at(size_t), accounting for each
// component's own stride. Validate its verified payload-load prefix.
// Sixteen-byte components use a verified getter with an index-copy
// instruction before the payload load (ActorRotationComponent).
const std::array<uint8_t,7> indexed{0x48,0x89,0xd0,0x48,0x8b,0x49,0x50};
if(get<uint32_t>(fn)!=0x50498b48 && get<std::array<uint8_t,7>>(fn)!=indexed) return 0;
__try {return reinterpret_cast<uintptr_t(__fastcall*)(uintptr_t,size_t)>(fn)(storage,index);}
__except(EXCEPTION_EXECUTE_HANDLER) {return 0;}
}
inline uintptr_t component(uintptr_t registry,uint32_t entity,const char* type) {return component_at(pool(registry,hash(type)),entity);}
inline std::string string(uintptr_t address,size_t limit=96) {
struct native_string { char data[16];uint64_t size,capacity; } value;
if(!read(address,value) || value.size>limit || value.capacity<value.size || value.capacity>1048576) return {};
uintptr_t bytes=value.capacity<16 ? address : get<uintptr_t>(address);
std::string out;out.reserve(size_t(value.size));
for(size_t i=0;i<value.size;++i) {char c;if(!read(bytes+i,c) || !c) return {};out+=c;}
return out;
}
struct item {std::string name;int count=0;};
struct actor {
uint32_t id=0;std::string name;vec3 position{},feet{},head{},velocity{};
float health=0,max_health=0;bool health_known=false;
item held;std::array<item,4> armor{};
};
struct frame {
bool valid=false,has_block=false,has_target=false;
uint64_t stamp=0,world_id=0;actor local,target;
std::vector<actor> players;
std::vector<std::string> online_players;bool roster_known=false,xp_known=false;int xp_level=0;float xp_progress=0;
vec3 block{},camera{};float matrix[16]{},fov_x=1,fov_y=1;
};
inline std::shared_ptr<const frame> published=std::make_shared<frame>();
inline std::mutex frame_mutex,alias_mutex;
inline std::atomic<uintptr_t> client{0};
inline std::atomic<DWORD> render_thread{0};
inline std::atomic<bool> collect_players{false},collect_roster{false},collect_xp{false};
inline std::atomic<int> time_override{-1};
inline bool ready=false,camera_ready=false,time_ready=false,name_ready=false,fog_ready=false;
inline std::atomic<bool> fog_enabled{false};
inline std::atomic<uint32_t> fog_color{0};
inline std::atomic<bool> hide_native_names{false}, alias_enabled{false};
inline std::shared_ptr<const std::string> alias=std::make_shared<const std::string>("Player");
inline std::atomic<uintptr_t> local_actor{0};
inline thread_local bool rendering=false;
inline void (*after_world)()=nullptr;
inline std::shared_ptr<const frame> latest() {std::lock_guard<std::mutex> lock(frame_mutex);return published;}
inline void publish(frame value) {auto next=std::make_shared<frame>(std::move(value));std::lock_guard<std::mutex> lock(frame_mutex);published=std::move(next);}
inline std::shared_ptr<const std::string> current_alias() {std::lock_guard<std::mutex> lock(alias_mutex);return alias;}
inline void set_alias(std::string name) {auto next=std::make_shared<const std::string>(std::move(name));std::lock_guard<std::mutex> lock(alias_mutex);alias=std::move(next);}
inline bool fresh(const frame& value) {return value.valid && GetTickCount64()-value.stamp<500;}
inline item read_item(uintptr_t stack) {
item value;if(!stack) return value;
const auto counter=get<uintptr_t>(stack+8),type=get<uintptr_t>(counter);
if(!type) return value;
value.name=string(type+0xd8);value.count=get<uint8_t>(stack+0x22);
if(!value.count) value.name.clear();return value;
}
inline uintptr_t inventory_item(uintptr_t container,int slot) {
const auto first=get<uintptr_t>(container+0x1a0),end=get<uintptr_t>(container+0x1a8);
if(!first || end<first || end-first>152*256 || slot<0 || size_t(slot)>=(end-first)/152) return 0;
return first+152*slot;
}
inline uintptr_t carried_item(uintptr_t player) {
const auto inventory=get<uintptr_t>(player+0x5b8);
const auto container=get<uintptr_t>(inventory+0xb8);
const int selected=get<int>(inventory+0x10);
const auto first=get<uintptr_t>(container+0x198),last=get<uintptr_t>(container+0x1a0);
if(!first || selected<0 || selected>8 || get<uint8_t>(inventory+0xb0) || last<first || last-first>152*256 || size_t(selected)>=(last-first)/152) return 0;
return first+152*selected;
}
inline bool read_actor(uintptr_t registry,uint32_t id,actor& value,bool equipment=true) {
auto state=component(registry,id,"StateVectorComponent");
if(!state || !read(state,value.position) || !finite(value.position)) return false;
value.id=id;read(state+24,value.velocity);
auto bounds=component(registry,id,"AABBShapeComponent");
vec3 min{},max{};
value.feet={value.position.x,value.position.y-1.62f,value.position.z};
if(read(bounds,min) && read(bounds+12,max) && finite(max) && max.y-min.y>0 && max.y-min.y<5) {
value.feet={(min.x+max.x)*.5f,min.y,(min.z+max.z)*.5f};
value.head={(min.x+max.x)*.5f,max.y+.3f,(min.z+max.z)*.5f};
}
else value.head={value.position.x,value.position.y+.3f,value.position.z};
const auto sync=component(registry,id,"SynchedActorDataComponent");
const auto items=get<uintptr_t>(sync),end=get<uintptr_t>(sync+8);
if(items && end>=items+5*8 && end-items<8192) value.name=clean_name(string(get<uintptr_t>(items+4*8)+16));
const auto attrs=component(registry,id,"AttributesComponent");
const auto keys=get<uintptr_t>(attrs),last=get<uintptr_t>(attrs+8),values=get<uintptr_t>(attrs+24),val_end=get<uintptr_t>(attrs+32);
if(keys && last>keys && last-keys<=800 && values && val_end>values) {
const size_t count=(last-keys)/4,stride=(val_end-values)/count;
if(stride==136) for(size_t i=0;i<count;++i) if(get<uint32_t>(keys+i*4)==7) {
value.health=get<float>(values+i*stride+0x7c);value.max_health=get<float>(values+i*stride+0x78);
value.health_known=std::isfinite(value.health) && std::isfinite(value.max_health) && value.max_health>0 && value.max_health<=2048 && value.health>=0 && value.health<=value.max_health;break;
}
}
if(equipment) {
auto equip=component(registry,id,"ActorEquipmentComponent");auto armor=get<uintptr_t>(equip+8);
for(int i=0;i<4;++i) value.armor[i]=read_item(inventory_item(armor,i));
// The player's selected stack is accessed through its actual
// inventory reference rather than through item-renderer copies.
const auto owner=get<uintptr_t>(component(registry,id,"ActorOwnerComponent"));
value.held=read_item(carried_item(owner));
}
return true;
}
inline bool read_roster_map(uintptr_t map,std::vector<std::string>& names) {
const auto head=get<uintptr_t>(map+8),count=get<uintptr_t>(map+16);
if(!head || count>1024)return false;
auto node=get<uintptr_t>(head);std::vector<std::string> result;
for(size_t i=0;i<count;++i) {
if(!node || node==head)return false;
auto name=clean_name(string(node+56));if(name.empty())return false;
result.push_back(std::move(name));node=get<uintptr_t>(node);
}
if(node!=head || get<uintptr_t>(map+16)!=count)return false;
std::sort(result.begin(),result.end());names=std::move(result);return true;
}
inline bool read_roster(uintptr_t registry,std::vector<std::string>& names) {
const auto storage=pool(registry,hash("LevelComponent"));
const auto first=get<uintptr_t>(storage+32),last=get<uintptr_t>(storage+40);
if(!first || last-first!=4)return false;
const auto level=get<uintptr_t>(component_at(storage,get<uint32_t>(first)));
return level && read_roster_map(get<uintptr_t>(level+0x4e0),names);
}
inline bool read_xp_values(uintptr_t attrs,int& level,float& progress) {
const auto keys=get<uintptr_t>(attrs),end=get<uintptr_t>(attrs+8);
const auto values=get<uintptr_t>(attrs+24),last=get<uintptr_t>(attrs+32);
if(!keys || end<=keys || end-keys>800 || (end-keys)%4 || !values || last<values || last-values!=(end-keys)/4*136)return false;
float l=-1,p=-1;
for(size_t i=0;i<(end-keys)/4;++i) {
const auto id=get<uint32_t>(keys+4*i);
if(id==4)l=get<float>(values+136*i+0x70);
if(id==5)p=get<float>(values+136*i+0x70);
}
if(!std::isfinite(l) || l<0 || l>24791 || l!=std::floor(l) || !std::isfinite(p) || p<0 || p>1)return false;
level=int(l);progress=p;return true;
}
inline void capture(uintptr_t ci) {
frame out;out.stamp=GetTickCount64();
const auto registry_owner=get<uintptr_t>(ci+0x248),registry=registry_owner+0x30;
const auto entity=get<uint32_t>(ci+0x258);out.world_id=registry_owner;
local_actor=get<uintptr_t>(component(registry,entity,"ActorOwnerComponent"));
const auto renderer=get<uintptr_t>(ci+0x1c0),camera=get<uintptr_t>(renderer+0x468);
if(!registry_owner || !camera || !read_actor(registry,entity,out.local) || !read(camera+0x660,out.camera) || !read(ci+0x420,out.matrix)) {input::in_world=false;publish(std::move(out));return;}
out.fov_x=get<float>(camera+0xf58);out.fov_y=get<float>(camera+0xf6c);
out.valid=finite(out.camera) && std::isfinite(out.fov_x) && std::isfinite(out.fov_y) && out.fov_x>0 && out.fov_y>0;
const auto controller=get<uintptr_t>(component(registry,entity,"HitResultComponent"));
const auto hits=get<uintptr_t>(controller+8),hits_end=get<uintptr_t>(controller+16);
if(hits && hits_end>=hits+272 && hits_end-hits<272*64) {
const int type=get<int>(hits+24);
if(type==0) {
struct block_position{int x,y,z;} block;
if(read(hits+32,block)) {out.block={float(block.x),float(block.y),float(block.z)};out.has_block=true;}
} else if(type==1) {
const auto hit_owner=get<uintptr_t>(hits+56);const auto target=get<uint32_t>(hits+72);
const auto type_ptr=component(hit_owner+0x30,target,"ActorTypeComponent");
if(hit_owner==registry_owner && get<int>(type_ptr)==319) out.has_target=read_actor(registry,target,out.target);
}
}
if(collect_players) {
const auto owners=pool(registry,hash("ActorOwnerComponent"));
const auto first=get<uintptr_t>(owners+32),last=get<uintptr_t>(owners+40);
if(first && last>=first && last-first<=4*16384) for(auto at=first;at<last && out.players.size()<128;at+=4) {
const auto id=get<uint32_t>(at);if(id==entity || id==0xfffc0000) continue;
const auto type_ptr=component(registry,id,"ActorTypeComponent");if(get<int>(type_ptr)!=319) continue;
actor other;if(read_actor(registry,id,other,false) && distance(other.position,out.local.position)<=128 && !other.name.empty()) out.players.push_back(std::move(other));
}
}
if(out.valid && collect_roster)out.roster_known=read_roster(registry,out.online_players);
if(out.valid && collect_xp)out.xp_known=read_xp_values(component(registry,entity,"AttributesComponent"),out.xp_level,out.xp_progress);
input::in_world=out.valid;
publish(std::move(out));
}
inline game::game_hook update_hook,camera_hook,time_hook,name_hook,fog_hook;
inline void* level_target=nullptr;
using update_fn=bool(__fastcall*)(uintptr_t,bool);
using level_fn=int64_t(__fastcall*)(uintptr_t,void*,int64_t);
using camera_fn=void(__fastcall*)(uintptr_t,void*,float);
using time_fn=float(__fastcall*)(void*,int,float);
using active_fn=void*(__fastcall*)(void*,uintptr_t);
using name_fn=const std::string*(__fastcall*)(uintptr_t);
struct color {float r,g,b,a;};
using fog_fn=color*(__fastcall*)(void*,color*,const color*,float);
inline update_fn original_update=nullptr;
inline level_fn original_level=nullptr;
inline camera_fn original_camera=nullptr;
inline time_fn original_time=nullptr;
inline active_fn get_camera=nullptr;
inline name_fn original_name=nullptr;
inline fog_fn original_fog=nullptr;
inline color* __fastcall fog_detour(void* self,color* output,const color* base,float brightness) {
auto* result=original_fog(self,output,base,brightness);
if(result && fog_enabled && GetCurrentThreadId()==render_thread.load()) {
const auto color=fog_color.load(); const float blend=float((color>>24)&255)/255.f;
result->r+=(float(color&255)/255.f-result->r)*blend;
result->g+=(float((color>>8)&255)/255.f-result->g)*blend;
result->b+=(float((color>>16)&255)/255.f-result->b)*blend;
}
return result;
}
inline const std::string* __fastcall name_detour(uintptr_t self) {
const auto address=reinterpret_cast<uintptr_t>(_ReturnAddress())-reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const bool visual=GetCurrentThreadId()==render_thread.load() &&
(rendering || (address>=0x4600000 && address<0x4900000) || (address>=0x8c00000 && address<0x9000000));
if(visual) {
if(self==local_actor.load() && alias_enabled) {
thread_local std::shared_ptr<const std::string> returned;
returned=current_alias();return returned.get();
}
if(self!=local_actor.load() && hide_native_names) {
const auto reg=get<uintptr_t>(self+16);const auto id=get<uint32_t>(self+24);
if(get<int>(component(reg,id,"ActorTypeComponent"))==319) {static const std::string empty;return &empty;}
}
}
return original_name(self);
}
struct player_look_lock {
bool held=false;uintptr_t owner=0;uint32_t entity=0;
std::array<float,4> rotation{};std::array<float,2> head{},body{},render{},delta{},last_native{};
bool apply(uintptr_t identity,uint32_t id,uintptr_t rot,uintptr_t head_at,uintptr_t body_at,uintptr_t render_at,bool active) {
delta={};
if(!active){held=false;owner=0;return false;}
const bool continuing=held && owner==identity && entity==id;
if(!continuing) {
std::array<float,4> r;std::array<float,2> h,b,v;
if(!read(rot,r) || !read(head_at,h) || !read(body_at,b) || !read(render_at,v))return false;
for(float value:r)if(!std::isfinite(value))return false;
for(float value:h)if(!std::isfinite(value))return false;
for(float value:b)if(!std::isfinite(value))return false;
rotation={r[0],r[1],r[0],r[1]};head={h[0],h[0]};body={b[0],b[0]};render={r[0],r[1]};
last_native={r[0],r[1]};held=true;owner=identity;entity=id;
}
if(continuing) {
std::array<float,4> current;
if(!read(rot,current) || !std::isfinite(current[0]) || !std::isfinite(current[1]))return false;
// Bedrock may reapply its cached absolute look target every tick.
// Consume target changes once; ignore our own restored baseline.
if(current[0]!=rotation[0] || current[1]!=rotation[1]) {
delta={current[0]-last_native[0],std::remainder(current[1]-last_native[1],360.f)};
last_native={current[0],current[1]};
}
}
return write(rot,rotation) && write(head_at,head) && write(body_at,body) && write(render_at,render);
}
};
inline player_look_lock frozen_look;
inline std::mutex player_look_mutex;
inline std::atomic<float> pending_orbit_yaw{0},pending_orbit_pitch{0};
inline void accumulate(std::atomic<float>& target,float delta) {
auto previous=target.load();while(!target.compare_exchange_weak(previous,previous+delta)){}
}
inline void sync_player_look(uintptr_t ci) {
std::lock_guard lock(player_look_mutex);
if(!input::freelook_active()){frozen_look.held=false;frozen_look.owner=0;pending_orbit_yaw=0;pending_orbit_pitch=0;return;}
const auto owner=get<uintptr_t>(ci+0x248),registry=owner+0x30;
const auto id=get<uint32_t>(ci+0x258);if(!owner)return;
const bool applied=frozen_look.apply(owner,id,component(registry,id,"ActorRotationComponent"),
component(registry,id,"ActorHeadRotationComponent"),component(registry,id,"MobBodyRotationComponent"),
component(registry,id,"RenderRotationComponent"),true);
if(applied) {
accumulate(pending_orbit_pitch,frozen_look.delta[0]);
accumulate(pending_orbit_yaw,frozen_look.delta[1]);
}
}
inline bool __fastcall update_detour(uintptr_t self,bool initial) {
client=self;sync_player_look(self);
const auto result=original_update(self,initial);sync_player_look(self);return result;
}
inline int64_t __fastcall level_detour(uintptr_t self,void* context,int64_t parameters) {
render_thread=GetCurrentThreadId();sync_player_look(client.load());const bool previous=rendering;rendering=true;
const auto result=original_level(self,context,parameters);
capture(client.load());if(after_world) after_world();rendering=previous;return result;
}
struct active_context {uintptr_t owner,registry;uint32_t entity;uint8_t padding[4];bool valid;uint8_t tail[7];};
inline uintptr_t active_camera(uintptr_t ci) {
active_context context{};
__try {if(get_camera) get_camera(&context,ci);}
__except(EXCEPTION_EXECUTE_HANDLER) {return 0;}
return context.valid ? component(context.registry,context.entity,"MinecraftCamera::CameraComponent") : 0;
}
inline game::game_hook perspective_hook;
inline bool perspective_ready=false;
using perspective_fn=int(__fastcall*)(uintptr_t);
inline perspective_fn original_perspective=nullptr;
inline std::atomic<float> orbit_distance{4.f};
inline int __fastcall perspective_detour(uintptr_t options) {
sync_player_look(client.load());
const int native=original_perspective(options);
return input::freelook_active() ? 1 : native;
}
inline constexpr const char* perspective_signature="48 83 EC 38 48 8B 05 45 2C 82 10 48 31 E0 48 89 44 24 30 48 8B 01 48 8B 40 08 48 8D 54 24 28 41 B8 03 00 00 00 FF 15 4D 46 14 0E 48 8B 4C 24 28 48 89 C8 48 8B 49 08 48 8B 89 38 02 00 00 48 85 C9 75 ED 8B 40 18 48 8B 4C 24 30 48 31 E1 48 3B 0D FB 2B 82 10 75 05 48 83 C4";
inline std::mutex look_mutex;
inline quaternion saved_orientation{};
inline float yaw=0,pitch=0;
inline bool was_looking=false;
inline void __fastcall camera_detour(uintptr_t self,void* context,float alpha) {
render_thread=GetCurrentThreadId();const auto ci=get<uintptr_t>(self+0x1168);
sync_player_look(ci);
const bool looking=input::freelook_active();
const auto camera=looking ? active_camera(ci) : 0;
quaternion original{},replacement{};vec3 original_position{};bool changed=false,moved=false;
{
std::lock_guard<std::mutex> lock(look_mutex);
const auto frame=latest();
if(camera && fresh(*frame) && read(camera+0x30,original) && read(camera+0x40,original_position) && finite(original_position)) {
if(!was_looking) {saved_orientation=original;yaw=pitch=0;input::look_dx=0;input::look_dy=0;}
yaw=std::remainder(yaw+pending_orbit_yaw.exchange(0)*(input::look_sensitivity.load()/.15f),360.f);
pitch=std::clamp(pitch+pending_orbit_pitch.exchange(0)*(input::look_sensitivity.load()/.15f),-85.f,85.f);
replacement=turn(saved_orientation,yaw,pitch);
const auto position=orbit_position(frame->local.position,replacement,orbit_distance.load());
changed=write(camera+0x30,replacement);
if(changed)moved=write(camera+0x40,position);
}
was_looking=looking && camera;
}
original_camera(self,context,alpha);
if(changed) {
write(camera+0x30,original);
if(moved)write(camera+0x40,original_position);
}
}
inline float __fastcall time_detour(void* self,int ticks,float alpha) {
const int chosen=time_override.load();
return original_time(self,chosen>=0 && GetCurrentThreadId()==render_thread.load() ? chosen : ticks,alpha);
}
inline void initialize() {
bool update_ok=update_hook.install("client world context",client_update_signature,reinterpret_cast<void*>(&update_detour),reinterpret_cast<void**>(&original_update),true);
auto call=sigscan::find("E8 ?? ?? ?? ?? 45 31 E4 48 83 BE A8 01 00 00 00",true);
if(call) {
level_target=sigscan::resolve_rip(call,1,5);
if(MH_CreateHook(level_target,&level_detour,reinterpret_cast<void**>(&original_level))!=MH_OK) level_target=nullptr;
}
ready=update_ok && level_target && update_hook.set_enabled(true) && MH_EnableHook(level_target)==MH_OK;
auto active=sigscan::find(active_camera_signature,true);
if(active) {
DWORD64 image_base=0;
auto function=RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(active),&image_base,nullptr);
if(function) get_camera=reinterpret_cast<active_fn>(image_base+function->BeginAddress);
}
camera_ready=get_camera && camera_hook.install("camera matrices",camera_matrix_signature,reinterpret_cast<void*>(&camera_detour),reinterpret_cast<void**>(&original_camera),true) && camera_hook.set_enabled(true);
perspective_ready=perspective_hook.install("view perspective",perspective_signature,reinterpret_cast<void*>(&perspective_detour),reinterpret_cast<void**>(&original_perspective),true) && perspective_hook.set_enabled(true);
input::freelook_supported=camera_ready && perspective_ready;
time_ready=time_hook.install("visual time",time_signature,reinterpret_cast<void*>(&time_detour),reinterpret_cast<void**>(&original_time),true) && time_hook.set_enabled(true);
name_ready=name_hook.install("visual player name",name_signature,reinterpret_cast<void*>(&name_detour),reinterpret_cast<void**>(&original_name),true) && name_hook.set_enabled(true);
fog_ready=fog_hook.install("dimension fog color",fog_signature,reinterpret_cast<void*>(&fog_detour),reinterpret_cast<void**>(&original_fog),true) && fog_hook.set_enabled(true);
game::log(std::string("world modules: ")+(ready ? "ready" : "unavailable"));
}
}
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <d3d11.h>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <atomic>
#include "world.h"
#pragma comment(lib,"d3dcompiler.lib")
#pragma comment(lib,"d3d11.lib")
namespace world_filter {
using Microsoft::WRL::ComPtr;
inline std::atomic<bool> enabled{false};
inline std::atomic<uint32_t> tint{0xffffffff};
inline std::atomic<float> brightness{1};
inline ComPtr<ID3D11VertexShader> vs;
inline ComPtr<ID3D11PixelShader> ps;
inline ComPtr<ID3D11SamplerState> sampler;
inline ComPtr<ID3D11RasterizerState> raster;
inline ComPtr<ID3D11DepthStencilState> depth;
inline ComPtr<ID3D11Buffer> constants;
inline ComPtr<ID3D11Texture2D> copy;
inline ComPtr<ID3D11ShaderResourceView> view;
inline ID3D11Device* owner=nullptr;
inline bool initialize(ID3D11Device* device) {
if(owner==device && vs && ps && constants && sampler && raster && depth) return true;
owner=device;
const char* source=R"(
Texture2D image:register(t0);SamplerState sampleImage:register(s0);
cbuffer settings:register(b0){float4 color;float4 light;}
struct Vertex{float4 position:SV_POSITION;float2 uv:TEXCOORD0;};
Vertex vertex(uint id:SV_VertexID){Vertex v;v.uv=float2((id<<1)&2,id&2);v.position=float4(v.uv*float2(2,-2)+float2(-1,1),0,1);return v;}
float4 pixel(Vertex v):SV_TARGET{float4 c=image.Sample(sampleImage,v.uv);c.rgb*=lerp(float3(1,1,1),color.rgb,color.a)*light.x;return c;}
)";
ComPtr<ID3DBlob> vertex,pixel,error;
if(FAILED(D3DCompile(source,strlen(source),nullptr,nullptr,nullptr,"vertex","vs_4_0",0,0,&vertex,&error)) ||
FAILED(D3DCompile(source,strlen(source),nullptr,nullptr,nullptr,"pixel","ps_4_0",0,0,&pixel,&error))) return false;
if(FAILED(device->CreateVertexShader(vertex->GetBufferPointer(),vertex->GetBufferSize(),nullptr,&vs)) ||
FAILED(device->CreatePixelShader(pixel->GetBufferPointer(),pixel->GetBufferSize(),nullptr,&ps))) return false;
D3D11_SAMPLER_DESC sd{};sd.Filter=D3D11_FILTER_MIN_MAG_MIP_LINEAR;sd.AddressU=sd.AddressV=sd.AddressW=D3D11_TEXTURE_ADDRESS_CLAMP;sd.MaxLOD=D3D11_FLOAT32_MAX;
D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=true;
D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;
D3D11_BUFFER_DESC bd{};bd.ByteWidth=32;bd.Usage=D3D11_USAGE_DEFAULT;bd.BindFlags=D3D11_BIND_CONSTANT_BUFFER;
return SUCCEEDED(device->CreateSamplerState(&sd,&sampler)) && SUCCEEDED(device->CreateRasterizerState(&rs,&raster)) &&
SUCCEEDED(device->CreateDepthStencilState(&ds,&depth)) && SUCCEEDED(device->CreateBuffer(&bd,nullptr,&constants));
}
inline bool apply(ID3D11Device* device,ID3D11DeviceContext* context,ID3D11RenderTargetView* target) {
if(!enabled || !initialize(device)) return false;
ComPtr<ID3D11Resource> resource;target->GetResource(&resource);
ComPtr<ID3D11Texture2D> texture;if(FAILED(resource.As(&texture))) return false;
D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
D3D11_RENDER_TARGET_VIEW_DESC td{};target->GetDesc(&td);
if(desc.SampleDesc.Count!=1 || desc.ArraySize!=1 || desc.MipLevels!=1) return false;
D3D11_TEXTURE2D_DESC previous{};if(copy) copy->GetDesc(&previous);
if(!copy || previous.Width!=desc.Width || previous.Height!=desc.Height || previous.Format!=desc.Format) {
copy.Reset();view.Reset();desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;desc.CPUAccessFlags=0;desc.MiscFlags=0;desc.Usage=D3D11_USAGE_DEFAULT;
if(FAILED(device->CreateTexture2D(&desc,nullptr,&copy))) return false;
D3D11_SHADER_RESOURCE_VIEW_DESC srv{};srv.Format=td.Format;srv.ViewDimension=D3D11_SRV_DIMENSION_TEXTURE2D;srv.Texture2D.MipLevels=1;
if(FAILED(device->CreateShaderResourceView(copy.Get(),&srv,&view))) {copy.Reset();return false;}
}
context->CopyResource(copy.Get(),texture.Get());
ComPtr<ID3D11VertexShader> old_vs;ComPtr<ID3D11PixelShader> old_ps;ComPtr<ID3D11GeometryShader> old_gs;
ComPtr<ID3D11HullShader> old_hs;ComPtr<ID3D11DomainShader> old_ds;
ComPtr<ID3D11Buffer> old_cb;ComPtr<ID3D11ShaderResourceView> old_srv;ComPtr<ID3D11SamplerState> old_sampler;
ComPtr<ID3D11InputLayout> layout;ComPtr<ID3D11RasterizerState> old_rs;ComPtr<ID3D11DepthStencilState> old_depth;
ComPtr<ID3D11BlendState> blend;ComPtr<ID3D11DepthStencilView> dsv;
ID3D11RenderTargetView* targets[8]{};context->OMGetRenderTargets(8,targets,&dsv);
ID3D11ClassInstance* classes[5][256]{};UINT class_count[5]={256,256,256,256,256};
ComPtr<ID3D11DeviceContext1> extended;context->QueryInterface(IID_PPV_ARGS(&extended));
UINT first_constant=0,constant_count=0;
UINT stencil=0,mask=0,count=16;float factor[4]{};D3D11_VIEWPORT ports[16]{};D3D11_PRIMITIVE_TOPOLOGY topology;
context->VSGetShader(&old_vs,classes[0],&class_count[0]);context->PSGetShader(&old_ps,classes[1],&class_count[1]);context->GSGetShader(&old_gs,classes[2],&class_count[2]);
context->HSGetShader(&old_hs,classes[3],&class_count[3]);context->DSGetShader(&old_ds,classes[4],&class_count[4]);
if(extended) extended->PSGetConstantBuffers1(0,1,&old_cb,&first_constant,&constant_count);
else context->PSGetConstantBuffers(0,1,&old_cb);
context->PSGetShaderResources(0,1,&old_srv);context->PSGetSamplers(0,1,&old_sampler);
context->IAGetInputLayout(&layout);context->IAGetPrimitiveTopology(&topology);context->RSGetState(&old_rs);context->RSGetViewports(&count,ports);
context->OMGetDepthStencilState(&old_depth,&stencil);context->OMGetBlendState(&blend,factor,&mask);
const auto color=tint.load();float data[8]={float(color&255)/255,float((color>>8)&255)/255,float((color>>16)&255)/255,float(color>>24)/255,
brightness.load(),0,0,0};context->UpdateSubresource(constants.Get(),0,nullptr,data,0,0);
ID3D11Buffer* cb=constants.Get();ID3D11ShaderResourceView* srv=view.Get();ID3D11SamplerState* sm=sampler.Get();
D3D11_VIEWPORT port{0,0,float(desc.Width),float(desc.Height),0,1};
context->OMSetRenderTargets(1,&target,nullptr);context->OMSetDepthStencilState(depth.Get(),0);context->OMSetBlendState(nullptr,nullptr,0xffffffff);
context->RSSetState(raster.Get());context->RSSetViewports(1,&port);context->IASetInputLayout(nullptr);context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
context->VSSetShader(vs.Get(),nullptr,0);context->PSSetShader(ps.Get(),nullptr,0);context->GSSetShader(nullptr,nullptr,0);context->HSSetShader(nullptr,nullptr,0);context->DSSetShader(nullptr,nullptr,0);
context->PSSetConstantBuffers(0,1,&cb);context->PSSetShaderResources(0,1,&srv);context->PSSetSamplers(0,1,&sm);context->Draw(3,0);
srv=nullptr;context->PSSetShaderResources(0,1,&srv);
context->OMSetRenderTargets(8,targets,dsv.Get());context->OMSetDepthStencilState(old_depth.Get(),stencil);context->OMSetBlendState(blend.Get(),factor,mask);
context->RSSetState(old_rs.Get());context->RSSetViewports(count,ports);context->IASetInputLayout(layout.Get());context->IASetPrimitiveTopology(topology);
context->VSSetShader(old_vs.Get(),classes[0],class_count[0]);context->PSSetShader(old_ps.Get(),classes[1],class_count[1]);context->GSSetShader(old_gs.Get(),classes[2],class_count[2]);context->HSSetShader(old_hs.Get(),classes[3],class_count[3]);context->DSSetShader(old_ds.Get(),classes[4],class_count[4]);
cb=old_cb.Get();srv=old_srv.Get();sm=old_sampler.Get();
if(extended) extended->PSSetConstantBuffers1(0,1,&cb,&first_constant,&constant_count);
else context->PSSetConstantBuffers(0,1,&cb);
context->PSSetShaderResources(0,1,&srv);context->PSSetSamplers(0,1,&sm);
for(int stage=0;stage<5;++stage) for(UINT i=0;i<class_count[stage];++i) if(classes[stage][i]) classes[stage][i]->Release();
for(auto* rt:targets) if(rt) rt->Release();return true;
}
inline void shutdown() {enabled=false;vs.Reset();ps.Reset();sampler.Reset();raster.Reset();depth.Reset();constants.Reset();copy.Reset();view.Reset();owner=nullptr;}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <algorithm>
#include <cmath>
#include <string>
#include "imgui.h"
namespace world {
struct vec3 { float x = 0, y = 0, z = 0; };
struct quaternion { float x = 0, y = 0, z = 0, w = 1; };
inline bool finite(vec3 p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
inline float distance(vec3 a, vec3 b) { return std::sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z)); }
inline quaternion multiply(quaternion a, quaternion b) {
return {a.w*b.x+a.x*b.w+a.y*b.z-a.z*b.y, a.w*b.y-a.x*b.z+a.y*b.w+a.z*b.x,
a.w*b.z+a.x*b.y-a.y*b.x+a.z*b.w, a.w*b.w-a.x*b.x-a.y*b.y-a.z*b.z};
}
inline quaternion turn(quaternion q, float yaw, float pitch) {
constexpr float rad = 3.14159265359f / 360.f;
q = multiply(multiply({0, std::sin(-yaw*rad), 0, std::cos(yaw*rad)}, q),
{std::sin(-pitch*rad), 0, 0, std::cos(pitch*rad)});
const float length = std::sqrt(q.x*q.x+q.y*q.y+q.z*q.z+q.w*q.w);
if (!std::isfinite(length) || length < .01f) return {};
return {q.x/length,q.y/length,q.z/length,q.w/length};
}
inline vec3 camera_back(quaternion q) {
return {2*(q.x*q.z+q.w*q.y),2*(q.y*q.z-q.w*q.x),1-2*(q.x*q.x+q.y*q.y)};
}
inline vec3 orbit_position(vec3 pivot,quaternion orientation,float radius) {
const auto back=camera_back(orientation);
return {pivot.x+back.x*radius,pivot.y+back.y*radius,pivot.z+back.z*radius};
}
inline bool project(const float* matrix, vec3 camera, vec3 point, float fov_x, float fov_y, ImVec2 size, ImVec2& result) {
if (!finite(camera) || !finite(point) || size.x <= 0 || size.y <= 0) return false;
const vec3 p{point.x-camera.x,point.y-camera.y,point.z-camera.z};
const float x=matrix[0]*p.x+matrix[1]*p.y+matrix[2]*p.z+matrix[3];
const float y=matrix[4]*p.x+matrix[5]*p.y+matrix[6]*p.z+matrix[7];
const float z=matrix[8]*p.x+matrix[9]*p.y+matrix[10]*p.z+matrix[11];
if (!std::isfinite(z) || z >= -.02f || !std::isfinite(fov_x) || !std::isfinite(fov_y)) return false;
result = {size.x*.5f*(1+x/-z*fov_x), size.y*.5f*(1-y/-z*fov_y)};
return std::isfinite(result.x) && std::isfinite(result.y) && std::abs(result.x)<100000 && std::abs(result.y)<100000;
}
inline bool project_edge(const float* matrix,vec3 camera,vec3 a,vec3 b,float fov_x,float fov_y,ImVec2 size,ImVec2& first,ImVec2& second) {
const auto depth=[&](vec3 p){return matrix[8]*(p.x-camera.x)+matrix[9]*(p.y-camera.y)+matrix[10]*(p.z-camera.z)+matrix[11];};
float za=depth(a),zb=depth(b);constexpr float clip_plane=-.025f;
if(!std::isfinite(za) || !std::isfinite(zb) || (za>=clip_plane && zb>=clip_plane))return false;
if(za>=clip_plane || zb>=clip_plane) {
const float t=(clip_plane-za)/(zb-za);
const vec3 clipped{a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t,a.z+(b.z-a.z)*t};
if(za>=clip_plane)a=clipped;else b=clipped;
}
if(!project(matrix,camera,a,fov_x,fov_y,size,first) || !project(matrix,camera,b,fov_x,fov_y,size,second))return false;
return true;
}
inline std::string clean_name(const std::string& name) {
std::string result;
for (size_t i=0;i<name.size() && result.size()<96;++i) {
const auto c=static_cast<unsigned char>(name[i]);
if (c==0xc2 && i+2<name.size() && static_cast<unsigned char>(name[i+1])==0xa7) {i+=2;continue;}
if (c==0xa7 && i+1<name.size()) {++i;continue;}
if (c>=32 && c!=127) result+=name[i];
}
return result;
}
inline bool weapon(const std::string& name) {
return name.find("sword")!=std::string::npos || name.find("axe")!=std::string::npos && name.find("pickaxe")==std::string::npos ||
name.find("bow")!=std::string::npos || name.find("trident")!=std::string::npos || name.find("mace")!=std::string::npos || name.find("spear")!=std::string::npos;
}
inline std::string item_label(std::string name) {
if (auto colon=name.find(':');colon!=std::string::npos) name.erase(0,colon+1);
std::replace(name.begin(),name.end(),'_',' '); return name.empty() ? "empty" : name;
}
}
+126 -13
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cfloat>
#include <algorithm>
#include <cmath>
#include <string>
#include "imgui.h"
@@ -8,6 +9,7 @@
#include "widgets.h"
#include "../input.h"
#include "../modules/module_manager.h"
#include "../config/profiles.h"
inline std::string key_name(int vk) {
if (vk == 0) return "none";
@@ -34,6 +36,9 @@ public:
void init() {
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr; // never write imgui.ini into the game's folder
// Minecraft owns the OS cursor. ImGui's WM_SETCURSOR handler must not
// hide it on the window thread while our software cursor is visible.
io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange;
io.LogFilename = nullptr;
fonts::load();
theme::apply();
@@ -49,6 +54,7 @@ public:
if (esc_down && !esc_was_down_ && g_menu_open && !any_binding()) set_open(false);
esc_was_down_ = esc_down;
update_menu_cursor();
open_t_ = theme::approach(open_t_, g_menu_open ? 1.f : 0.f, ImGui::GetIO().DeltaTime * 14.f);
}
@@ -63,6 +69,12 @@ public:
dl->AddRectFilled(ImVec2(0.f, 0.f), io.DisplaySize,
theme::u32(theme::with_alpha(theme::bg(), k_backdrop_alpha * a)));
if(g_menu_open && hud_editor::options.snap && hud_editor::options.show_grid) {
const float spacing=float(std::clamp(hud_editor::options.grid_size,4,64));
const auto color=theme::u32(theme::with_alpha(theme::line(),.22f*a));
for(float x=0;x<io.DisplaySize.x;x+=spacing)dl->AddLine({x,0},{x,io.DisplaySize.y},color);
for(float y=0;y<io.DisplaySize.y;y+=spacing)dl->AddLine({0,y},{io.DisplaySize.x,y},color);
}
// title bar, like the launcher: cube + lowercase wordmark
const ImVec2 logo_pos(26.f, 18.f);
const float logo_h = 30.f;
@@ -90,6 +102,7 @@ public:
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, open_t_);
draw_profiles();
float x = 40.f;
for (category cat : k_categories) {
if (!has_modules(cat)) continue;
@@ -110,6 +123,67 @@ private:
float open_t_ = 0.f;
bool menu_key_was_down_ = false;
bool esc_was_down_ = false;
char profile_name_[49]{};
hud_editor::drag hud_drag_;
void draw_profiles() {
ImGui::SetNextWindowPos(ImVec2(40.f, 56.f), ImGuiCond_Always);
ImGui::SetNextWindowSize(ImVec2(850.f, 0.f), ImGuiCond_Always);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8.f, 4.f));
auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
if (!g_menu_open) flags |= ImGuiWindowFlags_NoInputs;
if (ImGui::Begin("##profiles", nullptr, flags)) {
ImGui::AlignTextToFramePadding(); ImGui::TextUnformatted("profile"); ImGui::SameLine();
ImGui::SetNextItemWidth(200.f);
if (ImGui::BeginCombo("##active", profiles().active().c_str())) {
const auto choices = profiles().names();
for (const auto& name : choices) {
const bool selected = name == profiles().active();
if (ImGui::Selectable(name.c_str(), selected)) profiles().switch_to(name);
if (selected) ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
ImGui::SameLine(); if (ImGui::Button("save now")) profiles().save();
ImGui::SameLine(); if (ImGui::Button("manage profiles")) { profiles().refresh(); ImGui::OpenPopup("manage profiles"); }
ImGui::SameLine();
ImGui::TextColored(profiles().blocked() ? theme::accent() : theme::muted(), "%s",
profiles().blocked() ? "autosave paused: file error" : profiles().dirty() ? "autosaving..." : "autosave on / saved");
ImGui::SameLine();if(ImGui::Button("hud editor"))ImGui::OpenPopup("hud editor");
if(ImGui::BeginPopup("hud editor")) {
widgets::checkbox("snap to grid",&hud_editor::options.snap,220);
widgets::checkbox("show grid",&hud_editor::options.show_grid,220);
ImGui::TextUnformatted("grid size (px)");ImGui::SetNextItemWidth(220);
ImGui::SliderInt("##grid size",&hud_editor::options.grid_size,4,64);
ImGui::TextColored(theme::muted(),"hold Shift while dragging for free movement");
ImGui::EndPopup();
}
if (ImGui::BeginPopup("manage profiles")) {
ImGui::TextUnformatted("New profiles copy your current settings.");
ImGui::TextUnformatted("Names: letters, numbers, spaces, _ or -");
ImGui::SetNextItemWidth(310.f); ImGui::InputText("name", profile_name_, sizeof(profile_name_));
if (ImGui::Button("create & use")) { if (profiles().create(profile_name_)) profile_name_[0] = 0; }
ImGui::SameLine();
if (ImGui::Button("rename current")) { if (profiles().rename(profile_name_)) profile_name_[0] = 0; }
ImGui::Separator();
if (ImGui::Button("delete current profile")) ImGui::OpenPopup("Delete profile?");
if (ImGui::BeginPopupModal("Delete profile?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Text("Delete '%s'?", profiles().active().c_str());
ImGui::TextUnformatted("Default is protected. Another profile will be loaded.");
if (ImGui::Button("delete")) { if (profiles().remove_active()) ImGui::CloseCurrentPopup(); }
ImGui::SameLine(); if (ImGui::Button("cancel")) ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (!profiles().last_error().empty()) {
ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 400.f);
ImGui::TextColored(theme::accent(), "%s", profiles().last_error().c_str()); ImGui::PopTextWrapPos();
}
ImGui::EndPopup();
}
}
ImGui::End(); ImGui::PopStyleVar();
}
static const char* category_title(category c) {
switch (c) {
@@ -123,20 +197,33 @@ private:
void set_open(bool open) {
if (open == g_menu_open) return;
g_menu_open = open;
ImGui::GetIO().MouseDrawCursor = open; // ImGui draws its own cursor while open
update_menu_cursor();
if (open) {
input::release_cursor();
}
else {
input::restore_cursor();
for (auto& m : modules().all()) m->ui.binding = false;
for (auto& m : modules().all()) {
m->ui.binding = false;
for (auto& s : m->settings()) s.binding = false;
}
}
}
static void update_menu_cursor() {
CURSORINFO cursor{sizeof(cursor)};
const bool native_visible=GetCursorInfo(&cursor) && (cursor.flags&CURSOR_SHOWING);
// Show a software pointer in gameplay, while retaining the native pointer
// in inventory screens. Never change the game's cursor visibility/count.
ImGui::GetIO().MouseDrawCursor=g_menu_open && !native_visible;
}
bool any_binding() const {
for (auto& m : modules().all())
for (auto& m : modules().all()) {
if (m->ui.binding) return true;
for (auto& s : m->settings()) if (s.binding) return true;
}
return false;
}
@@ -151,10 +238,11 @@ private:
void draw_panel(category cat, float default_x) {
ImGui::SetNextWindowPos(ImVec2(default_x, 100.f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(k_panel_w, 0.f), ImGuiCond_Always); // fixed width, auto height
ImGui::SetNextWindowSizeConstraints(ImVec2(k_panel_w, 0.f),
ImVec2(k_panel_w, (std::max)(100.f, ImGui::GetIO().DisplaySize.y - 145.f)));
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoSavedSettings;
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
if (!g_menu_open) flags |= ImGuiWindowFlags_NoInputs; // fading out: no more clicks
const std::string id = std::string("##panel_") + category_name(cat);
@@ -297,6 +385,32 @@ private:
ImGui::PushID(&s);
switch (s.type) {
case setting_type::text: {
char value[257]{}; strncpy_s(value, s.text_value.c_str(), _TRUNCATE);
ImGui::TextUnformatted(s.name.c_str()); ImGui::SetNextItemWidth(w);
if (ImGui::InputText("##text", value, (std::min)(sizeof(value), size_t(s.int_max + 1)))) s.text_value = value;
break;
}
case setting_type::action:
if (widgets::button("##action", s.name.c_str(), false, w) && s.action) s.action();
break;
case setting_type::keybind: {
ImGui::TextUnformatted(s.name.c_str());
const std::string text = s.binding ? "press a key..." : key_name(s.int_value);
if (widgets::button("##key", text.c_str(), false, w)) s.binding = !s.binding;
if (s.binding) {
for (int vk = 0x08; vk < 0xFF; ++vk) {
if (is_key_down(vk)) {
// Keep modifiers specific so synthetic input and real input can be separated.
if (vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU) continue;
s.int_value = vk == VK_ESCAPE ? 0 : vk;
s.binding = false;
break;
}
}
}
break;
}
case setting_type::toggle:
widgets::checkbox(s.name.c_str(), &s.bool_value, w);
break;
@@ -348,11 +462,10 @@ private:
if (size.x <= 0.f || size.y <= 0.f) continue;
// keep it on screen
m.hud_pos.x = theme::clampf(m.hud_pos.x, 0.f, io.DisplaySize.x - size.x);
m.hud_pos.y = theme::clampf(m.hud_pos.y, 0.f, io.DisplaySize.y - size.y);
m.hud_pos = hud_editor::constrain(m.hud_pos,size,io.DisplaySize,false,10);
ImGui::SetNextWindowPos(m.hud_pos, ImGuiCond_Always);
ImGui::SetNextWindowSize(size, ImGuiCond_Always);
ImGui::SetNextWindowSize(m.hud_drag_size(), ImGuiCond_Always);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.f, 0.f));
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.f);
@@ -365,14 +478,14 @@ private:
if (!g_menu_open) flags |= ImGuiWindowFlags_NoInputs;
if (ImGui::Begin(id.c_str(), nullptr, flags)) {
ImGui::InvisibleButton("##drag", size);
ImGui::InvisibleButton("##drag", m.hud_drag_size());
const bool hovered = ImGui::IsItemHovered();
const bool active = ImGui::IsItemActive();
if (active && ImGui::IsMouseDragging(ImGuiMouseButton_Left, 0.f)) {
m.hud_pos.x += io.MouseDelta.x;
m.hud_pos.y += io.MouseDelta.y;
}
if(ImGui::IsItemActivated())hud_drag_.begin(m.hud_pos,io.MousePos);
if(g_menu_open && active && ImGui::IsMouseDragging(ImGuiMouseButton_Left,0.f))
m.hud_pos=hud_drag_.move(io.MousePos,size,io.DisplaySize,
hud_editor::options.snap && !io.KeyShift,hud_editor::options.grid_size);
const ImVec4 col = (hovered || active) ? theme::focus() : theme::hover();
ImGui::GetForegroundDrawList()->AddRect(
+3 -2
View File
@@ -5,7 +5,8 @@
// optional fallback if the Segoe UI files can't be found
#if __has_include("../font_data.h")
#include "../font_data.h"
const unsigned char* amnesia_fallback_font();
int amnesia_fallback_font_size();
#define AMNESIA_HAS_FONT 1
#else
#define AMNESIA_HAS_FONT 0
@@ -55,7 +56,7 @@ namespace fonts {
#if AMNESIA_HAS_FONT
ImFontConfig cfg;
cfg.FontDataOwnedByAtlas = false;
return io.Fonts->AddFontFromMemoryTTF((void*)k_font_data, (int)k_font_size, size, &cfg);
return io.Fonts->AddFontFromMemoryTTF((void*)amnesia_fallback_font(), amnesia_fallback_font_size(), size, &cfg);
#else
return io.Fonts->AddFontDefault();
#endif
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <algorithm>
#include "fonts.h"
#include "theme.h"
namespace hud_card {
inline constexpr float pad_x = 12.f, pad_y = 7.f, gap = 6.f;
inline ImVec2 size(const char* label, const char* value, float scale, const char* reserve = "") {
const auto a = fonts::text_size(fonts::body, fonts::k_body_size, label);
const auto b = fonts::text_size(fonts::semibold, fonts::k_body_size, value);
const auto c = fonts::text_size(fonts::semibold, fonts::k_body_size, reserve);
return ImVec2((pad_x * 2 + a.x + (a.x > 0 ? gap : 0) + (std::max)(b.x, c.x)) * scale,
(pad_y * 2 + (std::max)(a.y, b.y)) * scale);
}
inline void background(ImDrawList* draw, ImVec2 pos, ImVec2 size, float scale, bool enabled, float alpha = 1.f) {
if (!enabled) return;
const ImVec2 end(pos.x + size.x, pos.y + size.y);
draw->AddRectFilled(pos, end, theme::u32(theme::with_alpha(theme::surface(), .85f * alpha)), 10.f * scale);
draw->AddRect(pos, end, theme::u32(theme::with_alpha(theme::line(), alpha)), 10.f * scale, 0, scale);
}
inline void text(ImDrawList* draw, ImFont* font, float scale, ImVec2 pos, ImU32 color, const char* value, bool card) {
if (!card) draw->AddText(font, fonts::k_body_size * scale, ImVec2(pos.x + scale, pos.y + scale),
theme::u32(theme::with_alpha(theme::bg(), .7f)), value);
draw->AddText(font, fonts::k_body_size * scale, pos, color, value);
}
inline void draw(ImVec2 pos, const char* label, const char* value, float scale, bool card, ImU32 color, const char* reserve = "") {
auto* draw = ImGui::GetBackgroundDrawList(); const auto bounds = size(label, value, scale, reserve);
background(draw, pos, bounds, scale, card);
const auto a = fonts::text_size(fonts::body, fonts::k_body_size, label);
const float y = pos.y + pad_y * scale;
text(draw, fonts::body, scale, ImVec2(pos.x + pad_x * scale, y), theme::u32(theme::muted()), label, card);
text(draw, fonts::semibold, scale, ImVec2(pos.x + (pad_x + a.x + (a.x > 0 ? gap : 0)) * scale, y), color, value, card);
}
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <algorithm>
#include <cmath>
#include "imgui.h"
namespace hud_editor {
struct preferences {bool snap=true,show_grid=true;int grid_size=10;};
inline preferences options;
inline ImVec2 constrain(ImVec2 position,ImVec2 size,ImVec2 screen,bool snap,int spacing) {
const float step=float(std::clamp(spacing,4,64));
if(snap){position.x=std::round(position.x/step)*step;position.y=std::round(position.y/step)*step;}
return {std::clamp(position.x,0.f,(std::max)(0.f,screen.x-size.x)),
std::clamp(position.y,0.f,(std::max)(0.f,screen.y-size.y))};
}
struct drag {
ImVec2 start{},mouse{};
void begin(ImVec2 position,ImVec2 cursor){start=position;mouse=cursor;}
ImVec2 move(ImVec2 cursor,ImVec2 size,ImVec2 screen,bool snap,int spacing) const {
// Keep the unsnapped mouse displacement so small movements accumulate.
return constrain({start.x+cursor.x-mouse.x,start.y+cursor.y-mouse.y},size,screen,snap,spacing);
}
};
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <algorithm>
#include <chrono>
#include <cmath>
#include <deque>
#include <string>
#include <mutex>
#include "fonts.h"
#include "theme.h"
namespace notifications {
enum class kind { info,success,warning,error };
inline double now() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
struct toast {
std::string key,title,body;
kind type=kind::info;
double born=0,duration=3;
float progress=-1,y=-1;
};
inline std::deque<toast> items;
inline std::mutex mutex;
inline void dismiss(const std::string& key) {
std::lock_guard lock(mutex);
for(auto& item:items) if(item.key==key) item.duration=(std::max)(0.001,now()-item.born);
}
inline void push(std::string title,std::string body,kind type=kind::info,double duration=3,
std::string key={},float progress=-1) {
std::lock_guard lock(mutex);
if(!key.empty()) for(auto& item:items) if(item.key==key) {
const bool changed=item.title!=title || item.type!=type || item.duration!=duration;
item.title=std::move(title);item.body=std::move(body);item.type=type;
item.duration=duration;item.progress=progress;if(changed) item.born=now();return;
}
if(items.size()>=6) {
auto removable=std::find_if(items.begin(),items.end(),[](const toast& t){return t.duration>0;});
if(removable!=items.end()) items.erase(removable);else items.pop_front();
}
items.push_back({std::move(key),std::move(title),std::move(body),type,now(),duration,progress,-1});
}
inline float entrance(float t) {t=std::clamp(t,0.f,1.f);return 1-(1-t)*(1-t);}
inline void draw() {
std::lock_guard lock(mutex);const double time=now();
for(auto it=items.begin();it!=items.end();) {
if(it->duration>0 && time-it->born>it->duration+.2)it=items.erase(it);else ++it;
}
const auto& io=ImGui::GetIO();auto* draw=ImGui::GetForegroundDrawList();
const float width=std::clamp(io.DisplaySize.x-24.f,140.f,300.f);float y=16;int shown=0;
for(auto it=items.rbegin();it!=items.rend() && shown<3;++it,++shown) {
auto& item=*it;const float age=float(time-item.born),in=std::clamp(age/.18f,0.f,1.f);
const float out=item.duration>0 ? std::clamp((age-float(item.duration))/.2f,0.f,1.f) : 0;
const float alpha=entrance(in)*(1-out);
if(item.y<0)item.y=y;item.y+=(y-item.y)*(1-std::exp(-16.f*io.DeltaTime));
const float x=io.DisplaySize.x-width-16+(1-entrance(in)+out)*8;
fonts::push_font(fonts::body,fonts::k_body_size);
const auto body=ImGui::CalcTextSize(item.body.c_str(),nullptr,false,width-24);ImGui::PopFont();
const float height=28+(item.body.empty() ? 0 : body.y+5)+(item.progress>=0 ? 8 : 0);
auto color=[&](ImVec4 c){c.w*=alpha;return ImGui::ColorConvertFloat4ToU32(c);};
draw->AddRectFilled({x,item.y},{x+width,item.y+height},color(theme::with_alpha(theme::surface(),.85f)),10);
draw->AddRect({x,item.y},{x+width,item.y+height},color(theme::line()),10);
draw->PushClipRect({x+12,item.y},{x+width-12,item.y+height},true);
draw->AddText(fonts::semibold,fonts::k_body_size,{x+12,item.y+7},color(item.type==kind::error ? theme::danger() : theme::fg()),item.title.c_str());
if(!item.body.empty())draw->AddText(fonts::body,fonts::k_body_size,{x+12,item.y+26},color(theme::muted()),item.body.c_str(),nullptr,width-24);
if(item.progress>=0) {
const float p=std::isfinite(item.progress) ? std::clamp(item.progress,0.f,1.f) : 0;
draw->AddRectFilled({x+12,item.y+height-7},{x+width-12,item.y+height-4},color(theme::line()),2);
draw->AddRectFilled({x+12,item.y+height-7},{x+12+(width-24)*p,item.y+height-4},color(theme::accent()),2);
}
draw->PopClipRect();y+=height+8;
}
}
}
+75 -4
View File
@@ -1,6 +1,7 @@
#pragma once
#include <windows.h>
#include <atomic>
#include <array>
#include "MinHook.h"
#include "imgui.h"
#include "imgui_impl_win32.h"
@@ -11,13 +12,67 @@ inline std::atomic<bool> g_menu_open{ false };
namespace input {
inline constexpr ULONG_PTR sprint_input_tag = 0x414d535052494e54ull;
inline std::array<std::atomic<bool>, 256> physical_keys{};
inline std::atomic<uint64_t> activity_sequence{0};
inline std::atomic<unsigned> left_clicks{0}, right_clicks{0};
inline HWND hooked_window = nullptr;
using inventory_handler_fn=bool(*)(HWND,UINT,WPARAM,LPARAM);
inline std::atomic<inventory_handler_fn> inventory_handler{nullptr};
inline std::atomic<void(*)()> focus_lost_handler{nullptr};
inline std::atomic<bool> freelook_enabled{false}, freelook_supported{false}, in_world{false};
inline std::atomic<int> freelook_key{VK_LMENU}, look_dx{0}, look_dy{0};
inline std::atomic<float> look_sensitivity{.15f};
inline bool freelook_active() {
const int key=freelook_key.load(); CURSORINFO cursor{sizeof(cursor)};
return freelook_enabled && freelook_supported && in_world && !g_menu_open && hooked_window &&
GetForegroundWindow()==hooked_window && key>0 && key<256 && (GetAsyncKeyState(key)&0x8000) &&
GetCursorInfo(&cursor) && !(cursor.flags&CURSOR_SHOWING);
}
inline void observe_message(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
if (msg == WM_KILLFOCUS) {
for (auto& key : physical_keys) key.store(false, std::memory_order_relaxed);
}
if (GetMessageExtraInfo() == static_cast<LPARAM>(sprint_input_tag)) return;
if(msg==WM_KEYDOWN || msg==WM_KEYUP || msg==WM_SYSKEYDOWN || msg==WM_SYSKEYUP ||
msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || msg==WM_LBUTTONUP || msg==WM_RBUTTONDOWN || msg==WM_RBUTTONDBLCLK || msg==WM_RBUTTONUP ||
msg==WM_MBUTTONDOWN || msg==WM_MBUTTONDBLCLK || msg==WM_MBUTTONUP || msg==WM_MOUSEWHEEL || msg==WM_XBUTTONDOWN || msg==WM_XBUTTONDBLCLK || msg==WM_XBUTTONUP)
++activity_sequence;
const int mouse_key=(msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || msg==WM_LBUTTONUP) ? VK_LBUTTON :
(msg==WM_RBUTTONDOWN || msg==WM_RBUTTONDBLCLK || msg==WM_RBUTTONUP) ? VK_RBUTTON :
(msg==WM_MBUTTONDOWN || msg==WM_MBUTTONDBLCLK || msg==WM_MBUTTONUP) ? VK_MBUTTON :
(msg==WM_XBUTTONDOWN || msg==WM_XBUTTONDBLCLK || msg==WM_XBUTTONUP) ? (HIWORD(wp)==XBUTTON1 ? VK_XBUTTON1 : VK_XBUTTON2) : 0;
if(mouse_key)physical_keys[mouse_key]=(msg!=WM_LBUTTONUP && msg!=WM_RBUTTONUP && msg!=WM_MBUTTONUP && msg!=WM_XBUTTONUP);
if(msg==WM_INPUT) {
RAWINPUT raw{};UINT size=sizeof(raw);
if(GetRawInputData(reinterpret_cast<HRAWINPUT>(lp),RID_INPUT,&raw,&size,sizeof(RAWINPUTHEADER))!=UINT(-1) &&
raw.header.dwType==RIM_TYPEMOUSE && raw.data.mouse.ulExtraInformation!=DWORD(sprint_input_tag) &&
(raw.data.mouse.lLastX || raw.data.mouse.lLastY || raw.data.mouse.usButtonFlags))++activity_sequence;
}
if (msg == WM_KEYDOWN || msg == WM_KEYUP || msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP) {
int vk = static_cast<int>(wp);
const bool down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
if (vk >= 0 && vk < 256) physical_keys[vk].store(down, std::memory_order_relaxed);
if (vk == VK_CONTROL) vk = (lp & (1ll << 24)) ? VK_RCONTROL : VK_LCONTROL;
else if (vk == VK_MENU) vk = (lp & (1ll << 24)) ? VK_RMENU : VK_LMENU;
else if (vk == VK_SHIFT) vk = MapVirtualKeyW((lp >> 16) & 0xff, MAPVK_VSC_TO_VK_EX);
if (vk >= 0 && vk < 256) physical_keys[vk].store(down, std::memory_order_relaxed);
}
if (!g_menu_open && GetForegroundWindow() == hwnd) {
if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) ++left_clicks;
if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) ++right_clicks;
}
}
using set_cursor_pos_fn = BOOL(WINAPI*)(int, int);
using clip_cursor_fn = BOOL(WINAPI*)(const RECT*);
inline WNDPROC o_wnd_proc = nullptr;
inline HWND hooked_window = nullptr;
inline set_cursor_pos_fn o_set_cursor_pos = nullptr;
inline clip_cursor_fn o_clip_cursor = nullptr;
inline void* set_cursor_target = nullptr;
inline void* clip_cursor_target = nullptr;
// the clip rect the game had before the menu opened, and anything it asked for while the menu was open
inline RECT saved_clip{};
@@ -51,6 +106,10 @@ namespace input {
clip_cursor_fn clip = o_clip_cursor ? o_clip_cursor : ClipCursor;
if (wanted_set) clip(wanted_null ? nullptr : &wanted_clip);
else clip(&saved_clip);
// Ask the game to select the right gameplay/inventory cursor on its own
// window thread; a Present-thread SetCursor call cannot restore that state.
if(hooked_window && GetForegroundWindow()==hooked_window)
PostMessageW(hooked_window,WM_SETCURSOR,reinterpret_cast<WPARAM>(hooked_window),MAKELPARAM(HTCLIENT,WM_MOUSEMOVE));
}
// messages the game must not see while the menu is open
@@ -90,6 +149,13 @@ namespace input {
WPARAM wp,
LPARAM lp
) {
if(msg==WM_KILLFOCUS)if(auto handler=focus_lost_handler.load())handler();
observe_message(hwnd, msg, wp, lp);
if(auto handler=inventory_handler.load();handler && handler(hwnd,msg,wp,lp))return 0;
// Bedrock's input pipeline receives mouse movement normally. Freelook
// captures native turn deltas and restores player angles before rendering;
// Win32 raw messages are not its source of camera movement.
if(freelook_active() && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || msg==WM_RBUTTONDOWN || msg==WM_RBUTTONDBLCLK))return 0;
// always feed imgui while the menu is open
if (g_menu_open.load()) {
ImGui_ImplWin32_WndProcHandler(hwnd, msg, wp, lp);
@@ -117,11 +183,16 @@ namespace input {
if (!hwnd || !IsWindow(hwnd)) return false;
hooked_window = hwnd;
for (int vk = 0; vk < 256; ++vk)
physical_keys[vk].store((GetAsyncKeyState(vk) & 0x8000) != 0, std::memory_order_relaxed);
o_wnd_proc = (WNDPROC)SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)wnd_proc);
MH_CreateHookApi(L"user32", "SetCursorPos", (LPVOID)&hk_set_cursor_pos, (LPVOID*)&o_set_cursor_pos);
MH_CreateHookApi(L"user32", "ClipCursor", (LPVOID)&hk_clip_cursor, (LPVOID*)&o_clip_cursor);
MH_EnableHook(MH_ALL_HOOKS);
if (MH_CreateHookApiEx(L"user32", "SetCursorPos", (LPVOID)&hk_set_cursor_pos,
(LPVOID*)&o_set_cursor_pos, &set_cursor_target) == MH_OK)
MH_EnableHook(set_cursor_target);
if (MH_CreateHookApiEx(L"user32", "ClipCursor", (LPVOID)&hk_clip_cursor,
(LPVOID*)&o_clip_cursor, &clip_cursor_target) == MH_OK)
MH_EnableHook(clip_cursor_target);
return o_wnd_proc != nullptr;
}
+52
View File
@@ -17,6 +17,19 @@
#include "modules/optimizations.h"
#include "modules/macro.h"
#include "modules/fullbright.h"
#include "modules/fov_changer.h"
#include "modules/zoom.h"
#include "modules/glint_changer.h"
#include "modules/music_player.h"
#include "modules/inventory_tools.h"
#include "modules/anti_afk.h"
#include "modules/server_hud.h"
#include "modules/viewmodel.h"
#include "modules/toggle_sprint.h"
#include "modules/cps_counter.h"
#include "modules/clock.h"
#include "modules/world_modules.h"
#include "gui/notifications.h"
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
@@ -39,6 +52,7 @@ HRESULT __stdcall hk_present(IDXGISwapChain* sc, UINT sync, UINT flags) {
return o_present(sc, sync, flags);
g_device->GetImmediateContext(&g_ctx);
media_art::device=g_device;
DXGI_SWAP_CHAIN_DESC desc;
sc->GetDesc(&desc);
@@ -62,15 +76,27 @@ HRESULT __stdcall hk_present(IDXGISwapChain* sc, UINT sync, UINT flags) {
}
if (rtv) {
const auto scene=world::latest();
if(!world::fresh(*scene)) input::in_world=false;
CURSORINFO cursor{sizeof(cursor)};
if(world::fresh(*scene) && GetCursorInfo(&cursor) && !(cursor.flags&CURSOR_SHOWING) && world_filter::enabled) {
static bool filter_warning=false;
const bool applied=world_filter::apply(g_device,g_ctx,rtv);
if(!applied && !filter_warning) notifications::push("World tint unavailable","This render target does not support the world color filter. Fog color remains available.",notifications::kind::warning,5,"world_filter");
filter_warning=!applied;
}
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (!profiles().ready()) profiles().initialize(modules());
gui().update(); // menu key, esc, animations
if (!g_menu_open) modules().update_keys(); // toggle keys are ignored while the menu is open
gui().draw_backdrop();
modules().render();
gui().draw();
profiles().tick(notifications::now());
notifications::draw();
ImGui::Render();
g_ctx->OMSetRenderTargets(1, &rtv, nullptr);
@@ -117,6 +143,7 @@ static void* get_present_address() {
DWORD WINAPI main_thread(LPVOID) {
MH_Initialize();
world::initialize();
modules().add<fps_counter>()->set_enabled(true);
modules().add<keystrokes>()->set_enabled(true);
@@ -125,6 +152,27 @@ DWORD WINAPI main_thread(LPVOID) {
modules().add<optimizations>();
modules().add<macro>();
modules().add<fullbright>(); // scans for its signature here; can take a couple of seconds
modules().add<fov_changer>();
modules().add<zoom>();
modules().add<glint_changer>();
modules().add<music_player>();
modules().add<inventory_tools_module>();
modules().add<anti_afk>();
modules().add<tab_list>();
modules().add<xp_progress_hud>();
modules().add<viewmodel>();
modules().add<toggle_sprint>();
modules().add<cps_counter>();
modules().add<clock_hud>();
modules().add<block_outlines>();
modules().add<atmosphere>();
modules().add<armor_hud>();
modules().add<name_changer>();
modules().add<better_nametags>();
modules().add<target_hud>();
modules().add<client_time>();
modules().add<freelook>();
modules().add<coordinates_hud>();
void* present = get_present_address();
if (!present) { MessageBoxA(nullptr, "couldn't find Present!", "amnesia", MB_OK); return 1; }
@@ -140,7 +188,11 @@ extern "C" __declspec(dllexport) DWORD WINAPI unload(LPVOID) {
input::uninstall(); // restores the game's window proc (and the cursor if the menu was open)
Sleep(300); // let any in-flight Present / window messages finish
profiles().shutdown(); // save enabled states before clear() disables them
modules().clear();
media::shutdown();
media_art::device=nullptr;
world_filter::shutdown();
if (g_init) {
ImGui_ImplDX11_Shutdown();
+74
View File
@@ -0,0 +1,74 @@
#pragma once
#include "text_hud.h"
#include "anti_afk_engine.h"
#include "../input.h"
#include "../game/world.h"
#include <cstdio>
#include <mutex>
class anti_afk : public text_hud {
public:
anti_afk():text_hud("anti afk","periodic movement while idle; pauses in menus and when unfocused",category::utility) {
hud_pos={10,690};label_="anti afk";reserve_="next 300s";
mode_=&add_mode("action",{"jump","alternating strafe","jump + alternating strafe"},2);
interval_=&add_int("idle interval (seconds)",30,10,300);
hold_=&add_int("key hold (ms)",150,50,1000);
jump_=&add_key("jump key",VK_SPACE);left_=&add_key("left key",'A');right_=&add_key("right key",'D');
status_=&add_toggle("show status",true);
instance_=this;
}
~anti_afk() override {release();}
bool is_hud() const override{return status_->bool_value;}
bool consumes_key(int key) const override {
std::lock_guard lock(mutex_);
return engine_.active() && !physical(key) &&
(key==cached_config_.jump || key==cached_config_.left || key==cached_config_.right);
}
void on_enable() override {
release();{std::lock_guard lock(mutex_);if(!engine_.active())engine_={};world_id_=0;}
input::focus_lost_handler=&focus_lost;update();
}
void on_disable() override {input::focus_lost_handler=nullptr;release();}
void on_frame_end() override {update();}
void on_render() override {
update();const auto cfg=settings_config();
char value[40];
{std::lock_guard lock(mutex_);
if(!eligible_)snprintf(value,sizeof(value),"paused");
else if(engine_.active())snprintf(value,sizeof(value),"active");
else snprintf(value,sizeof(value),"next %llus",(engine_.remaining(GetTickCount64(),cfg)+999)/1000);
}
text_=value;if(status_->bool_value)draw_text();
}
private:
setting *mode_,*interval_,*hold_,*jump_,*left_,*right_,*status_;
anti_afk_logic::engine engine_;uint64_t world_id_=0;bool eligible_=false;
mutable std::mutex mutex_;anti_afk_logic::config cached_config_;
static inline anti_afk* instance_=nullptr;
static void focus_lost() {
auto* self=instance_;if(!self)return;
std::lock_guard lock(self->mutex_);self->eligible_=false;
self->engine_.update(GetTickCount64(),false,input::activity_sequence.load(),false,self->cached_config_,physical,send);
}
static bool physical(int key){return key>0 && key<256 && input::physical_keys[key].load();}
static bool send(int key,bool down) {
INPUT event{};event.type=INPUT_KEYBOARD;event.ki.wVk=WORD(key);
event.ki.wScan=WORD(MapVirtualKeyW(key,MAPVK_VK_TO_VSC));event.ki.dwFlags=down ? 0 : KEYEVENTF_KEYUP;
if(key==VK_RCONTROL || key==VK_RMENU || (key>=VK_PRIOR && key<=VK_DOWN))event.ki.dwFlags|=KEYEVENTF_EXTENDEDKEY;
event.ki.dwExtraInfo=input::sprint_input_tag;
return SendInput(1,&event,sizeof(event))==1;
}
void release(){std::lock_guard lock(mutex_);engine_.stop(physical,send);}
anti_afk_logic::config settings_config() const {
return {std::clamp(mode_->int_value,0,2),jump_->int_value,left_->int_value,right_->int_value,
uint64_t(std::clamp(interval_->int_value,10,300))*1000,uint64_t(std::clamp(hold_->int_value,50,1000))};
}
void update() {
const auto frame=world::latest();CURSORINFO cursor{sizeof(cursor)};
const bool allowed=world::fresh(*frame) && !g_menu_open && is_game_focused() && GetCursorInfo(&cursor) && !(cursor.flags&CURSOR_SHOWING);
bool held=false;for(int key=1;key<256;++key)if(physical(key)){held=true;break;}
std::lock_guard lock(mutex_);eligible_=allowed;cached_config_=settings_config();
const bool changed=world_id_!=frame->world_id;world_id_=frame->world_id;
engine_.update(GetTickCount64(),eligible_ && !changed,input::activity_sequence.load(),held,cached_config_,physical,send);
}
};
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <cstdint>
#include <algorithm>
#include "sprint_latch.h"
namespace anti_afk_logic {
struct config {int mode=2,jump=32,left='A',right='D';uint64_t interval=30000,hold=150;};
class engine {
public:
bool active() const{return jump_.held_key() || move_.held_key();}
uint64_t remaining(uint64_t now,config const& settings) const {
return now<idle_since_+settings.interval ? idle_since_+settings.interval-now : 0;
}
template<class Physical,class Send> void stop(Physical physical,Send send) {
jump_.update(false,0,physical,send);move_.update(false,0,physical,send);pulsing_=false;
}
template<class Physical,class Send> void update(uint64_t now,bool eligible,uint64_t activity,bool user_held,
config const& settings,Physical physical,Send send) {
const bool changed=mode_!=settings.mode || jump_key_!=settings.jump || left_!=settings.left || right_!=settings.right;
if(!initialized_ || !eligible || !eligible_before_ || activity!=activity_ || user_held || changed) {
stop(physical,send);initialized_=true;activity_=activity;idle_since_=now;
eligible_before_=eligible;
mode_=settings.mode;jump_key_=settings.jump;left_=settings.left;right_=settings.right;
return;
}
if(pulsing_) {
if(now>=release_at_)stop(physical,send);
return;
}
// Retry a failed key-up before starting another movement pulse.
if(active()){stop(physical,send);return;}
if(now<idle_since_+settings.interval)return;
const int direction=right_next_ ? settings.right : settings.left;
const auto valid=[](int key){return key>0 && key<256;};
if(settings.mode!=1 && valid(settings.jump))jump_.update(true,settings.jump,physical,send);
if(settings.mode!=0 && valid(direction) && (settings.mode==1 || direction!=settings.jump))move_.update(true,direction,physical,send);
right_next_=!right_next_;idle_since_=now;
pulsing_=active();release_at_=now+std::clamp<uint64_t>(settings.hold,50,1000);
}
private:
sprint_latch jump_,move_;bool initialized_=false,pulsing_=false,right_next_=false,eligible_before_=false;
uint64_t idle_since_=0,release_at_=0,activity_=0;
int mode_=-1,jump_key_=0,left_=0,right_=0;
};
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <cstdio>
#include "text_hud.h"
class clock_hud : public text_hud {
public:
clock_hud() : text_hud("clock", "shows your computer's local time") {
hud_pos = ImVec2(10.f, 230.f);
label_ = "clock"; reserve_ = "00:00:00 PM";
twenty_four_ = &add_toggle("24 hour", true);
seconds_ = &add_toggle("seconds", false);
text_ = "00:00";
}
void on_render() override {
SYSTEMTIME time;
GetLocalTime(&time);
char buf[32];
const unsigned hour = twenty_four_->bool_value ? time.wHour : (time.wHour % 12 ? time.wHour % 12 : 12);
if (seconds_->bool_value) snprintf(buf, sizeof(buf), "%02u:%02u:%02u", hour, time.wMinute, time.wSecond);
else snprintf(buf, sizeof(buf), "%02u:%02u", hour, time.wMinute);
text_ = buf;
if (!twenty_four_->bool_value) text_ += time.wHour < 12 ? " AM" : " PM";
draw_text();
}
private:
setting* twenty_four_;
setting* seconds_;
};
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <deque>
#include <cstdio>
#include "text_hud.h"
#include "../input.h"
class cps_counter : public text_hud {
public:
cps_counter() : text_hud("cps counter", "left and right clicks per second") {
hud_pos = ImVec2(10.f, 185.f);
label_ = "cps"; reserve_ = "L 00 | R 00";
text_ = "L 0 | R 0";
}
void on_enable() override { reset(); }
void on_disable() override { reset(); }
void on_render() override {
const double now = ImGui::GetTime();
const unsigned left = input::left_clicks.load(), right = input::right_clicks.load();
if (!is_game_focused() || g_menu_open) {
reset();
} else {
if (left != last_left_ || right != last_right_)
samples_.push_back({now, left - last_left_, right - last_right_});
last_left_ = left;
last_right_ = right;
while (!samples_.empty() && samples_.front().time <= now - 1.0) samples_.pop_front();
unsigned l = 0, r = 0;
for (const auto& sample : samples_) { l += sample.left; r += sample.right; }
char buf[64];
snprintf(buf, sizeof(buf), "L %u | R %u", l, r);
text_ = buf;
}
draw_text();
}
private:
struct sample { double time; unsigned left, right; };
std::deque<sample> samples_;
unsigned last_left_ = 0, last_right_ = 0;
void reset() {
samples_.clear();
last_left_ = input::left_clicks.load();
last_right_ = input::right_clicks.load();
text_ = "L 0 | R 0";
}
};
+117 -28
View File
@@ -1,38 +1,127 @@
#pragma once
#include "module.h"
#include "../input.h"
#include "crosshair_animation.h"
#include "../game/hook.h"
#include "../game/signatures.h"
class crosshair : public module {
public:
crosshair()
: module("crosshair", "draws a custom crosshair at the center of the screen",
category::visual, VK_F8) {
length_ = &add_float("length", 8.f, 2.f, 30.f);
gap_ = &add_float("gap", 4.f, 0.f, 20.f);
thickness_ = &add_float("thickness", 2.f, 1.f, 8.f);
dot_ = &add_toggle("center dot", false);
color_ = &add_color("color", 1.f, 1.f, 1.f, 0.9f);
crosshair() : module("custom crosshair", "custom colors, gradient, spin, and pulsing or reactive arms", category::visual, VK_F8) {
length_=&add_float("length",8.f,1.f,60.f);
width_=&add_float("width",2.f,0.5f,12.f);
gap_=&add_float("gap",4.f,0.f,40.f);
dynamic_gap_=&add_toggle("dynamic gap",false);
gap_mode_=&add_mode("dynamic gap mode",{"pulse","movement / clicks"});
gap_amount_=&add_float("dynamic gap amount",8.f,0.f,40.f);
gap_speed_=&add_float("dynamic gap speed",2.f,0.1f,10.f);
gap_easing_=&add_mode("dynamic gap easing",easings());
dynamic_length_=&add_toggle("dynamic length",false);
length_mode_=&add_mode("dynamic length mode",{"pulse","movement / clicks"});
length_amount_=&add_float("dynamic length amount",6.f,0.f,40.f);
length_speed_=&add_float("dynamic length speed",2.f,0.1f,10.f);
length_easing_=&add_mode("dynamic length easing",easings());
color_=&add_color("color",1.f,1.f,1.f,0.9f);
gradient_=&add_toggle("gradient",false);
gradient_color_=&add_color("gradient color",0.4f,0.7f,1.f,0.9f);
spin_=&add_toggle("spin",false);
spin_speed_=&add_float("spin speed (degrees/s)",90.f,0.f,720.f);
spin_easing_=&add_mode("spin easing",easings());
dot_=&add_toggle("center dot",false);
outline_=&add_toggle("black outline",false);
outline_width_=&add_float("outline width",1.f,0.5f,4.f);
instance_=this;
if (!native_hook_.install("render_native_crosshair",sigs::render_native_crosshair,
reinterpret_cast<void*>(&native_detour),reinterpret_cast<void**>(&original_native_),true))
set_description("custom crosshair; hiding the native crosshair is unavailable for this game version");
}
void on_enable() override {
reset();
suppress_native_.store(true,std::memory_order_relaxed);
if (!native_hook_.set_enabled(true))
set_description("custom crosshair; could not enable native crosshair hiding");
}
void on_disable() override {
suppress_native_.store(false,std::memory_order_relaxed);
native_hook_.set_enabled(false);
reset();
}
void on_render() override {
ImGuiIO& io = ImGui::GetIO();
ImDrawList* dl = ImGui::GetBackgroundDrawList();
const ImVec2 c(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f);
const float len = length_->float_value, gap = gap_->float_value;
const float h = thickness_->float_value * 0.5f;
const ImU32 col = setting_color(*color_);
dl->AddRectFilled(ImVec2(c.x - h, c.y - gap - len), ImVec2(c.x + h, c.y - gap), col); // top
dl->AddRectFilled(ImVec2(c.x - h, c.y + gap), ImVec2(c.x + h, c.y + gap + len), col); // bottom
dl->AddRectFilled(ImVec2(c.x - gap - len, c.y - h), ImVec2(c.x - gap, c.y + h), col); // left
dl->AddRectFilled(ImVec2(c.x + gap, c.y - h), ImVec2(c.x + gap + len, c.y + h), col); // right
if (dot_->bool_value)
dl->AddRectFilled(ImVec2(c.x - h, c.y - h), ImVec2(c.x + h, c.y + h), col);
const ImGuiIO& io=ImGui::GetIO();
const bool clicking=is_key_down(VK_LBUTTON)||is_key_down(VK_RBUTTON);
const unsigned left=input::left_clicks.load(),right=input::right_clicks.load();
if (!g_menu_open && (clicking || left!=last_left_ || right!=last_right_)) click_until_=ImGui::GetTime()+0.12;
last_left_=left;last_right_=right;
const bool reacting=!g_menu_open && is_game_focused() && (is_key_down('W') || is_key_down('A') ||
is_key_down('S') || is_key_down('D') || is_key_down(VK_SPACE) || ImGui::GetTime()<click_until_);
const float gap=gap_->float_value+gap_amount_->float_value*gap_anim_.update(io.DeltaTime,
dynamic_gap_->bool_value,gap_mode_->int_value,reacting,gap_speed_->float_value,gap_easing_->int_value);
const float length=length_->float_value+length_amount_->float_value*length_anim_.update(io.DeltaTime,
dynamic_length_->bool_value,length_mode_->int_value,reacting,length_speed_->float_value,length_easing_->int_value);
const float angle=crosshair_animation::spin(spin_phase_,io.DeltaTime,spin_->bool_value,
spin_speed_->float_value,spin_easing_->int_value);
const ImVec2 center(io.DisplaySize.x*0.5f,io.DisplaySize.y*0.5f);
ImDrawList* dl=ImGui::GetBackgroundDrawList();
const ImU32 inner=setting_color(*color_),outer=gradient_->bool_value ? setting_color(*gradient_color_) : inner;
const ImVec2 uv=ImGui::GetFontTexUvWhitePixel();
// Draw all outlines first so overlaps cannot cover another arm's colored fill.
if(outline_->bool_value) {
const float border=outline_width_->float_value;
const ImU32 black=IM_COL32(0,0,0,255);
for(int arm=0;arm<4;++arm) {
const float a=angle+arm*1.5707963267948966f;
const float x=std::cos(a),y=std::sin(a),h=width_->float_value*0.5f+border;
const float start=gap-border,end=gap+length+border;
const ImVec2 points[] = {
{center.x+x*start-y*h,center.y+y*start+x*h},
{center.x+x*end-y*h,center.y+y*end+x*h},
{center.x+x*end+y*h,center.y+y*end-x*h},
{center.x+x*start+y*h,center.y+y*start-x*h}
};
dl->AddQuadFilled(points[0],points[3],points[2],points[1],black);
}
if(dot_->bool_value) dl->AddCircleFilled(center,width_->float_value*0.5f+border,black,16);
}
for(int arm=0;arm<4;++arm) {
const float a=angle+arm*1.5707963267948966f;
const float x=std::cos(a),y=std::sin(a),h=width_->float_value*0.5f;
const ImVec2 p0(center.x+x*gap-y*h,center.y+y*gap+x*h);
const ImVec2 p1(center.x+x*(gap+length)-y*h,center.y+y*(gap+length)+x*h);
const ImVec2 p2(center.x+x*(gap+length)+y*h,center.y+y*(gap+length)-x*h);
const ImVec2 p3(center.x+x*gap+y*h,center.y+y*gap-x*h);
dl->PrimReserve(6,4);
const unsigned idx=dl->_VtxCurrentIdx;
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx));
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx+1));
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx+2));
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx));
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx+2));
dl->PrimWriteIdx(static_cast<ImDrawIdx>(idx+3));
dl->PrimWriteVtx(p0,uv,inner); dl->PrimWriteVtx(p1,uv,outer);
dl->PrimWriteVtx(p2,uv,outer); dl->PrimWriteVtx(p3,uv,inner);
}
if(dot_->bool_value) dl->AddCircleFilled(center,width_->float_value*0.5f,inner,16);
}
private:
setting* length_ = nullptr;
setting* gap_ = nullptr;
setting* thickness_ = nullptr;
setting* dot_ = nullptr;
setting* color_ = nullptr;
static std::vector<std::string> easings() { return {"linear","smooth","ease in","ease out","ease in/out"}; }
void reset() {
gap_anim_={};length_anim_={};spin_phase_=0;click_until_=0;
last_left_=input::left_clicks.load();last_right_=input::right_clicks.load();
}
setting *length_,*width_,*gap_,*dynamic_gap_,*gap_mode_,*gap_amount_,*gap_speed_,*gap_easing_;
setting *dynamic_length_,*length_mode_,*length_amount_,*length_speed_,*length_easing_;
setting *color_,*gradient_,*gradient_color_,*spin_,*spin_speed_,*spin_easing_,*dot_;
setting *outline_,*outline_width_;
using native_fn=void(__fastcall*)(void*,void*,void*,void*);
static inline crosshair* instance_=nullptr;
static inline native_fn original_native_=nullptr;
std::atomic<bool> suppress_native_{false};
game::game_hook native_hook_;
static void __fastcall native_detour(void* renderer,void* context,void* control,void* bounds) {
if (!instance_->suppress_native_.load(std::memory_order_relaxed))
original_native_(renderer,context,control,bounds);
}
crosshair_animation::channel gap_anim_,length_anim_;
double spin_phase_=0,click_until_=0;
unsigned last_left_=0,last_right_=0;
};
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include <algorithm>
#include <cmath>
namespace crosshair_animation {
inline float ease(float t, int mode) {
t = std::clamp(t, 0.f, 1.f);
switch (mode) {
case 1: return t*t*(3.f-2.f*t); // smoothstep
case 2: return t*t*t;
case 3: return 1.f-std::pow(1.f-t,3.f);
case 4: return t<0.5f ? 4.f*t*t*t : 1.f-std::pow(-2.f*t+2.f,3.f)*0.5f;
default: return t;
}
}
struct channel {
double phase = 0;
float current = 0, start = 0, target = 0, progress = 1;
float update(float dt, bool enabled, int mode, bool reacting, float speed, int easing) {
if (!enabled) { *this = {}; return 0; }
dt = std::clamp(dt, 0.f, 0.25f);
speed = std::clamp(speed, 0.1f, 10.f);
if (mode == 0) {
phase = std::fmod(phase + dt*speed, 1.0);
const float triangle = 1.f-std::fabs(static_cast<float>(phase)*2.f-1.f);
current = ease(triangle,easing);
} else {
const float next = reacting ? 1.f : 0.f;
if (target != next) { start=current; target=next; progress=0; }
progress=std::clamp(progress+dt*speed,0.f,1.f);
current=start+(target-start)*ease(progress,easing);
}
return current;
}
};
inline float spin(double& phase, float dt, bool enabled, float speed, int easing) {
if (!enabled) { phase=0; return 0; }
phase=std::fmod(phase+std::clamp(dt,0.f,0.25f)*std::clamp(speed,0.f,720.f)/360.f,1.0);
return ease(static_cast<float>(phase),easing)*6.283185307179586f;
}
}
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <atomic>
#include <algorithm>
#include <cmath>
#include "module.h"
#include "../game/hook.h"
#include "../game/signatures.h"
namespace zoom_effect {
inline std::atomic<bool> supported{false};
inline std::atomic<float> magnification{1.f};
inline float apply(float degrees, float factor) {
if (!std::isfinite(degrees) || degrees <= 0 || degrees >= 180) return degrees;
if (!std::isfinite(factor) || factor <= 1) return degrees;
constexpr float rad = 3.14159265359f / 180.f;
return 2.f * std::atan(std::tan(degrees * rad * .5f) / std::clamp(factor, 1.f, 12.f)) / rad;
}
}
class fov_changer : public module {
public:
fov_changer() : module("fov changer", "sets the world field of view in degrees", category::visual) {
degrees_ = &add_float("fov", 90.f, 30.f, 130.f);
instance_ = this;
zoom_effect::supported = hook_.install("get_fov", sigs::get_fov,
reinterpret_cast<void*>(&detour), reinterpret_cast<void**>(&original_), true) && hook_.set_enabled(true);
if (!zoom_effect::supported)
set_description("unavailable: FOV signature missing or ambiguous for this game version");
}
void on_enable() override {
publish_fov();
if (!hook_.ok() || !hook_.set_enabled(true)) {
set_description("unavailable: could not enable the FOV hook");
set_enabled(false);
}
}
void on_disable() override {
override_degrees_.store(0.f, std::memory_order_relaxed);
}
void on_render() override { publish_fov(); }
private:
using get_fov_fn = float(__fastcall*)(void* renderer, float frame_alpha, bool world_projection);
static inline fov_changer* instance_ = nullptr;
static inline get_fov_fn original_ = nullptr;
void publish_fov() {
const float value = degrees_->float_value;
override_degrees_.store(std::isfinite(value) ? std::clamp(value, 30.f, 130.f) : 90.f,
std::memory_order_relaxed);
}
static float __fastcall detour(void* renderer, float frame_alpha, bool world_projection) {
const float vanilla = original_(renderer, frame_alpha, world_projection);
const float degrees = instance_->override_degrees_.load(std::memory_order_relaxed);
// Leave the separate hand/UI projection alone. No saved game settings are changed.
return world_projection ? zoom_effect::apply(degrees >= 30.f ? degrees : vanilla,
zoom_effect::magnification.load(std::memory_order_relaxed)) : vanilla;
}
setting* degrees_ = nullptr;
std::atomic<float> override_degrees_{0.f};
game::game_hook hook_;
};
+6 -59
View File
@@ -1,66 +1,13 @@
#pragma once
#include <cstdio>
#include "module.h"
#include "../gui/fonts.h"
#include "../gui/theme.h"
class fps_counter : public module {
#include "text_hud.h"
class fps_counter : public text_hud {
public:
fps_counter()
: module("fps counter", "shows your current fps", category::hud, VK_F6) {
hud_pos = ImVec2(10.f, 10.f);
background_ = &add_toggle("background", true);
scale_ = &add_float("scale", 1.f, 0.7f, 2.5f);
const ImVec4 fg = theme::fg();
color_ = &add_color("color", fg.x, fg.y, fg.z);
fps_counter() : text_hud("fps counter", "shows your current fps", category::hud, VK_F6) {
label_ = "fps"; text_ = "0"; reserve_ = "000"; hud_pos = ImVec2(10, 10);
}
bool is_hud() const override { return true; }
ImVec2 hud_size() const override {
const float s = scale_->float_value;
const ImVec2 label = fonts::text_size(fonts::body, fonts::k_body_size, "fps");
const ImVec2 value = fonts::text_size(fonts::semibold, fonts::k_body_size, "000"); // fixed width, no jitter
return ImVec2((pad_x * 2.f + label.x + gap + value.x) * s,
(pad_y * 2.f + value.y) * s);
}
void on_render() override {
const float s = scale_->float_value;
const float fs = fonts::k_body_size * s;
char buf[16];
snprintf(buf, sizeof(buf), "%.0f", ImGui::GetIO().Framerate);
ImDrawList* dl = ImGui::GetBackgroundDrawList();
const ImVec2 size = hud_size();
const ImVec2 q(hud_pos.x + size.x, hud_pos.y + size.y);
if (background_->bool_value) { // a launcher card: Surface fill, Line border
dl->AddRectFilled(hud_pos, q, theme::u32(theme::with_alpha(theme::surface(), 0.85f)), 10.f * s);
dl->AddRect(hud_pos, q, theme::u32(theme::line()), 10.f * s, 0, 1.f);
char value[24]; snprintf(value, sizeof(value), "%.0f", ImGui::GetIO().Framerate);
text_ = value; draw_text();
}
const ImVec2 label = fonts::text_size(fonts::body, fonts::k_body_size, "fps");
const float y = hud_pos.y + (size.y - label.y * s) * 0.5f;
float x = hud_pos.x + pad_x * s;
if (!background_->bool_value) { // no card: a soft shadow keeps it readable
const ImU32 shadow = theme::u32(theme::with_alpha(theme::bg(), 0.7f));
dl->AddText(fonts::body, fs, ImVec2(x + s, y + s), shadow, "fps");
dl->AddText(fonts::semibold, fs, ImVec2(x + (label.x + gap) * s + s, y + s), shadow, buf);
}
dl->AddText(fonts::body, fs, ImVec2(x, y), theme::u32(theme::muted()), "fps");
x += (label.x + gap) * s;
dl->AddText(fonts::semibold, fs, ImVec2(x, y), setting_color(*color_), buf);
}
private:
static constexpr float pad_x = 12.f;
static constexpr float pad_y = 7.f;
static constexpr float gap = 6.f;
setting* background_ = nullptr;
setting* scale_ = nullptr;
setting* color_ = nullptr;
};
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include "module.h"
#include "../game/hook.h"
#include "../game/world.h"
#include "../gui/notifications.h"
namespace glint_effect {
inline std::atomic<bool> enabled{false};
inline std::atomic<ImU32> tint{IM_COL32(180,100,255,255)};
// FNV-1a of the native shader uniform name, independently verified from
// the 26.52 uniform-name initializer. Other uniforms must pass untouched.
inline constexpr uint64_t color_name=0x71ac3c48991afd1eULL;
struct values {uint64_t count;const float* data;};
inline bool is_color(uintptr_t context,uintptr_t index,uintptr_t input) {
uint16_t slot,count;uintptr_t entries,definition;uint64_t name;
values source{};
return world::read(index,slot) && world::read(context+0x3a,count) && slot<count && count<4096 &&
world::read(context+0x30,entries) && entries &&
world::read(entries+slot*16,definition) && definition &&
world::read(definition+0x28,name) && name==color_name &&
world::read(input,source) && source.count==1 && source.data;
}
using setter_fn=void(__fastcall*)(uintptr_t,uintptr_t,const values*);
inline setter_fn original=nullptr;
inline void __fastcall detour(uintptr_t context,uintptr_t index,const values* input) {
if(enabled && is_color(context,index,reinterpret_cast<uintptr_t>(input))) {
const ImU32 packed=tint.load();
const float rgba[]={float(packed&255)/255,float((packed>>8)&255)/255,float((packed>>16)&255)/255,float((packed>>24)&255)/255};
const values replacement{1,rgba};original(context,index,&replacement);
} else original(context,index,input);
}
}
class glint_changer : public module {
public:
glint_changer():module("glint changer","changes the enchantment glint color",category::visual) {
color_=&add_color("color",.7f,.4f,1);
available_=hook_.install("glint uniform", "41 57 41 56 56 57 55 53 48 83 EC 28 48 89 CE 44 0F B7 32 4C 8B 79 30 41 C1 E6 04 43 0F B7 4C 37 08 48 39 4E 20 0F 86 ? ? ? ? 4C 89 C7 4D 8B 00 4D 85 C0 0F 84 ? ? ? ? 48 89 D3 48 03 4E 28 48 8B 57 08 49 C1 E0 04",
reinterpret_cast<void*>(&glint_effect::detour),reinterpret_cast<void**>(&glint_effect::original),true);
}
void on_enable() override {
if(!available_ || !hook_.set_enabled(true)) {
set_enabled(false);
notifications::push("Glint unavailable","The shader uniform hook could not be verified.",notifications::kind::warning);
return;
}
on_render();glint_effect::enabled=true;
}
void on_disable() override {glint_effect::enabled=false;hook_.set_enabled(false);}
void on_render() override {glint_effect::tint=setting_color(*color_);}
private:setting* color_;game::game_hook hook_;bool available_=false;
};
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include "module.h"
#include "../game/inventory_tools.h"
#include "../gui/hud_card.h"
class inventory_tools_module : public module {
public:
inventory_tools_module():module("inventory tools","steal, dump and middle-click sorting in container screens",category::utility) {
buttons_=&add_toggle("UI buttons",true);middle_=&add_toggle("middle-click sort",true);
hotbar_=&add_toggle("include hotbar when dumping",false);
delay_=&add_int("action delay (ms)",75,30,500);
x_=&add_float("buttons X (screen fraction)",.5f,0,1);y_=&add_float("buttons Y (screen fraction)",.1f,0,1);
add_action("stop",[]{inventory_tools::queue(inventory_tools::action::stop);});
instance_=this;inventory_tools::initialize();
}
void on_enable() override {
if(!inventory_tools::ready){set_enabled(false);notifications::push("Inventory tools unavailable","The container hooks could not be verified.",notifications::kind::warning);return;}
inventory_tools::enabled=true;input::inventory_handler=&handle_input;
}
void on_disable() override {inventory_tools::enabled=false;input::inventory_handler=nullptr;left_owned_=false;middle_owned_=false;inventory_tools::reset();}
void on_render() override {
inventory_tools::delay=delay_->int_value;inventory_tools::include_hotbar=hotbar_->bool_value;
button_enabled_=buttons_->bool_value;middle_enabled_=middle_->bool_value;
const auto state=inventory_tools::latest();if(!inventory_tools::fresh(state) || !inventory_tools::playing_ui())return;
if(!buttons_->bool_value)return;
const auto size=ImGui::GetIO().DisplaySize;
const ImVec2 pos{std::clamp(size.x*x_->float_value-156.f,0.f,(std::max)(0.f,size.x-312.f)),std::clamp(size.y*y_->float_value,0.f,(std::max)(0.f,size.y-32.f))};
{std::lock_guard lock(button_mutex_);button_pos_=pos;button_stamp_=GetTickCount64();}
auto* draw=ImGui::GetForegroundDrawList();
const bool chest=inventory_tools::find(state,"container_items")!=nullptr;
const char* labels[]={"steal","dump",state.busy ? "stop" : "sort"};
for(int i=0;i<3;++i) {
const ImVec2 at{pos.x+i*104.f,pos.y};
hud_card::background(draw,at,{100,30},1,true);
const auto color=theme::u32(i<2 && !chest || state.cursor ? theme::muted() : theme::fg());
const auto text=fonts::text_size(fonts::semibold,fonts::k_body_size,labels[i]);
hud_card::text(draw,fonts::semibold,1,{at.x+(100-text.x)/2,at.y+7},color,labels[i],true);
}
}
private:
setting *buttons_,*middle_,*hotbar_,*delay_,*x_,*y_;
static inline inventory_tools_module* instance_=nullptr;
inline static std::mutex button_mutex_;inline static ImVec2 button_pos_;inline static uint64_t button_stamp_=0;
inline static std::atomic<bool> left_owned_{false},middle_owned_{false};
inline static std::atomic<bool> button_enabled_{true},middle_enabled_{true};
static bool handle_input(HWND,UINT message,WPARAM,LPARAM param) {
if(message==WM_LBUTTONUP && left_owned_){left_owned_=false;return true;}
if(message==WM_MBUTTONUP && middle_owned_){middle_owned_=false;return true;}
if(!instance_ || !inventory_tools::playing_ui())return false;
const auto state=inventory_tools::latest();if(!inventory_tools::fresh(state))return false;
if((message==WM_MBUTTONDOWN || message==WM_MBUTTONDBLCLK) && middle_enabled_ && inventory_tools::find(state,state.hover) && state.hover!="hotbar_items") {
inventory_tools::queue(inventory_tools::action::sort);middle_owned_=true;return true;
}
if(message!=WM_LBUTTONDOWN && message!=WM_LBUTTONDBLCLK)return false;
if(!button_enabled_){if(state.busy)inventory_tools::queue(inventory_tools::action::stop);return false;}
ImVec2 pos;uint64_t stamp;{std::lock_guard lock(button_mutex_);pos=button_pos_;stamp=button_stamp_;}
const int x=short(LOWORD(param)),y=short(HIWORD(param));
if(GetTickCount64()-stamp>150 || x<pos.x || x>=pos.x+312 || y<pos.y || y>=pos.y+30) {
if(state.busy)inventory_tools::queue(inventory_tools::action::stop);return false;
}
const int button=int((x-pos.x)/104);left_owned_=true;
if(!state.cursor) {
if(button==2)inventory_tools::queue(state.busy ? inventory_tools::action::stop : inventory_tools::action::sort,
inventory_tools::find(state,"container_items") ? "container_items" : "inventory_items");
else if(inventory_tools::find(state,"container_items"))inventory_tools::queue(button==0 ? inventory_tools::action::steal : inventory_tools::action::dump);
}
return true;
}
};
+16 -14
View File
@@ -1,13 +1,13 @@
#pragma once
#include <cmath>
#include "module.h"
#include "text_hud.h"
#include "../gui/fonts.h"
#include "../gui/theme.h"
class keystrokes : public module {
class keystrokes : public text_hud {
public:
keystrokes()
: module("keystrokes", "shows your key presses", category::hud, VK_F7) {
: text_hud("keystrokes", "shows your key presses", category::hud, VK_F7) {
hud_pos = ImVec2(10.f, 60.f);
size_ = &add_float("key size", 40.f, 28.f, 64.f);
space_ = &add_toggle("space bar", true);
@@ -22,20 +22,22 @@ public:
float w = 3.f * s + 2.f * gap;
float h = 2.f * s + gap;
if (space_->bool_value) h += gap + s * 0.55f;
return ImVec2(w, h);
return ImVec2((w + 24.f) * scale_->float_value, (h + 14.f) * scale_->float_value);
}
void on_render() override {
const float s = size_->float_value;
const float x = hud_pos.x, y = hud_pos.y;
const float scale = scale_->float_value;
const float s = size_->float_value * scale, spacing = gap * scale;
const float x = hud_pos.x + 12.f * scale, y = hud_pos.y + 7.f * scale;
hud_card::background(ImGui::GetBackgroundDrawList(), hud_pos, hud_size(), scale, background_->bool_value);
const float dt = ImGui::GetIO().DeltaTime;
draw_key(0, "W", 'W', x + s + gap, y, s, s, dt);
draw_key(1, "A", 'A', x, y + s + gap, s, s, dt);
draw_key(2, "S", 'S', x + s + gap, y + s + gap, s, s, dt);
draw_key(3, "D", 'D', x + 2.f * (s + gap), y + s + gap, s, s, dt);
draw_key(0, "W", 'W', x + s + spacing, y, s, s, dt);
draw_key(1, "A", 'A', x, y + s + spacing, s, s, dt);
draw_key(2, "S", 'S', x + s + spacing, y + s + spacing, s, s, dt);
draw_key(3, "D", 'D', x + 2.f * (s + spacing), y + s + spacing, s, s, dt);
if (space_->bool_value)
draw_key(4, "_____", VK_SPACE, x, y + 2.f * (s + gap), 3.f * s + 2.f * gap, s * 0.55f, dt);
draw_key(4, "space", VK_SPACE, x, y + 2.f * (s + spacing), 3.f * s + 2.f * spacing, s * 0.55f, dt);
}
private:
@@ -55,14 +57,14 @@ private:
const ImVec4 pressed(pressed_->color[0], pressed_->color[1], pressed_->color[2], pressed_->color[3]);
const ImVec4 fill = theme::mix(theme::with_alpha(theme::raised(), 0.85f), pressed, t);
const ImVec4 border = theme::mix(theme::line(), theme::accent(), t);
const ImVec4 text = theme::mix(theme::fg(), theme::bg(), t);
const float r = h * 0.3f;
const ImVec4 text = theme::mix(ImVec4(color_->color[0], color_->color[1], color_->color[2], color_->color[3]), theme::bg(), t);
const float r = 6.f * scale_->float_value;
const ImVec2 a(x, y), b(x + w, y + h);
dl->AddRectFilled(a, b, theme::u32(fill), r);
dl->AddRect(a, b, theme::u32(border), r, 0, 1.f);
const float scale = size_->float_value / 40.f;
const float scale = size_->float_value / 40.f * scale_->float_value;
const ImVec2 ts = fonts::text_size(fonts::semibold, fonts::k_body_size, label);
dl->AddText(fonts::semibold, fonts::k_body_size * scale,
ImVec2(floorf(x + (w - ts.x * scale) * 0.5f), floorf(y + (h - ts.y * scale) * 0.5f)),
+216 -271
View File
@@ -1,295 +1,240 @@
#pragma once
#include <windows.h>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <vector>
#include "module.h"
#include "villager_trade.h"
#include "trade_io.h"
#include "trade_profile.h"
#include "../config/save_bridge.h"
#include "../input.h"
#include "../gui/fonts.h"
#include "../gui/theme.h"
#include "../gui/notifications.h"
class macro : public module {
public:
macro()
: module("Macro", "Records clicks and key presses in menus (like villager trading) and replays them.",
category::utility) {
loops_ = &add_int("Loops (0 = until stopped)", 10, 0, 500);
speed_ = &add_float("Speed", 1.f, 0.25f, 3.f);
loop_delay_ = &add_int("Delay Between Loops (ms)", 300, 0, 5000);
show_status_ = &add_toggle("Show Status", true);
macro() : module("Macro","villager trading: select row, check stock/materials, then click trade",category::utility) {
delay_=&add_int("delay (ms)",10,1,1000);
hold_=&add_int("click hold (ms)",30,1,500);
max_=&add_int("maximum trades",500,1,10000);
capture_delay_=&add_float("capture countdown (seconds)",2.f,0.5f,10.f);
keys_[0]=&add_key("start / stop key",VK_F6);
keys_[1]=&add_key("save trade row key",VK_F7);
keys_[2]=&add_key("save trade button key",VK_F8);
keys_[3]=&add_key("calibrate red X key",VK_F9);
keys_[4]=&add_key("save material slot key",VK_F10);
keys_[5]=&add_key("emergency stop key",VK_END);
add_action("start / stop trading",[this] { set_enabled(true);if(engine_.running() || pending_!=pending::none) stop("Stopped by you");else queue(pending::start); });
add_action("capture trade row",[this] {set_enabled(true);queue(pending::row);});
add_action("capture trade button",[this] {set_enabled(true);queue(pending::button);});
add_action("calibrate red X",[this] {set_enabled(true);queue(pending::stock);});
add_action("capture material slot",[this] {set_enabled(true);queue(pending::slot);});
row_x_=&add_int("trade row x",-1,-1,16384);row_y_=&add_int("trade row y",-1,-1,16384);
button_x_=&add_int("trade button x",-1,-1,16384);button_y_=&add_int("trade button y",-1,-1,16384);
stock_check_=&add_toggle("out-of-stock check",true);
stock_x_=&add_int("red X center x",-1,-1,16384);stock_y_=&add_int("red X center y",-1,-1,16384);
stock_color_=&add_color("red X color",0.73f,0.22f,0.06f);
radius_=&add_int("red X search radius",14,0,50);
variation_=&add_int("red X color tolerance",30,0,255);
calibration_radius_=&add_int("red calibration radius",8,1,30);
red_score_=&add_int("minimum red dominance",60,0,255);
material_check_=&add_toggle("material check",true);
slot_x_=&add_int("material slot x",850,0,16384);slot_y_=&add_int("material slot y",459,0,16384);
slot_color_=&add_color("empty material color",0x99/255.f,0x34/255.f,0x34/255.f);
slot_tolerance_=&add_int("material color tolerance",10,0,255);
visible_cursor_=&add_toggle("require visible menu cursor",true);
notifications_=&add_toggle("notifications",true);
progress_=&add_toggle("live progress notification",true);
notification_duration_=&add_float("notification duration (seconds)",3.f,1.f,10.f);
add_action("save settings",[this] { if(save()) notify("Settings saved","Saved to this profile.",notifications::kind::success); });
add_action("import papertrade.ini",[this] {stop("Importing calibration");if(import_legacy()) {save();notify("Calibration imported","Your Desktop papertrade.ini positions are loaded.",notifications::kind::success);}else notify("Import unavailable","No valid papertrade.ini was found on your Desktop.",notifications::kind::warning);});
file_=trade_profile::path();
if(GetFileAttributesW(file_.c_str())!=INVALID_FILE_ATTRIBUTES) trade_profile::load(*this,file_);
else import_legacy();
}
void on_disable() override { stop("disabled"); }
void on_render() override {
if (g_menu_open) {
if (mode_ != mode::idle) stop("menu opened");
return;
}
handle_hotkeys();
if (mode_ == mode::recording) record_frame();
else if (mode_ == mode::playing) play_frame();
draw_status();
}
private:
// the status text below names these keys, so update it if you rebind
static constexpr int k_record_key = VK_F9;
static constexpr int k_play_key = VK_F10;
static constexpr int k_stop_key = VK_END;
enum class mode { idle, recording, playing };
enum class ev { mouse_down, mouse_up, key_down, key_up };
struct event { ev type; int vk; float x, y; double t; };
setting* loops_ = nullptr;
setting* speed_ = nullptr;
setting* loop_delay_ = nullptr;
setting* show_status_ = nullptr;
mode mode_ = mode::idle;
std::vector<event> events_;
bool rec_key_was_down_ = false, play_key_was_down_ = false, stop_key_was_down_ = false;
bool prev_down_[256] = {}; // recording: edge detection
bool held_[256] = {}; // playback: what we're holding down, so stop can release it
double rec_start_ = 0.0, play_t0_ = 0.0;
size_t next_ = 0;
int loops_done_ = 0;
bool cursor_placed_ = false;
const char* status_ = "";
double status_until_ = 0.0;
static double now() {
static const double freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return (double)f.QuadPart; }();
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return (double)c.QuadPart / freq;
}
// ---------------- control ----------------
void handle_hotkeys() {
const bool rec = is_key_down(k_record_key);
const bool play = is_key_down(k_play_key);
const bool stp = is_key_down(k_stop_key);
if (rec && !rec_key_was_down_) {
if (mode_ == mode::recording) stop("recording saved");
else if (mode_ == mode::idle) start_recording();
}
if (play && !play_key_was_down_) {
if (mode_ == mode::playing) stop("stopped");
else if (mode_ == mode::idle) start_playing();
}
if (stp && !stop_key_was_down_) stop("stopped");
rec_key_was_down_ = rec;
play_key_was_down_ = play;
stop_key_was_down_ = stp;
}
void say(const char* msg) { status_ = msg; status_until_ = now() + 2.5; }
void stop(const char* reason) {
if (mode_ == mode::playing) release_all();
if (mode_ != mode::idle) say(reason);
mode_ = mode::idle;
}
void start_recording() {
events_.clear();
for (int vk = 1; vk < 256; ++vk) prev_down_[vk] = is_key_down(vk); // held keys don't count as presses
rec_start_ = now();
mode_ = mode::recording;
}
void start_playing() {
if (events_.empty()) { say("nothing recorded yet"); return; }
std::memset(held_, 0, sizeof(held_));
next_ = 0;
loops_done_ = 0;
cursor_placed_ = false;
play_t0_ = now() + 0.3; // short grace period so you can let go of F10
mode_ = mode::playing;
}
// ---------------- recording ----------------
static bool cursor_fraction(float& fx, float& fy) {
POINT pt;
RECT rc;
if (!g_game_window || !GetCursorPos(&pt) || !ScreenToClient(g_game_window, &pt) ||
!GetClientRect(g_game_window, &rc)) return false;
const float w = (float)(rc.right - rc.left), h = (float)(rc.bottom - rc.top);
if (w <= 0.f || h <= 0.f) return false;
fx = pt.x / w;
fy = pt.y / h;
return true;
}
static bool recordable_key(int vk) {
if (vk == k_record_key || vk == k_play_key || vk == k_stop_key) return false;
if (vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU) return false; // use the left/right variants
if (vk == VK_RSHIFT) return false; // menu key
return true;
}
void record_frame() {
const double t = now() - rec_start_;
for (int vk : { VK_LBUTTON, VK_RBUTTON, VK_MBUTTON }) {
const bool down = is_key_down(vk);
if (down == prev_down_[vk]) continue;
prev_down_[vk] = down;
float fx = 0.f, fy = 0.f;
if (!cursor_fraction(fx, fy)) continue;
events_.push_back({ down ? ev::mouse_down : ev::mouse_up, vk, fx, fy, t });
}
for (int vk = 0x08; vk < 0xFF; ++vk) {
if (!recordable_key(vk)) continue;
const bool down = is_key_down(vk);
if (down == prev_down_[vk]) continue;
prev_down_[vk] = down;
events_.push_back({ down ? ev::key_down : ev::key_up, vk, 0.f, 0.f, t });
}
}
// ---------------- playback ----------------
void play_frame() {
if (!is_game_focused()) { stop("lost focus"); return; }
const double elapsed = (now() - play_t0_) * speed_->float_value;
if (next_ < events_.size() && events_[next_].t <= elapsed) {
const event& e = events_[next_];
const bool mouse = (e.type == ev::mouse_down || e.type == ev::mouse_up);
if (mouse && !cursor_placed_) { // frame 1: move the cursor, so the game sees the hover first
move_cursor(e.x, e.y);
cursor_placed_ = true;
return;
}
send(e); // frame 2: the click or key itself
cursor_placed_ = false;
++next_;
}
if (next_ >= events_.size()) {
++loops_done_;
const int target = loops_->int_value;
if (target != 0 && loops_done_ >= target) { stop("finished"); return; }
next_ = 0;
cursor_placed_ = false;
play_t0_ = now() + loop_delay_->int_value / 1000.0; // t0 in the future = wait before the next loop
}
}
static bool is_extended(int vk) {
switch (vk) {
case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: case VK_PRIOR: case VK_NEXT:
case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN: case VK_RCONTROL: case VK_RMENU:
return true;
default:
bool consumes_key(int key) const override {
if(!key) return false;
for(auto* setting:keys_) if(setting->int_value==key) return true;
return false;
}
void on_enable() override {
for(int i=0;i<6;++i) previous_[i]=is_key_down(keys_[i]->int_value);
notify("macro ready","Use the capture keys to set trade positions.");
}
static void move_cursor(float fx, float fy) {
RECT rc;
if (!g_game_window || !GetClientRect(g_game_window, &rc)) return;
POINT pt = { (LONG)(fx * (rc.right - rc.left)), (LONG)(fy * (rc.bottom - rc.top)) };
ClientToScreen(g_game_window, &pt);
const int vx = GetSystemMetrics(SM_XVIRTUALSCREEN), vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
const int vw = GetSystemMetrics(SM_CXVIRTUALSCREEN), vh = GetSystemMetrics(SM_CYVIRTUALSCREEN);
if (vw <= 1 || vh <= 1) return;
INPUT in{};
in.type = INPUT_MOUSE;
in.mi.dx = (LONG)(((pt.x - vx) * 65535.0) / (vw - 1));
in.mi.dy = (LONG)(((pt.y - vy) * 65535.0) / (vh - 1));
in.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
SendInput(1, &in, sizeof(INPUT));
void on_disable() override {stop("Macro disabled");save(false);}
void on_frame_end() override {if(!engine_.running()) engine_.release_pending(io_);}
void on_render() override {
if(!is_game_focused()) {stop("Minecraft lost focus");return;}
const double time=notifications::now();
if(g_menu_open) {
if(engine_.running()) stop("Client menu opened");
pending_at_=0;
sync_keys();return;
}
static void send_button(int vk, bool down) {
INPUT in{};
in.type = INPUT_MOUSE;
switch (vk) {
case VK_LBUTTON: in.mi.dwFlags = down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; break;
case VK_RBUTTON: in.mi.dwFlags = down ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP; break;
case VK_MBUTTON: in.mi.dwFlags = down ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP; break;
default: return;
if(is_key_down(VK_ESCAPE) || edge(5)) {stop("Stopped by you");sync_keys();return;}
if(edge(0)) {
if(engine_.running() || pending_!=pending::none) stop("Stopped by you");
else start();
}
SendInput(1, &in, sizeof(INPUT));
if(!engine_.running()) {
for(int i=1;i<=4;++i) if(edge(i)) capture(static_cast<pending>(i));
}
static void send_key(int vk, bool down) {
INPUT in{};
in.type = INPUT_KEYBOARD;
in.ki.wVk = (WORD)vk;
in.ki.wScan = (WORD)MapVirtualKeyA((UINT)vk, MAPVK_VK_TO_VSC);
in.ki.dwFlags = (down ? 0 : KEYEVENTF_KEYUP) | (is_extended(vk) ? KEYEVENTF_EXTENDEDKEY : 0);
SendInput(1, &in, sizeof(INPUT));
sync_keys();
if(pending_!=pending::none) {
if(pending_at_==0) pending_at_=time+capture_delay_->float_value;
if(notifications_->bool_value && time<pending_at_) {
char message[112];snprintf(message,sizeof(message),"%.1f seconds remaining. %s",pending_at_-time,
pending_==pending::slot_sample ? "Reading the unhovered material slot." : "Keep the cursor on the target.");
notifications::push("starting",message,notifications::kind::info,0,"trade_event",
1.f-float((pending_at_-time)/capture_delay_->float_value));
}
void send(const event& e) {
const bool down = (e.type == ev::mouse_down || e.type == ev::key_down);
if (e.type == ev::mouse_down || e.type == ev::mouse_up) send_button(e.vk, down);
else send_key(e.vk, down);
held_[e.vk] = down;
}
void release_all() { // never leave a key or button stuck down
for (int vk = 1; vk < 256; ++vk) {
if (!held_[vk]) continue;
if (vk == VK_LBUTTON || vk == VK_RBUTTON || vk == VK_MBUTTON) send_button(vk, false);
else send_key(vk, false);
held_[vk] = false;
if(time>=pending_at_) {
const auto action=pending_;pending_=pending::none;pending_at_=0;
if(action==pending::start) start();
else if(action==pending::slot_sample) {
uint32_t color;
if(io_.pixel({slot_x_->int_value,slot_y_->int_value},color)) {
set_rgb(*slot_color_,color);save();
notify("Material slot calibrated","Position and unhovered empty-slot color saved.",notifications::kind::success);
} else notify("Capture failed","The material slot pixel could not be read.",notifications::kind::warning);
} else capture(action);
}
}
// ---------------- status chip ----------------
void draw_status() {
if (!show_status_->bool_value) return;
char buf[128];
ImVec4 dot = theme::dim();
if (mode_ == mode::recording) {
snprintf(buf, sizeof(buf), "REC %d events | F9 to save", (int)events_.size());
dot = theme::danger();
if(!engine_.running()) {engine_.release_pending(io_);return;}
if(!notifications_->bool_value || !progress_->bool_value) notifications::dismiss("villager_trade");
RECT rect{};
if(!GetClientRect(g_game_window,&rect) || rect.right!=run_width_ || rect.bottom!=run_height_) {stop("Window resized; check calibration");return;}
if(visible_cursor_->bool_value && !menu_cursor()) {stop("Trading menu closed");return;}
// Advance zero-delay check states together; actual moves/presses still
// schedule a positive delay and therefore wait for a later frame.
for(int step=0;step<4 && engine_.running();++step) engine_.tick(time,io_);
if(!engine_.running()) finish();
else if(engine_.count()!=last_count_) {last_count_=engine_.count();show_progress();}
}
else if (mode_ == mode::playing) {
if (loops_->int_value == 0)
snprintf(buf, sizeof(buf), "PLAYING loop %d | End to stop", loops_done_ + 1);
else
snprintf(buf, sizeof(buf), "PLAYING loop %d / %d | End to stop", loops_done_ + 1, loops_->int_value);
dot = theme::accent();
private:
// Values 1..4 deliberately match the four calibration hotkeys.
enum class pending {none,row,button,stock,slot,start,slot_sample};
setting *delay_,*hold_,*max_,*capture_delay_,*keys_[6];
setting *row_x_,*row_y_,*button_x_,*button_y_,*stock_check_,*stock_x_,*stock_y_,*stock_color_;
setting *radius_,*variation_,*calibration_radius_,*red_score_,*material_check_,*slot_x_,*slot_y_,*slot_color_,*slot_tolerance_;
setting *visible_cursor_,*notifications_,*progress_,*notification_duration_;
bool previous_[6]{};
trade_windows_io io_;
villager_trade::engine engine_;
pending pending_=pending::none;
double pending_at_=0;
int run_width_=0,run_height_=0,last_count_=0,run_max_=0;
std::wstring file_;
static uint32_t rgb(const setting& value) {
return (uint32_t(value.color[0]*255.f+0.5f)<<16)|(uint32_t(value.color[1]*255.f+0.5f)<<8)|uint32_t(value.color[2]*255.f+0.5f);
}
else if (now() < status_until_) {
snprintf(buf, sizeof(buf), "%s", status_);
static void set_rgb(setting& value,uint32_t color) {
value.color[0]=((color>>16)&255)/255.f;value.color[1]=((color>>8)&255)/255.f;value.color[2]=(color&255)/255.f;
}
else {
snprintf(buf, sizeof(buf), "Macro | F9 record F10 play End stop (%d events)", (int)events_.size());
bool edge(int i) const {return keys_[i]->int_value && is_key_down(keys_[i]->int_value) && !previous_[i];}
void sync_keys() {for(int i=0;i<6;++i) previous_[i]=is_key_down(keys_[i]->int_value);}
static bool menu_cursor() {CURSORINFO cursor{sizeof(cursor)};return GetCursorInfo(&cursor) && (cursor.flags&CURSOR_SHOWING);}
void notify(const std::string& title,const std::string& body,notifications::kind type=notifications::kind::info) {
if(notifications_->bool_value) notifications::push(title,body,type,notification_duration_->float_value,"trade_event");
}
ImDrawList* dl = ImGui::GetBackgroundDrawList();
const ImVec2 ts = fonts::text_size(fonts::body, fonts::k_body_size, buf);
const float pad_x = 14.f, h = ts.y + 14.f, w = ts.x + pad_x * 2.f + 16.f;
const ImVec2 p(floorf((ImGui::GetIO().DisplaySize.x - w) * 0.5f), 14.f);
const ImVec2 q(p.x + w, p.y + h);
dl->AddRectFilled(p, q, theme::u32(theme::with_alpha(theme::surface(), 0.9f)), 10.f);
dl->AddRect(p, q, theme::u32(theme::line()), 10.f, 0, 1.f);
dl->AddCircleFilled(ImVec2(p.x + pad_x + 4.f, p.y + h * 0.5f), 4.f, theme::u32(dot));
dl->AddText(fonts::body, fonts::k_body_size,
ImVec2(p.x + pad_x + 16.f, p.y + (h - ts.y) * 0.5f), theme::u32(theme::fg()), buf);
bool save(bool report=true) {
const bool success=config_save::request ? config_save::request() : trade_profile::save(*this,file_);
if(!success && report) notify("Could not save settings","The client DLL folder is not writable.",notifications::kind::warning);
return success;
}
void queue(pending action) {
stop("Calibration requested");pending_=action;pending_at_=0;
notify(action==pending::start ? "Trading queued" : "Capture queued",
"Close the client menu, hover the target, and wait for the capture countdown.");
}
void capture(pending action) {
POINT cursor{};RECT rect{};
if(!GetCursorPos(&cursor) || !ScreenToClient(g_game_window,&cursor) || !GetClientRect(g_game_window,&rect) ||
cursor.x<0 || cursor.y<0 || cursor.x>=rect.right || cursor.y>=rect.bottom) {
notify("Capture failed","Place the cursor inside Minecraft and try again.",notifications::kind::warning);return;
}
char location[64];snprintf(location,sizeof(location),"Client position: %ld, %ld",cursor.x,cursor.y);
if(action==pending::row) {row_x_->int_value=cursor.x;row_y_->int_value=cursor.y;notify("Trade row saved",location,notifications::kind::success);}
else if(action==pending::button) {button_x_->int_value=cursor.x;button_y_->int_value=cursor.y;notify("Trade button saved",location,notifications::kind::success);}
else if(action==pending::stock) {
std::vector<uint32_t> pixels;
if(!io_.capture({cursor.x,cursor.y},calibration_radius_->int_value,pixels)) {notify("Calibration failed","The red search box is outside the window or cannot be read.",notifications::kind::warning);return;}
int best_score=-1;uint32_t best=0;
for(auto color:pixels) if(villager_trade::red_score(color)>best_score) {best_score=villager_trade::red_score(color);best=color;}
if(best_score<red_score_->int_value) {notify("No red X found","Hover the center of an out-of-stock red X and try again.",notifications::kind::warning);return;}
stock_x_->int_value=cursor.x;stock_y_->int_value=cursor.y;set_rgb(*stock_color_,best);stock_check_->bool_value=true;
notify("Red X calibrated",location,notifications::kind::success);
} else if(action==pending::slot) {
slot_x_->int_value=cursor.x;slot_y_->int_value=cursor.y;
// Match the script: move off the slot before sampling its unhovered color.
POINT screen;
villager_trade::point away{row_x_->int_value,row_y_->int_value};
if(!io_.client_point(away,screen) || (away.x==cursor.x && away.y==cursor.y)) away={0,0};
if(!io_.move(away)) {notify("Capture failed","Could not move away from the material slot.",notifications::kind::warning);return;}
pending_=pending::slot_sample;pending_at_=notifications::now()+(std::max)(0.05,delay_->int_value*0.002);
return;
}
save();
}
void start() {
if(g_menu_open || !is_game_focused()) return;
if(visible_cursor_->bool_value && !menu_cursor()) {notify("Open a villager trade first","The macro requires a visible menu cursor.",notifications::kind::warning);return;}
villager_trade::config config;
config.row={row_x_->int_value,row_y_->int_value};config.button={button_x_->int_value,button_y_->int_value};
config.stock={stock_x_->int_value,stock_y_->int_value};config.slot={slot_x_->int_value,slot_y_->int_value};
POINT screen;
if(!io_.client_point(config.row,screen) || !io_.client_point(config.button,screen)) {
notify("Set trade positions first","Hover the row and press its save key, then do the same for the trade button.",notifications::kind::warning);return;
}
config.delay_ms=delay_->int_value;config.hold_ms=hold_->int_value;config.max_trades=max_->int_value;
config.stock_radius=radius_->int_value;config.stock_tolerance=variation_->int_value;config.stock_color=rgb(*stock_color_);
config.material_check=material_check_->bool_value;config.slot_color=rgb(*slot_color_);config.slot_tolerance=slot_tolerance_->int_value;
config.stock_check=stock_check_->bool_value && config.stock.x>=0 && config.stock.y>=0;
if(config.material_check && !io_.client_point(config.slot,screen)) {notify("Material slot is outside the window","Capture the material slot or adjust its coordinates.",notifications::kind::warning);return;}
RECT rect{};GetClientRect(g_game_window,&rect);run_width_=rect.right;run_height_=rect.bottom;
if(config.stock_check && (config.stock.x-config.stock_radius<0 || config.stock.y-config.stock_radius<0 ||
config.stock.x+config.stock_radius>=run_width_ || config.stock.y+config.stock_radius>=run_height_)) {
notify("Stock search box is outside the window","Adjust the red X position or reduce its search radius.",notifications::kind::warning);return;
}
if(stock_check_->bool_value && !config.stock_check) notify("Stock check is off","Calibrate the out-of-stock red X to enable it.",notifications::kind::warning);
save();run_max_=config.max_trades;last_count_=0;
if(!engine_.start(config,notifications::now())) {notify("Mouse release pending","Stop and release the mouse before starting another run.",notifications::kind::error);return;}
if(progress_->bool_value) show_progress();else notify("Trading started","Running.");
}
void show_progress() {
if(!notifications_->bool_value || !progress_->bool_value) return;
char text[128];snprintf(text,sizeof(text),"%d / %d trades",engine_.count(),run_max_);
notifications::push("trading",text,notifications::kind::info,0,"villager_trade",float(engine_.count())/run_max_);
}
void stop(const char* message) {
const bool was_running=engine_.running();
const bool was_pending=pending_!=pending::none;
pending_=pending::none;pending_at_=0;
if(was_running) {engine_.stop(io_);end_notification(message,notifications::kind::info);}
else engine_.release_pending(io_);
if(was_pending) notify("start cancelled",message);
}
void end_notification(const char* message,notifications::kind type) {
char body[160];snprintf(body,sizeof(body),"%s. %d trade attempts completed.",message,engine_.count());
if(notifications_->bool_value) notifications::push("macro",body,type,notification_duration_->float_value,"villager_trade");
else notifications::dismiss("villager_trade");
}
void finish() {
const auto reason=engine_.result();
const char* message="Stopped";auto type=notifications::kind::info;
if(reason==villager_trade::reason::completed) {message="Trade limit reached";type=notifications::kind::success;}
else if(reason==villager_trade::reason::out_of_stock) {message="Villager is out of stock";type=notifications::kind::warning;}
else if(reason==villager_trade::reason::out_of_materials) {message="Out of materials";type=notifications::kind::warning;}
else if(reason==villager_trade::reason::read_failed) {message="Could not read the trading screen";type=notifications::kind::error;}
else if(reason==villager_trade::reason::input_failed) {message="Mouse input failed";type=notifications::kind::error;}
end_notification(message,type);
}
bool import_legacy() {
const auto file=trade_profile::legacy_path();if(file.empty() || GetFileAttributesW(file.c_str())==INVALID_FILE_ATTRIBUTES) return false;
row_x_->int_value=GetPrivateProfileIntW(L"pos",L"tradeX",-1,file.c_str());row_y_->int_value=GetPrivateProfileIntW(L"pos",L"tradeY",-1,file.c_str());
button_x_->int_value=GetPrivateProfileIntW(L"pos",L"btnX",-1,file.c_str());button_y_->int_value=GetPrivateProfileIntW(L"pos",L"btnY",-1,file.c_str());
stock_x_->int_value=GetPrivateProfileIntW(L"x",L"cx",-1,file.c_str());stock_y_->int_value=GetPrivateProfileIntW(L"x",L"cy",-1,file.c_str());
slot_x_->int_value=GetPrivateProfileIntW(L"slot",L"sx",850,file.c_str());slot_y_->int_value=GetPrivateProfileIntW(L"slot",L"sy",459,file.c_str());
wchar_t color[32];GetPrivateProfileStringW(L"x",L"color",L"",color,32,file.c_str());if(*color) set_rgb(*stock_color_,wcstoul(color,nullptr,0));
GetPrivateProfileStringW(L"slot",L"color",L"",color,32,file.c_str());if(*color) set_rgb(*slot_color_,wcstoul(color,nullptr,0));
return row_x_->int_value>=0 && row_y_->int_value>=0 && button_x_->int_value>=0 && button_y_->int_value>=0;
}
};
+20 -2
View File
@@ -45,12 +45,14 @@ public:
virtual void on_disable() {}
virtual void on_render() {} // every frame while enabled, inside the ImGui frame
virtual void on_frame_end() {} // runs right after the game's Present returns (frame limiters go here)
virtual bool consumes_key(int) const { return false; }
void set_description(std::string d) { description_ = std::move(d); }
// HUD modules can be dragged around while the menu is open
virtual bool is_hud() const { return false; }
virtual ImVec2 hud_size() const { return ImVec2(0.f, 0.f); }
virtual ImVec2 hud_drag_size() const { return hud_size(); }
void set_enabled(bool enabled) {
if (enabled == enabled_) return;
@@ -67,9 +69,9 @@ public:
void set_toggle_key(int vk) { toggle_key_ = vk; }
// called once per frame; toggles on the key's press edge
void update_key() {
void update_key(bool blocked = false) {
bool down = toggle_key_ && is_key_down(toggle_key_);
if (down && !key_was_down_) toggle();
if (!blocked && down && !key_was_down_) toggle();
key_was_down_ = down;
}
@@ -97,6 +99,22 @@ public:
s.int_value = value; s.int_min = min_v; s.int_max = max_v;
return s;
}
setting& add_key(std::string name, int vk) {
setting& s = settings_.emplace_back();
s.name = std::move(name);
s.type = setting_type::keybind;
s.int_value = vk;
return s;
}
setting& add_action(std::string name, std::function<void()> callback) {
setting& s = settings_.emplace_back();
s.name = std::move(name); s.type = setting_type::action; s.action = std::move(callback);
return s;
}
setting& add_text(std::string name, std::string value, int limit = 64) {
setting& s = settings_.emplace_back(); s.name = std::move(name);
s.type = setting_type::text; s.text_value = std::move(value); s.int_max = limit; return s;
}
setting& add_mode(std::string name, std::vector<std::string> modes, int selected = 0) {
setting& s = settings_.emplace_back();
s.name = std::move(name);
+8 -1
View File
@@ -15,7 +15,14 @@ public:
const std::vector<std::unique_ptr<module>>& all() const { return modules_; }
void update_keys() { for (auto& m : modules_) m->update_key(); }
void update_keys() {
for (auto& m : modules_) {
bool reserved = false;
for (auto& owner : modules_)
if (owner->enabled() && owner->consumes_key(m->toggle_key())) { reserved = true; break; }
m->update_key(reserved);
}
}
void render() {
for (auto& m : modules_)
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include "text_hud.h"
#include "../input.h"
#include "../game/media.h"
#include <d3d11.h>
namespace media_art {
inline ID3D11Device* device=nullptr;
}
class music_player : public text_hud {
public:
music_player():text_hud("music mini player","track details and controls for Windows media sessions") {
hud_pos={10,560};width_=&add_float("width",300,220,600);
progress_=&add_toggle("progress bar",true);controls_=&add_toggle("controls",true);
hide_=&add_toggle("hide when idle",false);
art_=&add_toggle("album art",true);
player_=&add_text("player (blank = automatic)","",256);
add_action("next player",[this] {
const auto state=media::system().latest();
const auto found=std::find(state.players.begin(),state.players.end(),player_->text_value);
player_->text_value=found==state.players.end() ? (state.players.empty() ? "" : state.players.front()) :
std::next(found)==state.players.end() ? "" : *std::next(found);
media::system().prefer(player_->text_value);
});
add_action("previous track",[]{media::system().send(media::command::previous);});
add_action("play / pause",[]{media::system().send(media::command::pause);});
add_action("next track",[]{media::system().send(media::command::next);});
}
void on_enable() override {
try {media::system().prefer(player_->text_value);media::system().start();}
catch(...) {set_enabled(false);}
}
void on_disable() override {media::system().stop();image_.Reset();uploaded_.reset();}
ImVec2 hud_size() const override {return {width_->float_value*scale_->float_value,(controls_->bool_value ? 116.f : 80.f)*scale_->float_value};}
ImVec2 hud_drag_size() const override {return {hud_size().x,76*scale_->float_value};}
void on_render() override {
media::system().prefer(player_->text_value);const auto state=media::system().latest();
if(hide_->bool_value && !state.available && !g_menu_open)return;
draw(state);
}
void draw(media::snapshot const& state) {
const float s=scale_->float_value,w=width_->float_value;
const auto p=[&](float x,float y){return ImVec2(hud_pos.x+x*s,hud_pos.y+y*s);};
auto* draw=ImGui::GetBackgroundDrawList();hud_card::background(draw,hud_pos,hud_size(),s,background_->bool_value);
const auto color=setting_color(*color_);const auto muted=theme::u32(theme::muted());
const float left=art_->bool_value ? 76.f : 12.f;
if(art_->bool_value) {
upload(state.available ? state.art : nullptr);
draw->AddRectFilled(p(12,8),p(64,60),theme::u32(theme::line()),6*s);
if(image_)draw->AddImageRounded((ImTextureID)(uintptr_t)image_.Get(),p(12,8),p(64,60),{0,0},{1,1},IM_COL32_WHITE,6*s);
else {draw->AddCircle(p(38,34),15*s,muted,24,2*s);draw->AddCircleFilled(p(38,34),3*s,color);}
} else {image_.Reset();uploaded_.reset();}
draw->PushClipRect(p(left,0),p(w-12,64),true);
hud_card::text(draw,fonts::semibold,s,p(left,8),color,state.available ? state.title.c_str() : "music",background_->bool_value);
const auto detail=state.available ? (state.artist.empty() ? state.app : state.artist) : state.message;
hud_card::text(draw,fonts::body,s*.85f,p(left,29),muted,detail.c_str(),background_->bool_value);
hud_card::text(draw,fonts::body,s*.7f,p(left,47),muted,state.available ? (state.playing ? "playing" : "paused") : "Open a player that supports Windows media controls",background_->bool_value);
draw->PopClipRect();
if(progress_->bool_value && state.available && state.duration>0) {
const double elapsed=state.playing && state.stamp ? double(GetTickCount64()-state.stamp)/1000*state.rate : 0;
const float fraction=float(std::clamp((state.position+elapsed)/state.duration,0.,1.));
draw->AddRectFilled(p(12,68),p(w-12,71),theme::u32(theme::line()),2*s);
if(fraction>0)draw->AddRectFilled(p(12,68),p(12+(w-24)*fraction,71),color,2*s);
}
if(controls_->bool_value) {
// Buttons become interactive only while the client menu releases the cursor.
ImGui::SetNextWindowPos(p(12,81));ImGui::SetNextWindowSize({(w-24)*s,29*s});
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding,{0,0});ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize,0);
auto flags=ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_NoBackground|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoNav;
if(!g_menu_open)flags|=ImGuiWindowFlags_NoInputs;
if(ImGui::Begin("##music_controls",nullptr,flags)) {
const float button=(w-32)/3*s;
ImGui::BeginDisabled(!g_menu_open || !state.available || !state.previous);
if(ImGui::Button("previous",{button,26*s}))media::system().send(media::command::previous);ImGui::EndDisabled();ImGui::SameLine(0,4*s);
ImGui::BeginDisabled(!g_menu_open || !state.available || !state.pause);
if(ImGui::Button(state.playing ? "pause" : "play",{button,26*s}))media::system().send(media::command::pause);ImGui::EndDisabled();ImGui::SameLine(0,4*s);
ImGui::BeginDisabled(!g_menu_open || !state.available || !state.next);
if(ImGui::Button("next",{button,26*s}))media::system().send(media::command::next);ImGui::EndDisabled();
}
ImGui::End();ImGui::PopStyleVar(2);
}
}
private:
setting *width_,*progress_,*controls_,*hide_,*player_,*art_;
std::shared_ptr<const media::artwork> uploaded_;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> image_;
void upload(std::shared_ptr<const media::artwork> const& art) {
if(art==uploaded_)return;image_.Reset();uploaded_=art;
if(!art || !media_art::device || !art->width || !art->height || art->width>256 || art->height>256 || art->rgba.size()!=art->width*art->height*4)return;
D3D11_TEXTURE2D_DESC desc{};desc.Width=art->width;desc.Height=art->height;desc.MipLevels=desc.ArraySize=1;
desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;desc.SampleDesc.Count=1;desc.Usage=D3D11_USAGE_IMMUTABLE;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
D3D11_SUBRESOURCE_DATA data{art->rgba.data(),art->width*4,0};Microsoft::WRL::ComPtr<ID3D11Texture2D> texture;
if(SUCCEEDED(media_art::device->CreateTexture2D(&desc,&data,&texture)))media_art::device->CreateShaderResourceView(texture.Get(),nullptr,&image_);
}
};
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include "world_modules.h"
#include "../game/inventory_tools.h"
namespace xp_math {
inline int next(int level){return level<16 ? 2*level+7 : level<31 ? 5*level-38 : 9*level-158;}
inline int remaining(int level,float progress){return int(std::ceil((1.0-double(progress))*next(level)));}
}
class xp_progress_hud : public text_hud {
public:
xp_progress_hud():text_hud("xp progress","level, progress and XP needed for the next level") {
hud_pos={10,445};width_=&add_float("width",220,150,400);
percent_=&add_toggle("percentage",true);remaining_=&add_toggle("XP remaining",true);
bar_=&add_toggle("progress bar",true);
}
void on_enable() override {if(require_world(*this))world::collect_xp=true;}
void on_disable() override {world::collect_xp=false;}
ImVec2 hud_size() const override {return {width_->float_value*scale_->float_value,(bar_->bool_value ? 54.f : 34.f)*scale_->float_value};}
void on_render() override {
auto frame=world::latest();if(!g_menu_open && (!world::fresh(*frame) || !frame->xp_known))return;
const int level=frame->xp_known ? frame->xp_level : 28;const float progress=frame->xp_known ? frame->xp_progress : .3f;
char value[96];snprintf(value,sizeof(value),"level %d",level);std::string text=value;
if(percent_->bool_value){snprintf(value,sizeof(value)," %.1f%%",progress*100);text+=value;}
if(remaining_->bool_value){snprintf(value,sizeof(value)," %d XP to go",xp_math::remaining(level,progress));text+=value;}
const float scale=scale_->float_value;auto* draw=ImGui::GetBackgroundDrawList();
hud_card::background(draw,hud_pos,hud_size(),scale,background_->bool_value);
draw->PushClipRect(hud_pos,{hud_pos.x+hud_size().x,hud_pos.y+hud_size().y},true);
hud_card::text(draw,fonts::semibold,scale,{hud_pos.x+12*scale,hud_pos.y+9*scale},setting_color(*color_),text.c_str(),background_->bool_value);
if(bar_->bool_value) {
const ImVec2 p{hud_pos.x+12*scale,hud_pos.y+36*scale},q{hud_pos.x+(width_->float_value-12)*scale,p.y+5*scale};
draw->AddRectFilled(p,q,theme::u32(theme::line()),2*scale);
draw->AddRectFilled(p,{p.x+(q.x-p.x)*progress,q.y},setting_color(*color_),2*scale);
}
draw->PopClipRect();
}
private:setting *width_,*percent_,*remaining_,*bar_;
};
class tab_list : public text_hud {
public:
tab_list():text_hud("tab list","hold Tab to show everyone online on this server") {
hud_pos={330,35};key_=&add_key("show key",VK_TAB);mode_=&add_mode("activation",{"hold","toggle"});
rows_=&add_int("rows per column",20,5,40);width_=&add_float("column width",180,120,300);
}
void on_enable() override {if(require_world(*this))world::collect_roster=true;}
void on_disable() override {world::collect_roster=false;shown_=false;was_down_=false;}
bool consumes_key(int key) const override {return enabled() && key==key_->int_value;}
ImVec2 hud_size() const override {return bounds_;}
void on_render() override {
const bool down=is_key_down(key_->int_value);
if(!is_game_focused() || g_menu_open){shown_=false;was_down_=down;}
else {if(mode_->int_value==0)shown_=down;else if(down && !was_down_)shown_=!shown_;was_down_=down;}
auto frame=world::latest();if(!g_menu_open && (!shown_ || !world::fresh(*frame)))return;
// A current container snapshot means a game screen is open, even with a hidden OS cursor.
CURSORINFO cursor{sizeof(cursor)};
if(!g_menu_open && ((GetCursorInfo(&cursor) && cursor.flags&CURSOR_SHOWING) || inventory_tools::fresh(inventory_tools::latest())))return;
auto names=frame->online_players;
if(g_menu_open && names.empty())names={"player list preview"};
const bool known=frame->roster_known || g_menu_open;
const int rows=rows_->int_value,count=int(names.size()),columns=(std::max)(1,(count+rows-1)/rows);
const float scale=scale_->float_value,width=width_->float_value;
bounds_={columns*width*scale,(38.f+20.f*(std::max)(1,(std::min)(rows,count)))*scale};
auto* draw=ImGui::GetBackgroundDrawList();hud_card::background(draw,hud_pos,bounds_,scale,background_->bool_value);
draw->PushClipRect(hud_pos,{hud_pos.x+bounds_.x,hud_pos.y+bounds_.y},true);
std::string title=known ? "online "+std::to_string(frame->roster_known ? count : 0) : "player list unavailable";
hud_card::text(draw,fonts::body,scale,{hud_pos.x+12*scale,hud_pos.y+7*scale},theme::u32(theme::muted()),title.c_str(),background_->bool_value);
for(int i=0;i<count;++i) {
draw->PushClipRect({hud_pos.x+(i/rows*width+12)*scale,hud_pos.y},
{hud_pos.x+((i/rows+1)*width-8)*scale,hud_pos.y+bounds_.y},true);
hud_card::text(draw,fonts::semibold,scale,{hud_pos.x+(i/rows*width+12)*scale,hud_pos.y+(32+i%rows*20)*scale},setting_color(*color_),names[i].c_str(),background_->bool_value);
draw->PopClipRect();
}
draw->PopClipRect();
}
private:setting *key_,*mode_,*rows_,*width_;bool shown_=false,was_down_=false;ImVec2 bounds_{180,58};
};
+5 -1
View File
@@ -1,14 +1,18 @@
#pragma once
#include <string>
#include <vector>
#include <functional>
enum class setting_type { toggle, slider_float, slider_int, mode, color };
enum class setting_type { toggle, slider_float, slider_int, mode, color, keybind, action, text };
struct setting {
std::string name;
setting_type type = setting_type::toggle;
bool bool_value = false;
bool binding = false;
std::function<void()> action;
std::string text_value;
float float_value = 0.f, float_min = 0.f, float_max = 1.f;
int int_value = 0, int_min = 0, int_max = 10; // int_value doubles as the mode index
std::vector<std::string> modes;
+16
View File
@@ -0,0 +1,16 @@
#pragma once
// Own only the injected key, and hand ownership back to genuine physical input.
class sprint_latch {
public:
int held_key() const { return held_; }
template<class PhysicalKey, class SendKey>
void update(bool want, int key, PhysicalKey physical, SendKey send) {
if (held_ && (!want || held_ != key)) {
if (physical(held_) || send(held_, false)) held_ = 0;
}
if (want && !held_ && !physical(key) && send(key, true)) held_ = key;
}
private:
int held_ = 0;
};
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "module.h"
#include "../gui/hud_card.h"
class text_hud : public module {
public:
text_hud(const char* name, const char* description, category cat = category::hud, int key = 0)
: module(name, description, cat, key), label_(name) {
background_ = &add_toggle("background", true);
scale_ = &add_float("scale", 1.f, 0.7f, 2.5f);
const auto fg = theme::fg(); color_ = &add_color("color", fg.x, fg.y, fg.z);
}
bool is_hud() const override { return true; }
ImVec2 hud_size() const override {
return hud_card::size(label_.c_str(), text_.c_str(), scale_->float_value, reserve_.c_str());
}
protected:
std::string label_, text_, reserve_;
void draw_text() {
hud_card::draw(hud_pos, label_.c_str(), text_.c_str(), scale_->float_value, background_->bool_value, setting_color(*color_), reserve_.c_str());
}
protected:
setting* background_;
setting* scale_;
setting* color_;
};
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "text_hud.h"
#include "../input.h"
#include "sprint_latch.h"
class toggle_sprint : public text_hud {
public:
toggle_sprint() : text_hud("toggle sprint", "sprints while moving forward; pauses in menus and while sneaking", category::utility) {
hud_pos = ImVec2(10.f, 275.f);
label_ = "sprint"; reserve_ = "active";
forward_ = &add_key("forward key", 'W');
sprint_ = &add_key("sprint key", VK_LCONTROL);
show_status_ = &add_toggle("show status", true);
text_ = "ready";
}
void on_disable() override { release(); }
void on_frame_end() override { update(); }
void on_render() override {
update();
text_ = latch_.held_key() ? "active" : "ready";
if (show_status_->bool_value) draw_text();
}
bool is_hud() const override { return show_status_->bool_value; }
private:
setting* forward_;
setting* sprint_;
setting* show_status_;
sprint_latch latch_;
static bool send_key(int vk, bool down) {
INPUT event{};
event.type = INPUT_KEYBOARD;
event.ki.wVk = static_cast<WORD>(vk);
event.ki.wScan = static_cast<WORD>(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC));
event.ki.dwFlags = down ? 0 : KEYEVENTF_KEYUP;
if (vk == VK_RCONTROL || vk == VK_RMENU || (vk >= VK_PRIOR && vk <= VK_DOWN))
event.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
event.ki.dwExtraInfo = input::sprint_input_tag;
return SendInput(1, &event, sizeof(event)) == 1;
}
void release() {
latch_.update(false, 0, physical_key, send_key);
}
static bool physical_key(int key) { return input::physical_keys[key].load(std::memory_order_relaxed); }
void update() {
CURSORINFO cursor{sizeof(cursor)};
const int key = sprint_->int_value;
const bool gameplay = is_game_focused() && !g_menu_open &&
GetCursorInfo(&cursor) && !(cursor.flags & CURSOR_SHOWING);
const bool want = gameplay && key > 0 && key < 256 && forward_->int_value > 0 &&
forward_->int_value < 256 && key != forward_->int_value &&
is_key_down(forward_->int_value) && !is_key_down(VK_SHIFT) && !is_key_down('S');
latch_.update(want, key, physical_key, send_key);
}
};
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <windows.h>
#include <vector>
#include "villager_trade.h"
#include "module.h"
#pragma comment(lib,"gdi32.lib")
class trade_windows_io : public villager_trade::io {
public:
bool client_point(villager_trade::point p,POINT& screen) const {
RECT rect{};
if(!g_game_window || !GetClientRect(g_game_window,&rect) || p.x<0 || p.y<0 || p.x>=rect.right || p.y>=rect.bottom) return false;
screen={p.x,p.y};return ClientToScreen(g_game_window,&screen)!=0;
}
bool move(villager_trade::point p) override {
POINT screen;if(!client_point(p,screen)) return false;
return SetCursorPos(screen.x,screen.y)!=0;
}
bool button(bool down) override {
INPUT event{};event.type=INPUT_MOUSE;
event.mi.dwFlags=down ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
return SendInput(1,&event,sizeof(event))==1;
}
bool pixel(villager_trade::point p,uint32_t& rgb) override {
POINT screen;if(!client_point(p,screen)) return false;
HDC dc=GetDC(nullptr);if(!dc) return false;
const COLORREF value=GetPixel(dc,screen.x,screen.y);ReleaseDC(nullptr,dc);
if(value==CLR_INVALID) return false;
rgb=(GetRValue(value)<<16)|(GetGValue(value)<<8)|GetBValue(value);return true;
}
bool capture(villager_trade::point center,int radius,std::vector<uint32_t>& pixels) {
RECT rect{};if(!GetClientRect(g_game_window,&rect)) return false;
if(center.x-radius<0 || center.y-radius<0 || center.x+radius>=rect.right || center.y+radius>=rect.bottom) return false;
POINT origin;if(!client_point({center.x-radius,center.y-radius},origin)) return false;
const int size=radius*2+1;
BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth=size;info.bmiHeader.biHeight=-size;
info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;
HDC desktop=GetDC(nullptr);if(!desktop) return false;
HDC memory=CreateCompatibleDC(desktop);
void* bits=nullptr;HBITMAP bitmap=CreateDIBSection(desktop,&info,DIB_RGB_COLORS,&bits,nullptr,0);
bool success=false;
if(memory && bitmap && bits) {
HGDIOBJ previous=SelectObject(memory,bitmap);
if(BitBlt(memory,0,0,size,size,desktop,origin.x,origin.y,SRCCOPY|CAPTUREBLT)) {
auto* values=static_cast<uint32_t*>(bits);
pixels.assign(values,values+size*size);
for(auto& value:pixels) value&=0xffffff;
success=true;
}
SelectObject(memory,previous);
}
if(bitmap) DeleteObject(bitmap);if(memory) DeleteDC(memory);ReleaseDC(nullptr,desktop);
return success;
}
bool stock(const villager_trade::config& config,bool& found) override {
std::vector<uint32_t> pixels;
if(!capture(config.stock,config.stock_radius,pixels)) return false;
found=false;
for(uint32_t color:pixels) if(villager_trade::color_near(color,config.stock_color,config.stock_tolerance)) {found=true;break;}
return true;
}
};
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <windows.h>
#include <shlobj.h>
#include <string>
#include <algorithm>
#include <cmath>
#include "module.h"
#pragma comment(lib,"shell32.lib")
#pragma comment(lib,"ole32.lib")
#pragma comment(lib,"uuid.lib")
namespace trade_profile {
inline std::wstring path() {
HMODULE dll=nullptr;
if(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&path),&dll)) return {};
wchar_t name[32768]{};
const DWORD length=GetModuleFileNameW(dll,name,32768);if(!length || length>=32768) return {};
std::wstring result(name,length);const auto separator=result.find_last_of(L"\\/");
return separator==std::wstring::npos ? L"" : result.substr(0,separator+1)+L"villager-trade.ini";
}
inline std::wstring legacy_path() {
PWSTR desktop=nullptr;
if(FAILED(SHGetKnownFolderPath(FOLDERID_Desktop,0,nullptr,&desktop))) return {};
std::wstring result=std::wstring(desktop)+L"\\papertrade.ini";CoTaskMemFree(desktop);return result;
}
inline std::wstring wide(const std::string& text) {return std::wstring(text.begin(),text.end());}
inline void load(module& m,const std::wstring& file) {
if(file.empty()) return;
for(auto& setting:m.settings()) {
wchar_t value[128]{};const auto key=wide(setting.name);
if(!GetPrivateProfileStringW(L"macro",key.c_str(),L"",value,128,file.c_str())) continue;
wchar_t* end=nullptr;
if(setting.type==setting_type::slider_float) {
const float v=wcstof(value,&end);if(end!=value && std::isfinite(v)) setting.float_value=std::clamp(v,setting.float_min,setting.float_max);
} else if(setting.type==setting_type::slider_int || setting.type==setting_type::keybind || setting.type==setting_type::mode) {
const long v=wcstol(value,&end,10);if(end!=value) setting.int_value=setting.type==setting_type::slider_int ? std::clamp(int(v),setting.int_min,setting.int_max) : std::clamp(int(v),0,255);
} else if(setting.type==setting_type::toggle) setting.bool_value=wcstol(value,nullptr,10)!=0;
else if(setting.type==setting_type::color) {
unsigned color=wcstoul(value,&end,16);if(end==value) continue;
setting.color[0]=((color>>16)&255)/255.f;setting.color[1]=((color>>8)&255)/255.f;setting.color[2]=(color&255)/255.f;
}
}
}
inline bool save(module& m,const std::wstring& file) {
if(file.empty()) return false;
bool ok=true;
for(auto& setting:m.settings()) {
std::wstring value;
if(setting.type==setting_type::slider_float) value=std::to_wstring(setting.float_value);
else if(setting.type==setting_type::slider_int || setting.type==setting_type::keybind || setting.type==setting_type::mode) value=std::to_wstring(setting.int_value);
else if(setting.type==setting_type::toggle) value=setting.bool_value ? L"1" : L"0";
else if(setting.type==setting_type::color) {
wchar_t buf[16];const unsigned color=(unsigned(setting.color[0]*255)<<16)|(unsigned(setting.color[1]*255)<<8)|unsigned(setting.color[2]*255);
swprintf_s(buf,L"%06X",color);value=buf;
} else continue;
const auto key=wide(setting.name);
if(!WritePrivateProfileStringW(L"macro",key.c_str(),value.c_str(),file.c_str())) ok=false;
}
return ok;
}
}
+150
View File
@@ -0,0 +1,150 @@
#pragma once
#include <array>
#include <atomic>
#include <algorithm>
#include <cmath>
#include <intrin.h>
#include "module.h"
#include "../game/hook.h"
#include "../game/signatures.h"
#include "../game/viewmodel_math.h"
class viewmodel : public module {
public:
viewmodel() : module("viewmodel", "separate first-person main hand and shield/offhand transforms", category::visual) {
const char* names[] = {
"main position x (right)", "main position y (up)", "main position z (back)",
"main rotation x (pitch)", "main rotation y (yaw)", "main rotation z (roll)",
"offhand position x (right)", "offhand position y (up)", "offhand position z (back)",
"offhand rotation x (pitch)", "offhand rotation y (yaw)", "offhand rotation z (roll)"
};
for (int i = 0; i < 12; ++i) {
const float limit = i % 6 < 3 ? 2.f : 180.f;
settings_[i] = &add_float(names[i], 0.f, -limit, limit);
}
separate_ = &add_toggle("separate offhand", true);
instance_ = this;
if (!main_hook_.install("hand_bob", sigs::hand_bob, reinterpret_cast<void*>(&bob_detour),
reinterpret_cast<void**>(&original_bob_), true))
set_description("unavailable: hand transform signature missing or ambiguous");
draw_hook_.install("render_hands", sigs::render_hands, reinterpret_cast<void*>(&draw_detour),
reinterpret_cast<void**>(&original_draw_), true);
auto* call = sigscan::find(sigs::offhand_draw_call, true);
if (draw_hook_.ok() && call && offhand_hook_.install("render_offhand_item", sigs::render_offhand_item,
reinterpret_cast<void*>(&offhand_detour), reinterpret_cast<void**>(&original_offhand_), true) &&
sigscan::resolve_rip(call + 13, 1, 5) == offhand_hook_.target()) {
offhand_return_ = call + 18;
} else {
separate_->bool_value = false;
set_description("main hand available; separate offhand unavailable for this game version");
}
}
void on_enable() override {
publish();
active_.store(true, std::memory_order_relaxed);
if (!main_hook_.ok() || !main_hook_.set_enabled(true)) { set_enabled(false); return; }
if (draw_hook_.ok()) draw_hook_.set_enabled(true);
if (offhand_return_ && !offhand_hook_.set_enabled(true)) {
separate_->bool_value = false;
separate_active_.store(false, std::memory_order_relaxed);
set_description("main hand available; could not enable the separate offhand hook");
}
}
void on_disable() override {
active_.store(false, std::memory_order_relaxed);
main_hook_.set_enabled(false);
draw_hook_.set_enabled(false);
offhand_hook_.set_enabled(false);
}
void on_render() override { publish(); }
void on_frame_end() override { ++frame_; }
private:
using bob_fn = void(__fastcall*)(void*, float*, float);
using draw_fn = void(__fastcall*)(void*, void*, void*, unsigned char);
using item_fn = void(__fastcall*)(void*, void*, void*, void*, bool, unsigned char, bool, bool);
static inline viewmodel* instance_ = nullptr;
static inline draw_fn original_draw_ = nullptr;
static inline bob_fn original_bob_ = nullptr;
static inline item_fn original_offhand_ = nullptr;
struct draw_state { bool active; void* context; float correction[16]; };
static inline thread_local draw_state state_{};
struct bob_state { unsigned long long frame; bool valid; float vanilla[16]; };
static inline thread_local bob_state bob_{};
std::atomic<unsigned long long> frame_{1};
setting* settings_[12]{};
setting* separate_ = nullptr;
std::array<std::atomic<float>, 12> values_{};
std::atomic<bool> active_{false}, separate_active_{true};
game::game_hook main_hook_, draw_hook_, offhand_hook_;
void* offhand_return_ = nullptr;
void publish() {
for (int i = 0; i < 12; ++i) {
const float v = settings_[i]->float_value;
const float limit = i % 6 < 3 ? 2.f : 180.f;
values_[i].store(std::isfinite(v) ? std::clamp(v, -limit, limit) : 0.f, std::memory_order_relaxed);
}
separate_active_.store(separate_->bool_value && offhand_return_, std::memory_order_relaxed);
}
static void __fastcall bob_detour(void* renderer, float* matrix, float alpha) {
original_bob_(renderer, matrix, alpha);
bob_.valid = false;
if (!matrix || !instance_->active_.load(std::memory_order_relaxed)) return;
std::memcpy(bob_.vanilla, matrix, sizeof(bob_.vanilla));
bob_.frame = instance_->frame_.load(std::memory_order_relaxed);
bob_.valid = true;
float values[6];
for (int i = 0; i < 6; ++i) values[i] = instance_->values_[i].load(std::memory_order_relaxed);
game::transform_viewmodel(matrix, values, values + 3);
}
static void __fastcall draw_detour(void* renderer, void* context, void* source_matrix, unsigned char flags) {
// First-person is bit 0; other item flags can vary (e.g. 0x21 / 0x23).
if (!instance_->active_.load(std::memory_order_relaxed) || !(flags & 1)) {
original_draw_(renderer, context, source_matrix, flags);
return;
}
const draw_state previous = state_;
state_.active = false;
game::viewmodel_matrix_scope world(context);
float values[12];
for (int i = 0; i < 12; ++i) values[i] = instance_->values_[i].load(std::memory_order_relaxed);
// This renderer copies R8 into its own matrix at +0x388. Pass an adjusted
// copy instead of relying exclusively on the shared matrix it can replace.
float adjusted_source[16];
if (source_matrix) {
std::memcpy(adjusted_source, source_matrix, sizeof(adjusted_source));
game::transform_viewmodel(adjusted_source, values, values + 3);
}
if (world.matrix) {
const bool bob_applied = bob_.valid && bob_.frame == instance_->frame_.load(std::memory_order_relaxed);
if (!bob_applied) game::transform_viewmodel(world.matrix, values, values + 3);
world.dirty();
if (instance_->separate_active_.load(std::memory_order_relaxed)) {
float inverse_main[16], desired_offhand[16];
std::memcpy(desired_offhand, bob_applied ? bob_.vanilla : world.saved, sizeof(desired_offhand));
game::transform_viewmodel(desired_offhand, values + 6, values + 9);
if (game::inverse_matrix(world.matrix, inverse_main)) {
// Replace the shared main-hand pose, keeping item/blocking animations.
game::multiply_matrix(desired_offhand, inverse_main, state_.correction);
state_.context = context;
state_.active = true;
}
}
}
original_draw_(renderer, context, source_matrix ? adjusted_source : nullptr, flags);
state_ = previous;
}
static void __fastcall offhand_detour(void* renderer, void* context, void* player, void* item,
bool flag1, unsigned char item_flags, bool flag2, bool flag3) {
if (!state_.active || state_.context != context || _ReturnAddress() != instance_->offhand_return_ ||
!instance_->active_.load(std::memory_order_relaxed)) {
original_offhand_(renderer, context, player, item, flag1, item_flags, flag2, flag3);
return;
}
game::viewmodel_matrix_scope world(context);
if (world.matrix) {
game::multiply_matrix(state_.correction, world.matrix, world.matrix);
world.dirty();
}
original_offhand_(renderer, context, player, item, flag1, item_flags, flag2, flag3);
}
};
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <cstdint>
#include <algorithm>
#include <cmath>
namespace villager_trade {
struct point { int x = -1, y = -1; };
struct config {
point row, button, stock, slot{850,459};
int delay_ms=10, hold_ms=30, max_trades=500, stock_radius=14;
int stock_tolerance=30, slot_tolerance=10;
uint32_t stock_color=0, slot_color=0x993434;
bool stock_check=false, material_check=true;
};
inline bool color_near(uint32_t a,uint32_t b,int tolerance) {
for(int shift : {0,8,16})
if(std::abs(int((a>>shift)&255)-int((b>>shift)&255))>tolerance) return false;
return true;
}
inline int red_score(uint32_t color) {
return int((color>>16)&255)-(std::max)(int((color>>8)&255),int(color&255));
}
enum class reason { none, completed, stopped, out_of_stock, out_of_materials, read_failed, input_failed };
struct io {
virtual ~io()=default;
virtual bool move(point)=0;
virtual bool button(bool down)=0;
virtual bool pixel(point,uint32_t&)=0;
virtual bool stock(const config&,bool& found)=0;
};
class engine {
public:
bool start(config settings,double now) {
if(held_) return false;
config_=settings; count_=0; result_=reason::none; held_=false;
phase_=phase::pre_move; due_=now;
return true;
}
bool running() const { return phase_!=phase::idle; }
int count() const { return count_; }
reason result() const { return result_; }
void release_pending(io& input) {if(held_ && input.button(false)) held_=false;}
void stop(io& input,reason why=reason::stopped) {
release_pending(input);
phase_=phase::idle; result_=why;
}
void tick(double now,io& input) {
if(!running() || now<due_) return;
const double delay=config_.delay_ms/1000.0,hold=config_.hold_ms/1000.0;
auto move=[&](point p,phase next) {
if(!input.move(p)) { stop(input,reason::input_failed);return; }
phase_=next;due_=now+delay;
};
auto press=[&](phase next) {
if(!input.button(true)) { stop(input,reason::input_failed);return; }
held_=true;phase_=next;due_=now+hold;
};
auto release=[&](phase next,double wait) {
if(!input.button(false)) { stop(input,reason::input_failed);return; }
held_=false;phase_=next;due_=now+wait;
};
auto materials=[&]() {
if(!config_.material_check) return true;
uint32_t color;
if(!input.pixel(config_.slot,color)) { stop(input,reason::read_failed);return false; }
if(color_near(color,config_.slot_color,config_.slot_tolerance)) {
stop(input,reason::out_of_materials);return false;
}
return true;
};
switch(phase_) {
case phase::pre_move: move(config_.row,phase::pre_down);break;
case phase::pre_down: press(phase::pre_up);break;
case phase::pre_up: release(phase::pre_check,delay*2);break;
case phase::pre_check: if(materials()) phase_=phase::stock_move;break;
case phase::stock_move: move(config_.button,phase::stock_check);break;
case phase::stock_check: {
bool found=false;
if(config_.stock_check && !input.stock(config_,found)) { stop(input,reason::read_failed);break; }
if(found) { stop(input,reason::out_of_stock);break; }
phase_=phase::row_move;break;
}
case phase::row_move: move(config_.row,phase::row_down);break;
case phase::row_down: press(phase::row_up);break;
case phase::row_up: release(phase::material_check,delay);break;
case phase::material_check: if(materials()) phase_=phase::button_move;break;
case phase::button_move: move(config_.button,phase::button_down);break;
case phase::button_down: press(phase::button_up);break;
case phase::button_up: release(phase::finish,delay);break;
case phase::finish:
++count_;
if(count_>=config_.max_trades) stop(input,reason::completed);
else phase_=phase::stock_move;
break;
default: break;
}
}
private:
enum class phase { idle,pre_move,pre_down,pre_up,pre_check,stock_move,stock_check,row_move,row_down,
row_up,material_check,button_move,button_down,button_up,finish };
phase phase_=phase::idle;
config config_;
int count_=0;
bool held_=false;
double due_=0;
reason result_=reason::none;
};
}
+6 -59
View File
@@ -1,66 +1,13 @@
#pragma once
#include <cstdio>
#include "module.h"
#include "../gui/fonts.h"
#include "../gui/theme.h"
class watermark : public module {
#include "text_hud.h"
class watermark : public text_hud {
public:
watermark()
: module("watermark", "self-explanatory", category::hud, VK_F6) {
hud_pos = ImVec2(10.f, 10.f);
background_ = &add_toggle("background", true);
scale_ = &add_float("scale", 1.f, 0.7f, 2.5f);
const ImVec4 fg = theme::fg();
color_ = &add_color("color", fg.x, fg.y, fg.z);
watermark() : text_hud("watermark", "client name and frame rate", category::hud, VK_F6) {
label_ = "amnesia"; text_ = "0 fps"; reserve_ = "000 fps"; hud_pos = ImVec2(10, 320);
}
bool is_hud() const override { return true; }
ImVec2 hud_size() const override {
const float s = scale_->float_value;
const ImVec2 label = fonts::text_size(fonts::body, fonts::k_body_size, "amnesia");
const ImVec2 value = fonts::text_size(fonts::semibold, fonts::k_body_size, "| welcome, ian | 000 fps | 0 ping"); // fixed width, no jitter
return ImVec2((pad_x * 2.f + label.x + gap + value.x) * s,
(pad_y * 2.f + value.y) * s);
}
void on_render() override {
const float s = scale_->float_value;
const float fs = fonts::k_body_size * s;
char buf[64];
snprintf(buf, sizeof(buf), "| welcome, ian | %.0f fps | 0 ping", ImGui::GetIO().Framerate);
ImDrawList* dl = ImGui::GetBackgroundDrawList();
const ImVec2 size = hud_size();
const ImVec2 q(hud_pos.x + size.x, hud_pos.y + size.y);
if (background_->bool_value) { // a launcher card: Surface fill, Line border
dl->AddRectFilled(hud_pos, q, theme::u32(theme::with_alpha(theme::surface(), 0.85f)), 10.f * s);
dl->AddRect(hud_pos, q, theme::u32(theme::line()), 10.f * s, 0, 1.f);
char value[24]; snprintf(value, sizeof(value), "%.0f fps", ImGui::GetIO().Framerate);
text_ = value; draw_text();
}
const ImVec2 label = fonts::text_size(fonts::body, fonts::k_body_size, "amnesia");
const float y = hud_pos.y + (size.y - label.y * s) * 0.5f;
float x = hud_pos.x + pad_x * s;
if (!background_->bool_value) { // no card: a soft shadow keeps it readable
const ImU32 shadow = theme::u32(theme::with_alpha(theme::bg(), 0.7f));
dl->AddText(fonts::body, fs, ImVec2(x + s, y + s), shadow, "amnesia");
dl->AddText(fonts::semibold, fs, ImVec2(x + (label.x + gap) * s + s - 5, y + s), shadow, buf);
}
dl->AddText(fonts::body, fs, ImVec2(x, y), theme::u32(theme::muted()), "amnesia");
x += (label.x + gap) * s;
dl->AddText(fonts::semibold, fs, ImVec2(x, y), setting_color(*color_), buf);
}
private:
static constexpr float pad_x = 12.f;
static constexpr float pad_y = 7.f;
static constexpr float gap = 6.f;
setting* background_ = nullptr;
setting* scale_ = nullptr;
setting* color_ = nullptr;
};
+258
View File
@@ -0,0 +1,258 @@
#pragma once
#include <cstdio>
#include "text_hud.h"
#include "../game/world.h"
#include "../game/world_filter.h"
#include "../gui/notifications.h"
inline bool require_world(module& m,bool available=world::ready) {
if(available) return true;
m.set_enabled(false);
notifications::push("Module unavailable",m.name()+": a required 26.52 game hook could not be verified.",notifications::kind::warning,5,"world_module");
return false;
}
inline bool project_world(const world::frame& frame,world::vec3 p,ImVec2& out) {
return world::project(frame.matrix,frame.camera,p,frame.fov_x,frame.fov_y,ImGui::GetIO().DisplaySize,out);
}
inline void draw_hud_row(ImVec2 pos,float width,const char* label,const std::string& value,float scale,ImU32 color,bool background) {
auto* draw=ImGui::GetBackgroundDrawList();
const auto label_size=fonts::text_size(fonts::body,fonts::k_body_size,label);
const auto text_size=fonts::text_size(fonts::semibold,fonts::k_body_size,value.c_str());
hud_card::text(draw,fonts::body,scale,pos,theme::u32(theme::muted()),label,background);
hud_card::text(draw,fonts::semibold,scale,ImVec2((std::max)(pos.x+(label_size.x+6)*scale,pos.x+width-text_size.x*scale),pos.y),color,value.c_str(),background);
}
class block_outlines : public module {
public:
block_outlines():module("block outlines","colors the block you are looking at",category::visual) {
const auto accent=theme::accent();color_=&add_color("color",accent.x,accent.y,accent.z);
outline_=&add_toggle("black outline",true);width_=&add_float("width",2, .5f,8);
}
void on_enable() override {require_world(*this);}
void on_disable() override {last_hit_=0;world_id_=0;last_frame_.reset();}
void on_render() override {
auto frame=world::latest();CURSORINFO cursor{sizeof(cursor)};
if(g_menu_open || !is_game_focused() || !GetCursorInfo(&cursor) || (cursor.flags&CURSOR_SHOWING)) {last_hit_=0;last_frame_.reset();return;}
const auto now=GetTickCount64();
if(world::fresh(*frame))last_frame_=frame;
else if(last_frame_ && frame->world_id==last_frame_->world_id && frame->world_id && now-last_frame_->stamp<75)frame=last_frame_;
else {last_hit_=0;last_frame_.reset();return;}
if(world_id_!=frame->world_id){last_hit_=0;world_id_=frame->world_id;}
if(frame->has_block){block_=frame->block;last_hit_=now;}
else if(frame->has_target){last_hit_=0;return;}
else if(!last_hit_ || now-last_hit_>75)return;
draw_selection(*frame,block_,setting_color(*color_),width_->float_value,outline_->bool_value);
}
static void draw_selection(world::frame const& frame,world::vec3 block,ImU32 color,float width,bool outline) {
world::vec3 points[8];
for(int i=0;i<8;++i) points[i]={block.x+float(i&1),block.y+float((i>>1)&1),block.z+float((i>>2)&1)};
auto* draw=ImGui::GetBackgroundDrawList();
for(int i=0;i<8;++i) for(int axis=0;axis<3;++axis) {
const int j=i^(1<<axis);if(j<=i) continue;ImVec2 a,b;
if(!world::project_edge(frame.matrix,frame.camera,points[i],points[j],frame.fov_x,frame.fov_y,ImGui::GetIO().DisplaySize,a,b))continue;
if(outline)draw->AddLine(a,b,IM_COL32(0,0,0,color>>24),width+2);
draw->AddLine(a,b,color,width);
}
}
private:setting *color_,*outline_,*width_;world::vec3 block_{};uint64_t last_hit_=0,world_id_=0;std::shared_ptr<const world::frame> last_frame_;
};
class atmosphere : public module {
public:
atmosphere():module("atmosphere","custom fog, world tint and darkness without changing the time",category::visual) {
fog_=&add_toggle("custom fog color",true);fog_color_=&add_color("fog color",.4f,.6f,.9f,.65f);
tint_=&add_color("world color",1,1,1,1);
night_=&add_toggle("night mode",false);darkness_=&add_float("night darkness",.45f,.05f,.9f);
add_action("reset atmosphere",[this]{fog_color_->color[0]=.4f;fog_color_->color[1]=.6f;fog_color_->color[2]=.9f;fog_color_->color[3]=.65f;for(auto& v:tint_->color)v=1;night_->bool_value=false;});
}
void on_enable() override {if(require_world(*this,world::ready && world::fog_ready)) update();}
void on_disable() override {world::fog_enabled=false;world_filter::enabled=false;}
void on_render() override {update();}
private:
setting *fog_,*fog_color_,*tint_,*night_,*darkness_;
void update() {
world::fog_color=setting_color(*fog_color_);world::fog_enabled=fog_->bool_value;
world_filter::tint=setting_color(*tint_);world_filter::brightness=night_->bool_value ? 1-darkness_->float_value : 1;
world_filter::enabled=night_->bool_value || tint_->color[0]!=1 || tint_->color[1]!=1 || tint_->color[2]!=1;
}
};
class armor_hud : public text_hud {
public:
armor_hud():text_hud("armor hud","your equipped helmet, chestplate, leggings and boots") {
hud_pos={10,365};compact_=&add_toggle("compact",false);hide_empty_=&add_toggle("hide empty slots",false);
}
void on_enable() override {require_world(*this);}
ImVec2 hud_size() const override {return {width_*scale_->float_value,(14+rows_*20.f)*scale_->float_value};}
void on_render() override {
auto frame=world::latest();if(!world::fresh(*frame) && !g_menu_open) return;
const char* labels[] = {"head","chest","legs","feet"};
std::vector<std::pair<std::string,std::string>> rows;
for(int i=0;i<4;++i) {
const auto& item=frame->local.armor[i];if(hide_empty_->bool_value && item.name.empty() && !g_menu_open) continue;
std::string name=world::item_label(item.name);
if(compact_->bool_value) for(const auto* suffix:{" helmet"," chestplate"," leggings"," boots"}) {
const auto at=name.find(suffix);if(at!=std::string::npos) name.erase(at);
}
rows.emplace_back(labels[i],std::move(name));
}
rows_=int(rows.size());width_=140;
for(auto& row:rows) width_=(std::max)(width_,hud_card::size(row.first.c_str(),row.second.c_str(),1).x+8);
if(rows.empty()) return;
const float scale=scale_->float_value;auto* draw=ImGui::GetBackgroundDrawList();
hud_card::background(draw,hud_pos,hud_size(),scale,background_->bool_value);
for(size_t i=0;i<rows.size();++i) draw_hud_row({hud_pos.x+12*scale,hud_pos.y+(7+20*float(i))*scale},width_*scale-24*scale,
rows[i].first.c_str(),rows[i].second,scale,setting_color(*color_),background_->bool_value);
}
private:setting *compact_,*hide_empty_;float width_=210;int rows_=4;
};
class name_changer : public module {
public:
name_changer():module("name changer","changes your displayed name on this client",category::utility) {
name_=&add_text("display name","Player",48);
}
void on_enable() override {if(require_world(*this,world::ready && world::name_ready)) update();}
void on_disable() override {world::alias_enabled=false;}
void on_render() override {update();}
private:
setting* name_;
void update() {
const auto value=world::clean_name(name_->text_value);
auto old=world::current_alias();
if(value!=*old) world::set_alias(value);
world::alias_enabled=!value.empty();
}
};
class better_nametags : public module {
public:
better_nametags():module("better nametags","readable player names with health and distance",category::visual) {
background_=&add_toggle("background",true);scale_=&add_float("scale",1,.7f,2.5f);
color_=&add_color("color",1,1,1);health_=&add_toggle("health",true);distance_=&add_toggle("distance",true);
range_=&add_float("maximum distance",48,4,128);
}
void on_enable() override {if(require_world(*this,world::ready && world::name_ready)) {world::collect_players=true;world::hide_native_names=true;}}
void on_disable() override {world::collect_players=false;world::hide_native_names=false;}
void on_render() override {
auto frame=world::latest();if(!world::fresh(*frame) || g_menu_open) return;
for(const auto& player:frame->players) {
const float distance=world::distance(frame->local.position,player.position);if(distance>range_->float_value) continue;
ImVec2 pos;if(!project_world(*frame,player.head,pos)) continue;
std::string info;char value[48];
if(health_->bool_value) {if(player.health_known) snprintf(value,sizeof(value),"%.0f hp",player.health);else snprintf(value,sizeof(value),"hp ?");info=value;}
if(distance_->bool_value) {snprintf(value,sizeof(value),"%.1fm",distance);if(!info.empty())info+=" | ";info+=value;}
const auto size=hud_card::size(player.name.c_str(),info.c_str(),scale_->float_value);
pos={pos.x-size.x*.5f,pos.y-size.y};
if(pos.x+size.x<0 || pos.x>ImGui::GetIO().DisplaySize.x || pos.y+size.y<0 || pos.y>ImGui::GetIO().DisplaySize.y) continue;
hud_card::draw(pos,player.name.c_str(),info.c_str(),scale_->float_value,background_->bool_value,setting_color(*color_));
}
}
private:setting *background_,*scale_,*color_,*health_,*distance_,*range_;
};
class target_hud : public text_hud {
public:
target_hud():text_hud("target hud","shows the player you aim at while holding a weapon") {
hud_pos={320,365};weapon_=&add_toggle("require weapon",true);linger_=&add_float("linger (seconds)",2,0,5);
equipment_=&add_toggle("equipment",false);bar_=&add_toggle("health bar",true);
}
void on_enable() override {require_world(*this);}
void on_disable() override {last_seen_=-100;opacity_=0;target_={};}
ImVec2 hud_size() const override {return {width_*scale_->float_value,(equipment_->bool_value ? 152.f : 64.f)*scale_->float_value};}
void on_render() override {
auto frame=world::latest();const double now=ImGui::GetTime();
if(world_id_!=frame->world_id || !world::fresh(*frame)) {last_seen_=-100;target_={};world_id_=frame->world_id;}
const bool eligible=world::fresh(*frame) && !g_menu_open && frame->has_target && (!weapon_->bool_value || world::weapon(frame->local.held.name));
if(eligible) {target_=frame->target;last_seen_=now;distance_=world::distance(frame->local.position,target_.position);}
const bool preview=g_menu_open && target_.name.empty();
const bool show=preview || now-last_seen_<=linger_->float_value;
opacity_=theme::approach(opacity_,show ? 1.f : 0.f,ImGui::GetIO().DeltaTime*10);
if(opacity_<.01f) return;
const std::string name=preview ? "target preview" : target_.name.empty() ? "player" : target_.name;
width_=(std::max)(240.f,fonts::text_size(fonts::semibold,fonts::k_body_size,name.c_str()).x+76);
const float s=scale_->float_value;auto* draw=ImGui::GetBackgroundDrawList();
const auto rgba=[&](int r,int g,int b,float alpha=1.f){return IM_COL32(r,g,b,int(255*alpha*opacity_));};
const auto point=[&](float x,float y){return ImVec2(hud_pos.x+x*s,hud_pos.y+y*s);};
hud_card::background(draw,hud_pos,hud_size(),s,background_->bool_value,opacity_);
const ImU32 color=ImGui::ColorConvertFloat4ToU32({color_->color[0],color_->color[1],color_->color[2],color_->color[3]*opacity_});
// Neutral head placeholder: no skin pixels are available in the actor snapshot.
draw->AddRectFilled(point(10,10),point(46,46),rgba(12,13,15),6*s);
draw->AddRectFilled(point(19,16),point(37,32),rgba(48,50,54),2*s);
draw->AddRectFilled(point(16,33),point(40,44),rgba(35,37,41),3*s);
draw->AddRectFilled(point(22,23),point(25,26),rgba(16,17,19));
draw->AddRectFilled(point(31,23),point(34,26),rgba(16,17,19));
hud_card::text(draw,fonts::semibold,s,point(56,8),color,name.c_str(),background_->bool_value);
const bool known=!preview && target_.health_known && std::isfinite(target_.health) &&
std::isfinite(target_.max_health) && target_.max_health>0;
const float fraction=known ? std::clamp(target_.health/target_.max_health,0.f,1.f) : 0;
char percentage[24];if(known)snprintf(percentage,sizeof(percentage),"%.0f%%",fraction*100);
else snprintf(percentage,sizeof(percentage),"--%%");
const float percentage_width=fonts::text_size(fonts::semibold,fonts::k_body_size,percentage).x*.7f;
hud_card::text(draw,fonts::semibold,s*.7f,point(width_-12-percentage_width,27),color,percentage,background_->bool_value);
if(bar_->bool_value) {
draw->AddRectFilled(point(56,40),point(width_-12,44),rgba(30,31,34),2*s);
if(known && fraction>0) draw->AddRectFilled(point(56,40),point(56+(width_-68)*fraction,44),color,2*s);
}
char health[96];if(known)snprintf(health,sizeof(health),"%.0f / %.0f hp | %.1fm",target_.health,target_.max_health,distance_);
else if(preview)snprintf(health,sizeof(health),"health unknown | preview");
else snprintf(health,sizeof(health),"health unknown | %.1fm",distance_);
hud_card::text(draw,fonts::body,s*.8f,point(56,49),rgba(195,197,202),health,background_->bool_value);
if(equipment_->bool_value) {
const char* labels[]={"weapon","head","chest","legs","feet"};
for(int i=0;i<5;++i) {
const auto item=world::item_label(i==0 ? target_.held.name : target_.armor[i-1].name);
draw->PushClipRect(point(10,0),point(width_-10,152),true);
draw_hud_row(point(12,68+16.f*i),(width_-24)*s,labels[i],item,s*.8f,color,background_->bool_value);
draw->PopClipRect();
}
}
}
private:
setting *weapon_,*linger_,*equipment_,*bar_;
world::actor target_{};uint64_t world_id_=0;double last_seen_=-100;float opacity_=0,width_=240,distance_=0;
};
class client_time : public module {
public:
client_time():module("time changer","changes the local sun, moon and lighting; keeps world time intact",category::visual) {
mode_=&add_mode("time",{"custom","sunrise","day","sunset","night"},2);ticks_=&add_int("custom ticks",6000,0,23999);
}
void on_enable() override {if(require_world(*this,world::time_ready)) update();}
void on_disable() override {world::time_override=-1;}
void on_render() override {update();}
private:
setting *mode_,*ticks_;
void update(){const int presets[]={0,0,6000,12000,18000};world::time_override=mode_->int_value==0 ? ticks_->int_value : presets[std::clamp(mode_->int_value,0,4)];}
};
class freelook : public text_hud {
public:
freelook():text_hud("freelook","hold Left Alt to orbit around your player in third person",category::utility) {
hud_pos={10,470};label_="freelook";text_="hold Left Alt";
key_=&add_key("look key",VK_LMENU);sensitivity_=&add_float("sensitivity",.15f,.02f,.8f);distance_=&add_float("camera distance",4.f,1.f,8.f);status_=&add_toggle("show status",true);
}
bool consumes_key(int key) const override{return key && key==key_->int_value;}
bool is_hud() const override{return status_->bool_value;}
void on_enable() override {if(require_world(*this,world::ready && world::camera_ready && world::perspective_ready)) {input::freelook_enabled=true;update();}}
void on_disable() override {input::freelook_enabled=false;input::look_dx=0;input::look_dy=0;}
void on_render() override {update();text_=input::freelook_active() ? "active" : "ready";if(status_->bool_value)draw_text();}
private:setting *key_,*sensitivity_,*distance_,*status_;
void update(){input::freelook_key=key_->int_value;input::look_sensitivity=sensitivity_->float_value;world::orbit_distance=distance_->float_value;}
};
class coordinates_hud : public text_hud {
public:
coordinates_hud():text_hud("coordinates","your position and horizontal movement speed") {
label_="xyz";hud_pos={10,515};speed_=&add_toggle("movement speed",true);
}
void on_enable() override{require_world(*this);}
void on_render() override {
auto frame=world::latest();if(!world::fresh(*frame) && !g_menu_open)return;
char value[112];const auto p=frame->local.feet,v=frame->local.velocity;
if(speed_->bool_value)snprintf(value,sizeof(value),"%.1f %.1f %.1f | %.1f blocks/s",p.x,p.y,p.z,std::sqrt(v.x*v.x+v.z*v.z)*20);
else snprintf(value,sizeof(value),"%.1f %.1f %.1f",p.x,p.y,p.z);
text_=value;draw_text();
}
private:setting* speed_;
};
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include "fov_changer.h"
#include "../input.h"
#include "../game/world.h"
#include "../gui/notifications.h"
class zoom : public module {
public:
zoom() : module("zoom", "hold C for a smooth magnified view", category::visual) {
key_=&add_key("zoom key",'C');
mode_=&add_mode("activation",{"hold","toggle"});
strength_=&add_float("magnification",4,1.25f,12);
smooth_=&add_toggle("smooth zoom",true);
speed_=&add_float("transition speed",10,1,30);
easing_=&add_mode("easing",{"smooth","linear"});
}
bool consumes_key(int key) const override {return key && key==key_->int_value;}
void on_enable() override {
on_disable();
if (!zoom_effect::supported) {
set_enabled(false);
notifications::push("Zoom unavailable","The FOV hook could not be verified.",notifications::kind::warning);
}
}
void on_disable() override {amount_=0;latched_=false;was_down_=false;zoom_effect::magnification=1;}
void on_render() override {
CURSORINFO cursor{sizeof(cursor)};
const bool playing=!g_menu_open && is_game_focused() && world::fresh(*world::latest()) &&
GetCursorInfo(&cursor) && !(cursor.flags&CURSOR_SHOWING);
const bool down=playing && is_key_down(key_->int_value);
if(!playing || previous_key_!=key_->int_value || previous_mode_!=mode_->int_value) latched_=false;
if(down && !was_down_ && mode_->int_value==1) latched_=!latched_;
was_down_=down;previous_key_=key_->int_value;previous_mode_=mode_->int_value;
const float goal=playing && (mode_->int_value==0 ? down : latched_) ? 1.f : 0.f;
// Menus and focus loss restore the view immediately, including toggle mode.
if(!playing || !smooth_->bool_value) amount_=goal;
else {
const float dt=std::clamp(ImGui::GetIO().DeltaTime,0.f,.1f);
const float step=std::clamp(speed_->float_value,1.f,30.f)*dt;
if(easing_->int_value==0) amount_+=(goal-amount_)*(1-std::exp(-step));
else amount_+=std::clamp(goal-amount_,-step,step);
if(std::abs(goal-amount_)<.001f) amount_=goal;
}
zoom_effect::magnification=1+(std::clamp(strength_->float_value,1.25f,12.f)-1)*amount_;
}
private:
setting *key_,*mode_,*strength_,*smooth_,*speed_,*easing_;
float amount_=0;bool latched_=false,was_down_=false;int previous_key_='C',previous_mode_=0;
};
+42
View File
@@ -0,0 +1,42 @@
# Client profiles
Open the client menu with Right Shift. The profile bar above the module panels
shows the active profile and whether changes are saving or saved.
- Pick a profile from the dropdown to load it. Pending changes in the previous
profile are saved before switching.
- **Manage profiles** lets you create a copy of your current setup, rename the
active profile, or delete it with confirmation. Default is protected.
- **Save now** saves immediately. Autosaving is always on: changes save after
roughly 0.75 seconds without edits, or every five seconds during continuous
editing. Unloading saves pending changes before disabling modules.
- The last active profile loads automatically the next time you load the DLL.
Profiles include module enabled states, toggle keys, every configurable setting
(including RGBA colors and individual action keys), and HUD positions. Mode names
are stored so reordering options doesn't change the selected behavior. Buttons,
key-capture state, animations, notification history, trade runs, and countdowns
are not saved. Switching/creating profiles cancels trade activity and releases
injected inputs before applying settings; loading an enabled Macro only arms it.
Files live in **profiles** beside the loaded DLL, with one `.profile` file per
profile and `active.txt` remembering the selection. Names allow 1–48 ASCII letters,
numbers, spaces, underscores, and hyphens; reserved Windows names are rejected.
Each save writes and flushes a temporary file, then replaces the previous file.
A failed write preserves the previous save and shows an error notification.
Damaged or unsupported files are preserved. A damaged startup profile pauses
autosaving until you choose another profile or create a recovery profile. **Save
now** explicitly replaces it with your current settings. Damaged files selected
from the dropdown leave the current setup intact. Unknown modules/settings are
ignored; missing settings use initial defaults and numeric values are clamped to
their permitted ranges.
Existing `villager-trade.ini` or Desktop `papertrade.ini` calibration is used for
the initial setup. Once profiles are active, macro captures and its **save
settings** button save into the active profile.
The integration suite verifies all setting types, keybinds, HUD positions,
defaults, named modes, limits, cancellation, debounce and continuous autosave,
remembered profiles, missing-profile fallback, rename/delete, damaged-file
preservation, failed atomic writes, and unload saving enabled states.
+141
View File
@@ -0,0 +1,141 @@
# FOV Changer verification
## World modules and HUD style
See [WORLD_MODULES.md](WORLD_MODULES.md) for the new modules, verified interfaces,
controls, tests, current rendering limits and in-game checks.
## Profiles and autosaving
See [PROFILES.md](PROFILES.md) for profile controls, file storage, migration and
failure handling. The integration executable also tests profile serialization,
switching, cancellation, autosaving, rename/delete and recovery behavior.
## New quality-of-life modules
All new modules start disabled. Right-click their rows to expand settings, and use
the normal **bind** control to assign a module toggle key.
- **VISUAL / viewmodel:** separate **main** and **offhand** position X/Y/Z and
pitch/yaw/roll sliders. Zero is neutral. **Separate offhand** is on by default;
turn it off to make both hands inherit the main settings. Offhand controls cover
shields and other held offhand items, and substitute the offhand pose before the
game's item-specific transforms so animations remain relative to that pose.
Position offsets use each pose's local basis; rotation keeps its translation
pivot. Check shield raised/lowered, offhand items, empty hands, tools, blocks,
view bobbing both on/off, and third person in-game.
- **UTILITY / toggle sprint:** enable once to hold your sprint key while moving
forward. Defaults are W and Left Ctrl; both are rebindable in its settings.
Shift (sneak), S (backwards), visible menus/cursor, focus loss, and disabling
release the module's injected key. Its optional status HUD is draggable. This
uses normal keyboard input and preserves Minecraft's normal sprint restrictions.
- **HUD / cps counter:** separate left/right click totals over the previous second.
Clicks in the client menu are excluded; opening it or leaving the game clears
the rolling count. Mouse messages capture clicks between rendered frames.
- **HUD / clock:** local computer time, optional seconds and 12/24-hour format.
The expanded integration suite also checks actual viewmodel hook/trampoline calls,
independent main/offhand translation and all rotation axes, preservation of an
item-animation transform, linked mode, matrix restoration, and repeated toggles; plus Sprint's
key ownership, repeated updates, rebinding, failed-release retry, physical-input
handoff, injected-event filtering, and focus cleanup. Both x64 DLL builds pass.
The tests use controlled executable fixtures and do not establish visual behavior
inside Minecraft; the in-game checks above remain useful.
Cursor-hook installation now enables only those cursor hooks, so initializing
the menu does not enable unrelated game hooks. Module panels scroll when expanded
settings exceed the available screen height.
The viewmodel renderer, shared item renderer, and offhand call-site signatures
each matched exactly once in the captured 26.52 executable, at RVAs `0x47ca240`,
`0x47b5ba0`, and `0x47ceed3`. The call-site target is checked against the hooked
function. The offhand hook also requires that return address and the active
first-person render context, so other item-renderer calls are forwarded unchanged.
Temporary world matrices are restored after each draw scope. The isolated
executable fixtures use these exact prologues/call-site instructions and controlled
callbacks; shield rendering itself still needs the in-game check above.
### Viewmodel regression coverage
The working `hand_bob` hook is again the primary main-hand transform. The optional
hand-draw hook also passes an adjusted **copy** of its R8 source matrix: the real
26.52 renderer copies that matrix to its own storage at `+0x388`, so changing only
the shared matrix is insufficient. First-person checks accept the flags bit rather
than requiring an exact `0x21` value. Previous-frame bob snapshots expire at frame
end, avoiding duplicate main-hand offsets and stale offhand corrections.
Tests cover the direct hand hook and simulate the renderer copying a distinct input
matrix, including `0x23` flags and preservation of the caller's input. Earlier
fixtures consumed only the shared matrix and missed this rendering behavior.
### Custom crosshair
The existing crosshair module is now **custom crosshair** (F8). It includes length,
width, gap, dynamic gap/length toggles, independent speed and easing controls, base
color, gradient toggle/color, spin toggle/speed/easing, and the optional center dot.
Each dynamic channel has its own **pulse** or **movement / clicks** mode and amount.
Reactive mode responds to WASD/Space and left/right clicks; client-menu input is
excluded. Pulse speed is cycles per second; reactive speed sets transition rate;
spin speed is degrees per second. Easing options are linear, smooth, ease in,
ease out, and ease in/out. Gradient runs from the base color at the inner ends to
the second color at the outer ends. Spin and gradients work together.
Tests exercise animation timing at 60/144 Hz, easing bounds, reactive return to
rest, toggle reset, and actual ImGui draw vertices/indices, gradient colors, and
rotated geometry. Client Debug/Release builds pass. In-game rendering should be
checked after reloading the new DLL.
### Outline and native crosshair replacement
**Black outline** adds a black border behind each arm and the center dot; **outline
width** controls its thickness. The border uses the same animated gap, length, and
angle as the colored arms, and draws before the fill so gradient/spin combinations
remain intact.
Enabling Custom Crosshair suppresses the native CursorRenderer draw; disabling
restores it. The 26.52 CursorRenderer was identified through the `cursor_renderer`
factory/vtable and its `ui_crosshair` material. Its four-pointer render entry at
RVA `0x8db97b0` matches the signature exactly once in the captured executable.
The hook affects this renderer only. A missing/ambiguous signature leaves native
hiding unavailable and the module tooltip reports that limitation.
Integration tests use the verified native prologue and a controlled draw callback,
checking suppression, argument forwarding, restoration, and repeated toggles.
ImGui tests check black outline vertices with rotating arms and a center dot.
Visual behavior inside Minecraft remains an in-game check after reloading.
## FOV signature and original integration test
The FOV signature was checked against executable sections read from the running
Minecraft Windows **1.26.5203.0 (26.52)** process. It matched exactly once, at
RVA `0x46bd250`. Disassembly identified the `video.fov` option (`0x2f`), a float
return in degrees, a default of 70 degrees, and the game's 130-degree upper clamp.
Call sites pass `(renderer, frame_alpha, bool)` using the Windows x64 ABI.
`fov_changer_test.vcxproj` is a standalone x64 integration test. Its executable
fixture uses the verified function prologue with a controlled 70-degree return;
it is **not** an in-game rendering test. It exercises the production signature
scanner, MinHook, and FOV module, including:
- Missing and ambiguous signatures refuse to enable the module.
- Default off, slider updates, finite bounds, and NaN fallback.
- Forwarding calls with the projection flag false.
- Zoom composition with vanilla/overridden FOV and unchanged hand projection.
- Repeated enable/disable cycles restore the original getter.
Build the test project with Visual Studio/MSBuild in `Debug|x64`, then run
`client/build/tests/fov_changer_test.exe`. Assertions remain enabled in this project.
## In-game check
Load the updated client DLL using your existing workflow. Under **VISUAL**, enable
**fov changer** and expand its **fov** slider. The default is 90 degrees; the range
is 30–130. Check 30, 90, and 130 degrees in a world, then disable the module and
confirm the game's normal FOV returns. This sets a fixed world FOV, including
during sprinting. The zoom module magnifies this FOV when active. Neither module
writes Minecraft's saved FOV setting.
The Debug and Release client DLLs build successfully, and the isolated integration
test passes. Visual behavior inside Minecraft still requires the in-game check.
Future game updates may require a new signature; a missing or ambiguous match
leaves the module unavailable.
+74
View File
@@ -0,0 +1,74 @@
# Villager Macro
Macro replaces the old generic recorder with the supplied `trade.ahk` workflow.
The AutoHotkey source and its Desktop INI are read only; the client stores its own
configuration in the active client profile under `profiles` beside the DLL.
An existing `villager-trade.ini` is still read for initial migration.
## Use
1. Enable **Macro** in **UTILITY**, then close the client menu and open a villager.
2. Hover the trade row and press **F7**, then the trade button and press **F8**.
3. With a villager out of stock, hover the red X and press **F9** to sample the
strongest red pixel in a 17×17 area, matching the script's default calibration.
4. To recalibrate the material detector, hover an **empty** material slot and press
**F10**. The client saves the position, moves away, waits for the hover highlight
to disappear, and reads the empty-slot color. Alternatively edit the coordinates
and RGB color directly in the GUI.
5. Press **F6** to start or stop. **End** or **Escape** also stops immediately.
Ctrl+Escape stops this macro; it does not unload the DLL.
All keys are rebindable. While Macro is enabled, its assigned keys take priority
over other module toggles, including the existing F6/F7/F8 HUD/crosshair bindings.
Disable Macro to return those keys to their normal module controls.
The GUI also provides capture/start/stop buttons. Capture buttons wait for you to
close the client menu, then show a countdown before sampling the cursor position.
Start from the GUI waits for the same countdown after you return to the trade UI.
## Settings and persistence
The GUI exposes delay, click hold duration, maximum attempts, all calibration
coordinates and RGB colors, stock search radius/tolerance, red calibration radius
and minimum dominance, material tolerance, detector toggles, visible-cursor guard,
notification enable/duration, and live progress. A run takes a snapshot of timing,
coordinates, and detection settings when it starts.
The first load imports `Desktop/papertrade.ini` if there is no client profile.
**Import papertrade.ini** imports it again. Row/button/red X entries are supported,
as are optional `[slot] sx/sy/color` entries. **Save settings**, captures, starts,
and disabling Macro save the active client profile. GUI edits also autosave.
Switching profiles stops the run and countdown; enabling Macro from a saved
profile arms it without starting trades. The original INI is never written.
The click order follows the script: preliminary row click and material check;
move to the button before stock detection; select the row; check materials with
the cursor off the slot; click the trade button; repeat up to the attempt limit.
The configurable delays are minimum waits; frame rate can lengthen them. Nothing
sleeps in the rendering callback. Counts reflect trade-button attempts, not server
confirmation that each trade succeeded.
## Stops and notifications
Trading stops on stock exhaustion, the empty-material color, manual stop, module
disable/unload, Escape, focus loss, client menu opening, trading menu closure when
the visible-cursor guard is enabled, window resizing, pixel-read failure, or mouse
input failure. A held left mouse button is released on cancellation; failed releases
retain ownership for retry and prevent another run from starting.
Notifications appear at the upper right, with sliding/fading cards, reflow, shadows,
colored status icons, a spinner while running, and progress/lifetime bars. Trading
updates one persistent card rather than creating a toast for every attempt. The
renderer remains active after Macro is disabled so final stop messages can finish.
## Verification
The isolated trading-engine tests exercise the exact precheck/repeat click order,
three-attempt completion, stock/material stops, read failures, mid-click cancellation,
release retry, disabled checks, and RGB tolerance/red dominance. ImGui tests exercise
notification deduplication, progress updates, rendered finite vertices, dismissal,
and expiry. Debug/Release client builds and the existing integration suite pass.
Villager interaction and screen-pixel matching still require an in-game check with
your resolution/UI scale, resource pack, and trading screen. Recalibrate if those
change; the macro does not identify trades semantically or bypass game trade rules.
+334
View File
@@ -0,0 +1,334 @@
# World and player modules (26.52)
All new modules start disabled. Expand a module with right click. Settings,
text names, keybinds, enabled states, and HUD positions autosave in your profile.
| Module | Controls and behavior |
| --- | --- |
| Block outlines | Color, black outline toggle, width. Outlines the selected block cell using the game's actual hit result. |
| Atmosphere | Custom fog toggle/color, world color, night mode and darkness. Color alpha controls blend strength. Night mode darkens the rendered image without changing time. |
| Armor HUD | Equipped head/chest/legs/feet item names, compact display and hiding empty slots. |
| Name changer | Editable display name. The name getter substitutes it for local player display calls; the original entity string is never changed. |
| Better nametags | Player name, optional health/distance, maximum distance, scale, color and background. Native player names are suppressed during relevant display calls. |
| Target HUD | Aim at a player while holding a sword, axe, bow/crossbow, trident, mace or spear. Shows name, client-reported health, distance and equipped items. Optional weapon requirement, equipment and health bar; default linger is two seconds. |
| Time changer | Custom ticks (0–23999), sunrise/day/sunset/night presets. Changes the visual celestial calculation on the rendering thread; never writes the world's tick/time state. |
| Freelook | Enable the module, then hold Left Alt (rebindable). Mouse movement rotates only the render camera. Releasing returns to the normal view. Sensitivity and status HUD controls are provided. Works with the game's chosen first/third-person perspective. |
| Coordinates | Feet position and optional horizontal speed in blocks per second. |
| Zoom | Hold C by default, rebindable, with optional toggle activation. Magnification 1.25–12x, smooth zoom toggle, transition speed and smooth/linear easing. Composes with FOV changer; restores immediately on menus, focus loss, stale world data or disable. |
| Glint changer | RGBA color picker for the native named enchantment glint uniform. Other shader parameters and input color buffers are unchanged; disabling returns future draws to vanilla values. |
| Music mini player | Track/artist, playing/paused status, progress and previous/play/pause/next buttons. Background, scale, color, width, progress, controls and hide-when-idle settings. Blank player follows Windows' current session; next-player action cycles available source IDs and automatic mode. |
| Inventory tools | Steal transfers chest items into your inventory; dump transfers inventory items into the open chest. Middle-click sorts the hovered chest or inventory panel by item name. Three buttons appear over container screens; the sort button becomes stop while working. Hotbar dumping defaults off. Action delay and button X/Y positions are configurable. |
| Anti AFK | After 30 seconds idle by default, briefly jumps and alternates left/right movement. Jump-only and strafe-only modes, idle interval (10–300 seconds), hold time (50–1000ms), action keys and FPS-style status HUD. Settings/enabled state autosave. |
Anti AFK requires a fresh world snapshot, Minecraft focus and a hidden menu
cursor. Real keyboard/raw mouse activity and held physical keys reset the timer.
Client/game menus, focus loss, stale world data, world changes and disabling
release owned inputs. A focus-loss callback releases keys immediately even if
rendering pauses while minimized. Returning starts a fresh idle countdown. Its
tagged synthetic input does not count as user activity or trigger module hotkeys.
Tests cover interval/hold timing, alternating directions, activity interruption,
pause/resume, physical key ownership, rebinding and failed release retries.
Verify in your Realm by enabling the utility module while Minecraft stays
focused, observing movement/countdown, and then checking that menus, manual play,
Alt-Tab and disabling release keys. Realm idle-kick behavior itself has not been
verified in the automated test.
Inventory tools use native container transactions on the container tick thread,
not guessed slot coordinates or raw inventory writes. Same-name stacks are kept
separate; count/NBT remain owned by the game's stack operations. Armor, crafting
and hotbar sorting are excluded. They stop on focus/menu/controller changes,
cursor-held items, manual clicks elsewhere, and transfer acknowledgement timeout.
Unknown cursor state refuses operations. The verified interfaces are container
tick `0x4df8350`, group size `0x33e7550`, group item `0x33e6f80`, take-all
`0x4dfac60`, place-all `0x4dfae00`, and auto-place `0x4df9f60`. Each signature
matches uniquely in the captured 26.52 executable. Hovered group is at `+0x1098`,
distinct from selected group at `+0x1048`; container model is at `+0x12c0`.
Simulation tests cover sorting, transfers, separate stacks, empty slots and
cancellation. Actual server transactions still require an in-game check with
ordinary test items in a chest, then a full chest, closed screen and focus switch.
Outlines hide when the client menu/game cursor is visible or Minecraft loses
focus. Edges crossing the camera near plane are clipped rather than discarded;
a 75ms selection grace handles intermittent missed block-hit updates and resets
on menus, targets or world changes. This reduces selection/near-plane flicker.
The music card now includes an album-art toggle and a placeholder when no cover
is available. It reads the session thumbnail, limits encoded size to 4MB and
decoded dimensions, scales to at most 256px, decodes RGBA with Windows Imaging
Component, and uploads an immutable D3D11 texture on the rendering thread. Cover
data is cached by player/track/artist/album; player/track changes clear stale art.
Tests check decoded pixel colors, invalid images and real D3D11 texture upload.
Music controls are clickable while the client menu is open; drag the upper part
of the card to move it. The player field can also select an exact Windows source
ID, and module settings provide the same playback actions. Metadata is polled on
a cancellable worker, never synchronously on the rendering thread. Turning the
module off/unloading stops and joins that worker. Missing sessions and denied API
access show an explicit idle/error message. Players must expose a Windows media
session; this does not play local files or guarantee integration with every app.
The API is documented by [Microsoft](https://learn.microsoft.com/en-us/uwp/api/windows.media.control.globalsystemmediatransportcontrolssession).
Glint uses the uniquely verified float4 uniform setter at `0x52f2250`, matches
the FNV-1a hash of `GlintColor` (`0x71ac3c48991afd1e`), checks native slot bounds,
and passes a temporary replacement buffer to the original setter. Standard draws
using that uniform are affected; render paths/resource packs which bypass it may
retain their own color. Verify held enchanted items, armor, and inventory glint
in game, including disable/restoration.
The integration suite tests matching versus unrelated glint uniforms, rejected
slot/count cases, unchanged source buffers, music HUD geometry, and live media
API startup/cancellation/shutdown. Outside the sandbox the read-only Windows API
check found an active media session. No test sends playback commands. Minecraft
rendering and playback actions still need an in-game check.
Target HUD now has a compact head/name/health percentage/bar layout. Its head is
a neutral placeholder because snapshots do not contain player skins. Health and
distance remain beneath the bar. Equipment expands into five additional rows;
it defaults off for new profiles, while saved profile preferences are retained.
Unknown health shows `--%` and an empty track. Zero/invalid maximum health never
produces a fabricated percentage. The original two-second linger is retained.
FPS, watermark, CPS, clock, sprint status, freelook status, coordinates, armor and
target HUDs share the FPS card's fill, border, padding, rounded corners, muted
labels, semibold values, background toggle, scale and color settings. Keystrokes
uses the same surrounding card with its key grid inside. Crosshair geometry keeps
its existing visual controls.
The armor HUD uses readable item names rather than item textures and does not show
durability. Block outlines currently show a block cell (including for non-cube
blocks). World color/night mode filter the rendered game image before client HUD
cards, so vanilla HUD pixels also receive that filter. The filter pauses when the
game shows a menu cursor; fog uses the game's actual dimension fog calculation.
Health is what the client has received; unavailable values are shown as unknown.
Target information expires when leaving/changing worlds, and rendering stops
using snapshots older than half a second.
## Verified game interfaces
The new signatures each match exactly once in the captured executable sections
of Minecraft Windows 1.26.5203.0:
| Interface | RVA |
| --- | --- |
| ClientInstance update | `0x5da7c00` |
| LevelRenderer renderLevel call / target | `0x4be899` / `0x47f8570` |
| Render camera matrices | `0x46cff30` |
| Active render camera helper | `0x9ed0a0` (unique tag anchor at `0x9ed1f1`, resolved through native unwind data) |
| Visual celestial time | `0x2312080` |
| Actor name getter | `0x1a14ac0` |
| Dimension brightness-dependent fog color | `0x2308050` |
Read-only live inspection confirmed local entity registry and versions, the
player's position/rotation, camera origin/projection, armor item names, inventory
selected-slot getter, and paired entity/block hit results. The implementation
uses the native component storage's read-only `get_at` method after checking
sparse versions and packed membership. This avoids constructing/mutating a
registry or assuming an external EnTT build matches Bedrock's custom page sizes.
Immutable snapshots carry copied data to the HUD; entity pointers are not kept
by modules. Freelook saves/restores the camera quaternion around matrix generation.
The isolated integration suite tests sparse versions/membership and the native
storage ABI, projection and quaternion math, time/fog/name display isolation,
profile text round trips, and actual HUD geometry. A real D3D11 WARP device checks
the color/darkness shader's output pixels and renderer state restoration. Existing
FOV, viewmodel, sprint, crosshair, trading, notification and profile tests still
pass. These checks do not replace in-game visual verification after loading.
Zoom tests exercise the actual shared FOV hook both with and without the FOV
override, unchanged hand projection, restoration, menu cancellation and invalid
factor handling. Target HUD geometry covers compact/expanded equipment and
unknown/zero-maximum health. In game, check holding/releasing C, toggle mode,
transition controls, changing FOV while zooming, opening menus and switching focus.
SDK layouts were compared with the MIT-licensed
[26.52 ModBase](https://github.com/b01dev/MCBE_DX12_ModBase) and primary
[LeviLamina headers](https://github.com/LiteLDev/LeviLamina); signatures, offsets
and storage behavior above were verified directly against this game's binary and
read-only process data. No external SDK implementation is linked into the client.
## In-game checks
Enable modules individually after reloading. Check outline width/color on a cube;
fog in the distance; tint/night toggles and restoration; every armor slot;
name changes in a third-person display; other players' tags; target HUD with/without
a weapon and its linger; sunrise/night presets; and freelook while standing still
and moving. Releasing Alt, opening either menu, losing focus, disabling the module,
switching profiles and unloading should return normal camera/input behavior.
## Inventory buttons, tab list and XP HUD (26.52)
Read-only inspection of an open double chest confirmed that the model at
controller +0x12c0 owns the inventory/hotbar/container group views. The old
slot-count function used virtual slot 17, which returns zero for sparse UI views.
The fix verifies the slot-4 capacity getter and reads the ItemStack vector at
+0x100/+0x108 (152-byte stride). The live chest contained 54 slots and inventory
27. A fresh container tick establishes screen availability; an OS cursor flag
is not required. Transfers remain blocked while unfocused or in the client menu.
The server player roster comes from the singleton LevelComponent, rather than
nearby ActorOwner components. Level +0x4e0 points to the roster map; map head/size
are +8/+16 and the node player name is +56. Copied names are sorted and validated
before publication. No player, skin, or server data is modified. Unknown or stale
rosters are not replaced with a nearby-player approximation.
XP uses local AttributesComponent IDs 4 (level) and 5 (experience fraction),
136-byte entries, current value +0x70. Live inspection found level 28 and fraction
0.2983785. XP-to-next-level uses the three vanilla level ranges; remaining XP is
rounded up from the bar fraction. These layouts are specific to the verified build.
Tests cover sparse-view getter validation/capacity, malformed roster chains,
empty rosters, XP range boundaries and invalid attribute values, multi-column
roster geometry, menu previews and clearing collection on disable. In game,
enable inventory tools and check chest buttons; enable tab list and hold Tab;
enable XP progress and compare level/percentage to the vanilla bar. Verify tab
contents with a player farther away than entity rendering range. Notification
cards use the clickgui palette and simple fade/slide, with explicit task progress
only. In-game verification of the rebuilt DLL still requires loading it.
## HUD editor grid snapping
The clickgui's top bar has a `hud editor` popup with snap/grid toggles and a
4-64 pixel grid size (default 10). Hold Shift while dragging to bypass snapping.
Only dragged HUD elements snap; opening the editor leaves existing layouts alone.
Mouse displacement is measured from the original grab point, rather than rounding
each frame's delta, so slow dragging does not get stuck between grid cells.
Screen edges take priority over grid alignment, including HUD cards larger than
the screen. Editor preferences use a reserved profile entry and participate in
normal autosaving, profile switching and defaults for older profiles.
Tests cover accumulated movement, free movement, screen edges/oversized cards,
preference serialization, clamping and restoration when absent from old profiles.
## Inventory action correction
The old function at RVA 0x4df9f60 was auto-take into the cursor, not quick move.
It invokes model virtual slot 9 and therefore left the first stack on the cursor,
triggering the module's cursor cancellation. Steal/dump now bind the actual
controller quick-move action at RVA 0x4dfb4d0 (same four-argument ABI), which
resolves destination routes and invokes model virtual slot 15. Its 112-byte
signature was verified unique in the captured 1.26.5203.0 executable.
Sorting now uses the native model slot-to-slot swap at RVA 0x33e9880, with a
verified unique 96-byte signature. Slot descriptors explicitly use the game's
32-byte string plus slot-index layout, independent of debug STL layout. The
native swap queues one complete transaction and never borrows the cursor.
Sorting waits for the source change before scheduling the next swap, respecting
server update delays and preserving complete native stack data. Tests include
delayed acknowledgement and inventory/hotbar quick-move routing. In-game checks
still require reloading the rebuilt DLL and checking steal, dump and sort.
## Menu cursor ownership
ImGui's Win32 cursor updates are disabled with NoMouseCursorChange. Previously,
MouseDrawCursor caused its WM_SETCURSOR handler to call SetCursor(nullptr) on
Minecraft's window thread, leaving an invisible native cursor after close.
The menu now draws a software pointer only when the OS cursor is already hidden;
otherwise the native inventory pointer remains visible. Closing restores clipping
and posts WM_SETCURSOR to let the native window procedure choose its cursor on
its own thread. No ShowCursor counter manipulation or forced gameplay pointer.
Check opening/closing with Right Shift and Escape, both in gameplay and with a
chest/trade screen open, then moving the pointer without leaving Minecraft.
## Sorter compatibility correction
The live open chest used the legacy model path (model +0xa0 was null), and its
slots were correctly populated with unsorted item names/counts. The direct
slot-to-slot model swap was rejected on this path. This supersedes the direct
swap implementation described above. Sorting now uses native controller actions:
take-all 0x4dfac60, cursor swap 0x4dfa820, and place-all 0x4dfae00. Each signature
was checked unique against the captured executable. The controller actions also
perform native selection/UI bookkeeping that direct model calls bypass.
A staged state machine waits for the picked-up stack and empty source slot,
then the destination and displaced cursor stack, then cursor clearance and
place-back confirmation. It honors the configured action delay, accepts only
the expected held stack during its own operation, and does not continue on
controller/focus changes. A declined swap attempts to return the original stack
to its still-empty source. Timeouts provide a concise notification. Tests cover
multi-step sorting, delayed confirmation, rejected-swap recovery, empty slots
and separate same-name stacks. Reload and check sorting in a chest and inventory;
in-game success has not been verified by these isolated tests.
## Whole-stack pickup correction
The recorded failed sort had `sort_taken = arrow x10`, matching the reported
pickup of only five arrows. Binary inspection confirmed controller 0x4dfac60
calls model slot 12 (0x33e9c20), whose legacy request is subtype 1 and computes
half the stack. The previous name `take_all` was incorrect. Sorting now binds
only the controller left-click/swap action at 0x4dfa820 for pickup, replacement,
place-back and recovery; no half-stack action is called. The model slot-10 legacy
request uses subtype 0 (whole stack). This supersedes the pickup binding in the
previous section. Tests now explicitly observe an entire arrow x10 stack on the
cursor during sorting, along with odd-count x7 stacks and final count conservation.
## Recorded sort stop and directional placement
Live verification showed full pickup succeeded (charcoal x8 held, source slot 53
empty). The recorded stop reason was timeout, and the chest remained unchanged
after recovery. Binary analysis distinguished full take (controller 0x4dfa820,
model slot 10, source -> cursor) from full place (controller 0x4dfae00, model slot
11, cursor -> destination). The prior use of the take action on an occupied
cursor was incorrect. Sorting now takes once, places into the destination, then
places the displaced stack back into the source. The test take action rejects an
occupied cursor, rather than incorrectly modeling every call as a symmetric swap.
Additional controller ticks cannot overwrite an active owner's fresh snapshot;
phase timeouts govern transactions instead of display freshness. Recorded stop
reasons distinguish timeout, focus, controller, cursor, native action failure and
explicit stop. These changes supersede the same-action sequence above.
## Third-person orbit freelook
Freelook now temporarily overrides the native view-perspective getter to back
third person (1) while the hold key is active. Getter RVA 0xfb7430 is matched by a
unique signature against the captured 26.52 binary; the caller's native perspective
is returned unchanged outside freelook. CameraComponent orientation +0x30 and
position +0x40 are substituted only around matrix generation, then restored.
The camera position moves around the current local-player eye pivot according to
the look quaternion and adjustable radius (default 4, range 1-8 blocks). Input
continues to suppress camera/player mouse-turn packets during the hold. Release,
menus, loss of focus, disabling, profile switches and unloading remove the override.
No game perspective setting is saved/rewritten. Math tests cover side/front/full
rotation, fixed pivot and radius at steep pitch. Check in game that the local body
is visible, the camera orbits, aim stays fixed, and releasing Alt restores the prior
view. The orbit currently does not shorten its radius for walls/obstacles.
## Freelook player-angle lock
Read-only inspection verified ActorRotationComponent (16 bytes), head/body yaw
components (8 bytes each), and RenderRotationComponent (8 bytes). While holding
freelook, the local entity's current/previous pitch/yaw and head/body/render angles
are held at the entry values before/after client update and before rendering.
This supplements raw-input suppression, which does not cover all Bedrock input
paths. Position/velocity and movement keys are not modified. No component pointers
are retained across updates; registry/entity identity changes start a new lock.
Release/menu/focus loss/disable removes the angle lock, allowing normal turning.
Tests verify angle preservation despite attempted changes, continued translation,
independent orbit rotation, release/re-entry and changed player identity.
## Native freelook input verification
A live held-Alt trace showed `was_looking=1`, camera yaw/pitch staying zero,
`frozen_look.held=0`, and changing player angles. Thus Win32 raw-input deltas were
not delivered and the angle-lock lookup failed. ActorRotation's verified native
16-byte `get_at` starts with `mov rax,rdx` before loading its payload pages, unlike
the 8-byte getter previously accepted. The protected ECS accessor now validates
that specific alternate prefix as well. A test executes the actual leaf layout
against controlled sparse/payload storage to cover the missing ABI variant.
Freelook no longer relies on WM_INPUT for orbit movement. Native pitch/yaw changes
are measured against the held player angle, accumulated as camera-only deltas,
and the player/head/body/render angles are restored. Normal movement messages are
forwarded; WASD/jump remain active. Camera sensitivity scales the native angular
deltas. Tests cover angular wraparound, fixed player angles and the native getter.
The rebuilt native-input version was then monitored live during a held-Alt mouse
movement test (20 samples). `frozen_look.held` stayed true; player current/previous
pitch and yaw remained 16.716339 / -120.978310 throughout, while camera orbit yaw
and pitch changed across the samples. This verifies the angle lock and camera
input routing in the running game, rather than only in isolated math fixtures.
The native look target is now consumed by changes relative to the last observed
native target. Reapplying a cached absolute target no longer produces repeated
orbit deltas; reads of the restored player baseline do not reset that reference.
A regression checks that a repeated target contributes zero camera movement,
then a new target contributes only its incremental pitch/yaw change. This fixes
the observed continuous orbit after stopping the mouse.
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include "../src/modules/anti_afk_engine.h"
inline void test_anti_afk() {
using namespace anti_afk_logic;
anti_afk_logic::config settings;settings.interval=1000;settings.hold=150;
bool physical_keys[256]{};bool success=true;
std::vector<std::pair<int,bool>> events;
const auto physical=[&](int key){return physical_keys[key];};
const auto send=[&](int key,bool down){if(success)events.emplace_back(key,down);return success;};
engine timer;
timer.update(0,true,0,false,settings,physical,send);
timer.update(999,true,0,false,settings,physical,send);assert(events.empty());
timer.update(1000,true,0,false,settings,physical,send);
assert(events.size()==2 && events[0]==std::make_pair(VK_SPACE,true) && events[1]==std::make_pair(int('A'),true));
timer.update(1149,true,0,false,settings,physical,send);assert(events.size()==2);
timer.update(1150,true,0,false,settings,physical,send);assert(events.size()==4 && !timer.active());
timer.update(2000,true,0,false,settings,physical,send);assert(events.size()==6 && events.back()==std::make_pair(int('D'),true));
timer.update(2010,true,1,false,settings,physical,send);assert(events.size()==8 && !timer.active());
timer.update(2900,true,1,false,settings,physical,send);assert(events.size()==8);
timer.update(3010,true,1,false,settings,physical,send);assert(timer.active());
physical_keys[VK_SPACE]=true;const auto before=events.size();
timer.update(3020,true,2,true,settings,physical,send);
assert(!timer.active() && events.size()==before+1 && events.back()==std::make_pair(int('A'),false));
physical_keys[VK_SPACE]=false;
timer.update(8000,false,2,false,settings,physical,send);const auto paused=events.size();
timer.update(9000,false,2,false,settings,physical,send);assert(events.size()==paused);
timer.update(9100,true,2,false,settings,physical,send);assert(events.size()==paused);
timer.update(10100,true,2,false,settings,physical,send);assert(timer.active());
success=false;timer.stop(physical,send);assert(timer.active());
success=true;timer.stop(physical,send);assert(!timer.active());
settings.mode=0;settings.jump='J';timer.update(11000,true,2,false,settings,physical,send);
const auto rebound=events.size();timer.update(12000,true,2,false,settings,physical,send);
assert(events.size()==rebound+1 && events.back()==std::make_pair(int('J'),true));
timer.stop(physical,send);
const auto sequence=input::activity_sequence.load();
const auto previous=SetMessageExtraInfo(static_cast<LPARAM>(input::sprint_input_tag));
input::observe_message(nullptr,WM_KEYDOWN,VK_SPACE,0);assert(input::activity_sequence==sequence);
SetMessageExtraInfo(previous);input::observe_message(nullptr,WM_KEYDOWN,VK_SPACE,0);
assert(input::activity_sequence==sequence+1);input::observe_message(nullptr,WM_KILLFOCUS,0,0);
input::observe_message(nullptr,WM_LBUTTONDBLCLK,0,0);assert(input::physical_keys[VK_LBUTTON]);
input::observe_message(nullptr,WM_LBUTTONUP,0,0);assert(!input::physical_keys[VK_LBUTTON]);
input::observe_message(nullptr,WM_XBUTTONDOWN,WPARAM(XBUTTON1)<<16,0);assert(input::physical_keys[VK_XBUTTON1]);
input::observe_message(nullptr,WM_XBUTTONUP,WPARAM(XBUTTON1)<<16,0);assert(!input::physical_keys[VK_XBUTTON1]);
std::cout<<"PASS: anti-AFK timing, alternating pulses, activity/menu cancellation, physical key ownership, rebinding and release retry\n";
}
+444
View File
@@ -0,0 +1,444 @@
// Integration test: the verified FOV prologue with a controlled 70-degree return.
// Exercises the real signature scanner, MinHook trampoline, and module lifecycle.
#include <cassert>
#include <iostream>
#include <limits>
#include "../src/modules/fov_changer.h"
#include "../src/modules/viewmodel.h"
#include "../src/modules/sprint_latch.h"
#include "../src/modules/crosshair_animation.h"
#include "../src/modules/crosshair.h"
#include "../src/modules/villager_trade.h"
#include "../src/modules/trade_profile.h"
#include "../src/gui/notifications.h"
#include "../src/input.h"
#pragma section(".fvtest", read, execute)
#pragma comment(linker, "/SECTION:.fvtest,ER")
__declspec(allocate(".fvtest")) unsigned char fixture[] = {0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x60, 0x44, 0x0f, 0x29, 0x44, 0x24, 0x50, 0x0f, 0x29, 0x7c, 0x24, 0x40, 0x0f, 0x29, 0x74, 0x24, 0x30, 0x44, 0x89, 0xc3, 0x0f, 0x28, 0xf1, 0x48, 0x89, 0xce, 0x45, 0x84, 0xc0, 0x0f, 0x84, 0x23, 0x00, 0x00, 0x00, 0x48, 0x8b, 0x86, 0x88, 0x11, 0x00, 0x00, 0x48, 0x8b, 0x88, 0xf8, 0x03, 0x00, 0x00, 0x48, 0x8b, 0x01, 0x48, 0x8b, 0x80, 0xd8, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x54, 0x24, 0x28, 0x41, 0xb8, 0x2f, 0x00, 0x00, 0x00, 0xf3, 0x0f, 0x10, 0x05, 0x18, 0x00, 0x00, 0x00, 0x0f, 0x28, 0x74, 0x24, 0x30, 0x0f, 0x28, 0x7c, 0x24, 0x40, 0x44, 0x0f, 0x28, 0x44, 0x24, 0x50, 0x48, 0x83, 0xc4, 0x60, 0x5b, 0x5f, 0x5e, 0xc3, 0x00, 0x00, 0x8c, 0x42};
__declspec(allocate(".fvtest")) unsigned char duplicate[sizeof(fixture)] = {};
#include "separate_hand_fixture.h"
#include "viewmodel_fixture.h"
#include "native_crosshair_fixture.h"
static void write_code(unsigned char* target, const unsigned char* bytes, size_t size);
static void identity(float* m) {
memset(m, 0, sizeof(float) * 16);
m[0] = m[5] = m[10] = m[15] = 1.f;
}
static bool close_float(float a, float b) { return std::fabs(a - b) < 0.00001f; }
static float main_seen[16], offhand_seen[16], after_offhand[16];
static unsigned char test_item[0x30]{};
static void __fastcall offhand_callback(void*, void* context, void*, void*) {
std::memcpy(offhand_seen, game::viewmodel_world_matrix(context), sizeof(offhand_seen));
}
static void __fastcall hands_callback(void*, void* context, void* source, unsigned char) {
float* matrix = game::viewmodel_world_matrix(context);
// Reproduce the real renderer consuming its distinct input matrix.
if (source) std::memcpy(matrix,source,16*sizeof(float));
std::memcpy(main_seen, matrix, sizeof(main_seen));
// An item/blocking animation applied after the shared hand transform.
const float animation[] = {0, 2, 0}, rotation[] = {0, 0, 0};
game::transform_viewmodel(matrix, animation, rotation);
using call_fn = void(__fastcall*)(void*, void*, void*, void*);
reinterpret_cast<call_fn>(static_cast<void*>(offhand_call_fixture))(nullptr, context, nullptr, test_item);
std::memcpy(after_offhand, matrix, sizeof(after_offhand));
}
static void test_viewmodel() {
uintptr_t callback = reinterpret_cast<uintptr_t>(&hands_callback);
write_code(hands_fixture + hands_callback_offset, reinterpret_cast<unsigned char*>(&callback), sizeof(callback));
callback = reinterpret_cast<uintptr_t>(&offhand_callback);
write_code(offhand_fixture + offhand_callback_offset, reinterpret_cast<unsigned char*>(&callback), sizeof(callback));
const int32_t displacement = static_cast<int32_t>(offhand_fixture - (offhand_call_fixture + offhand_call_offset + 18));
write_code(offhand_call_fixture + offhand_call_offset + 14,
reinterpret_cast<const unsigned char*>(&displacement), sizeof(displacement));
assert(sigscan::find(sigs::render_hands,true)==hands_fixture);
assert(sigscan::find(sigs::render_offhand_item,true)==offhand_fixture);
test_item[0x23]=1;
unsigned char renderer[0x178]{}, context[0x30]{}, render[0x20]{}, screen[0xc0]{};
float matrix[16]; identity(matrix);
float* map[]={matrix};
*reinterpret_cast<void**>(context+0x28)=render;
*reinterpret_cast<void**>(render+0x18)=screen;
*reinterpret_cast<void**>(screen+0x88)=map;
*reinterpret_cast<size_t*>(screen+0x90)=1;
*reinterpret_cast<size_t*>(screen+0xa0)=1;
void* vtable[0x100]{}; void* client=vtable;
*reinterpret_cast<void**>(renderer+0x170)=&client;
viewmodel module;
using draw_fn=void(__fastcall*)(void*,void*,void*,unsigned char);
auto draw=reinterpret_cast<draw_fn>(static_cast<void*>(hands_fixture));
module.set_enabled(true); assert(module.enabled());
module.settings()[0].float_value=0.5f;
module.settings()[1].float_value=-0.25f;
module.settings()[6].float_value=-0.75f;
module.settings()[7].float_value=0.4f;
// The earlier working direct hand hook must continue to apply sliders.
using bob_fn=void(__fastcall*)(void*,float*,float);
unsigned char bob_renderer[0x1200]{};
float bob_matrix[16];identity(bob_matrix);
module.on_render();
reinterpret_cast<bob_fn>(static_cast<void*>(hand_fixture))(bob_renderer,bob_matrix,0.5f);
assert(close_float(bob_matrix[12],1.5f) && close_float(bob_matrix[13],-0.25f));
module.on_frame_end(); // Invalidate previous-frame bob snapshots.
module.on_render(); draw(renderer,context,nullptr,0x21);
assert(close_float(main_seen[12],0.5f) && close_float(main_seen[13],-0.25f));
assert(close_float(offhand_seen[12],-0.75f) && close_float(offhand_seen[13],2.4f));
assert(close_float(after_offhand[12],0.5f) && close_float(after_offhand[13],1.75f));
assert(matrix[12]==0 && matrix[13]==0 && matrix[0]==1); // Scope restores shared matrix.
float distinct_source[16];identity(distinct_source);
draw(renderer,context,distinct_source,0x23);
assert(close_float(main_seen[12],0.5f));
assert(close_float(offhand_seen[12],-0.75f));
assert(distinct_source[12]==0); // Never alter the caller's input matrix.
for(int axis=0;axis<3;++axis) {
for(int i=0;i<12;++i) module.settings()[i].float_value=0;
module.settings()[3+axis].float_value=90.f;
module.on_render();draw(renderer,context,nullptr,0x21);
// Offhand remains neutral with its own original animation, independent of main rotation.
assert(close_float(offhand_seen[0],1) && close_float(offhand_seen[5],1) && close_float(offhand_seen[10],1));
if(axis==0) assert(close_float(main_seen[6],1) && close_float(main_seen[9],-1));
if(axis==1) assert(close_float(main_seen[2],-1) && close_float(main_seen[8],1));
if(axis==2) assert(close_float(main_seen[1],1) && close_float(main_seen[4],-1));
module.settings()[3+axis].float_value=0;
module.settings()[9+axis].float_value=90;
module.on_render();draw(renderer,context,nullptr,0x21);
assert(main_seen[0]==1 && main_seen[5]==1 && main_seen[10]==1);
if(axis==0) assert(close_float(offhand_seen[6],1) && close_float(offhand_seen[9],-1));
if(axis==1) assert(close_float(offhand_seen[2],-1) && close_float(offhand_seen[8],1));
if(axis==2) assert(close_float(offhand_seen[1],1) && close_float(offhand_seen[4],-1));
}
module.settings()[12].bool_value=false;
module.settings()[0].float_value=1;
module.on_render();draw(renderer,context,nullptr,0x21);
assert(close_float(main_seen[12],1) && close_float(offhand_seen[12],1));
for(int i=0;i<10;++i) {
module.set_enabled(false);identity(matrix);draw(renderer,context,nullptr,0x21);
assert(main_seen[12]==0 && offhand_seen[12]==0);
module.set_enabled(true);identity(matrix);draw(renderer,context,nullptr,0x21);
assert(close_float(main_seen[12],1));
}
module.set_enabled(false);
}
static void test_crosshair_animation() {
using namespace crosshair_animation;
for(int easing=0;easing<5;++easing) {
assert(ease(0,easing)==0 && ease(1,easing)==1);
float previous=0;
for(int i=0;i<=100;++i) { const float value=ease(i/100.f,easing);assert(value>=previous && value<=1);previous=value; }
channel slow,fast;
for(int i=0;i<60;++i) slow.update(1.f/60,true,0,false,0.75f,easing);
for(int i=0;i<144;++i) fast.update(1.f/144,true,0,false,0.75f,easing);
assert(std::fabs(slow.current-fast.current)<0.0001f);
channel reactive;
for(int i=0;i<60;++i) reactive.update(1.f/60,true,1,true,2,easing);
assert(reactive.current==1);
for(int i=0;i<60;++i) reactive.update(1.f/60,true,1,false,2,easing);
assert(reactive.current==0);
assert(reactive.update(0.1f,false,1,true,2,easing)==0);
double phase=0;
for(int i=0;i<60;++i) spin(phase,1.f/60,true,90,easing);
assert(std::fabs(phase-0.25)<0.0001);
assert(spin(phase,0.1f,false,90,easing)==0 && phase==0);
}
}
struct fake_trade_io : villager_trade::io {
std::vector<std::pair<char,villager_trade::point>> events;
int downs=0,ups=0,reads=0,stock_reads=0;
bool held=false,exhausted=false,stock_empty=false,read_ok=true,release_ok=true;
bool move(villager_trade::point p) override {events.push_back({'m',p});return true;}
bool button(bool down) override {
if(!down && !release_ok) return false;
if(down) {++downs;held=true;}else {++ups;held=false;}return true;
}
bool pixel(villager_trade::point,uint32_t& color) override {
++reads;color=exhausted ? 0x993434 : 0x111111;return read_ok;
}
bool stock(const villager_trade::config&,bool& found) override {++stock_reads;found=stock_empty;return read_ok;}
};
static void test_villager_trade() {
using namespace villager_trade;
assert(color_near(0xBA370F,0xBA370F,0));
assert(color_near(0xBC390F,0xBA370F,2));
assert(!color_near(0xBD390F,0xBA370F,2));
assert(red_score(0xBA370F)==131);
config settings;settings.row={10,20};settings.button={30,40};settings.stock={50,60};settings.stock_check=true;settings.max_trades=3;
auto run=[](engine& trading,fake_trade_io& input) {for(int i=0;i<1000 && trading.running();++i) trading.tick(i*0.01,input);assert(!trading.running());};
fake_trade_io input;engine trading;
assert(trading.start(settings,0));run(trading,input);
assert(trading.result()==reason::completed && trading.count()==3);
assert(input.downs==7 && input.ups==7 && !input.held && input.stock_reads==3 && input.reads==4);
assert(input.events[0].second.x==10 && input.events[1].second.x==30 && input.events[2].second.x==10);
fake_trade_io empty;empty.exhausted=true;
trading.start(settings,0);run(trading,empty);
assert(trading.result()==reason::out_of_materials && trading.count()==0 && empty.downs==1 && !empty.held);
fake_trade_io sold_out;sold_out.stock_empty=true;
trading.start(settings,0);run(trading,sold_out);
assert(trading.result()==reason::out_of_stock && sold_out.downs==1 && sold_out.ups==1);
fake_trade_io failed;failed.read_ok=false;
trading.start(settings,0);run(trading,failed);
assert(trading.result()==reason::read_failed && !failed.held);
fake_trade_io cancel;
trading.start(settings,0);trading.tick(0,cancel);trading.tick(0.01,cancel);
assert(cancel.held);
cancel.release_ok=false;trading.stop(cancel);
assert(!trading.running() && !trading.start(settings,0));
cancel.release_ok=true;trading.release_pending(cancel);
assert(!cancel.held && cancel.ups==1 && trading.start(settings,0));
trading.stop(cancel);
fake_trade_io disabled_checks;disabled_checks.read_ok=false;
settings.stock_check=false;settings.material_check=false;
trading.start(settings,0);run(trading,disabled_checks);
assert(trading.result()==reason::completed && disabled_checks.reads==0 && disabled_checks.stock_reads==0);
}
static int native_crosshair_draws=0;
static void __fastcall native_crosshair_callback(void* a,void* b,void* c,void* d) {
assert(a==reinterpret_cast<void*>(1) && b==reinterpret_cast<void*>(2) &&
c==reinterpret_cast<void*>(3) && d==reinterpret_cast<void*>(4));
++native_crosshair_draws;
}
static void test_crosshair_render() {
const uintptr_t callback=reinterpret_cast<uintptr_t>(&native_crosshair_callback);
write_code(native_crosshair_fixture+native_crosshair_callback_offset,
reinterpret_cast<const unsigned char*>(&callback),sizeof(callback));
using native_draw_fn=void(__fastcall*)(void*,void*,void*,void*);
auto native_draw=reinterpret_cast<native_draw_fn>(static_cast<void*>(native_crosshair_fixture));
auto draw_native=[&] { native_draw(reinterpret_cast<void*>(1),reinterpret_cast<void*>(2),
reinterpret_cast<void*>(3),reinterpret_cast<void*>(4)); };
ImGui::CreateContext();
ImGuiIO& io=ImGui::GetIO();
io.IniFilename=nullptr;
io.DisplaySize=ImVec2(800,600);
io.DeltaTime=1.f/60;
unsigned char* pixels;int width,height;
io.Fonts->GetTexDataAsRGBA32(&pixels,&width,&height);
crosshair cross;
draw_native();assert(native_crosshair_draws==1);
auto setting_named=[&](const char* name)->setting& {
for(auto& value:cross.settings()) if(value.name==name) return value;
assert(false);return cross.settings().front();
};
cross.set_enabled(true);
draw_native();assert(native_crosshair_draws==1); // Native drawing suppressed only while enabled.
for(int frame=0;frame<4;++frame) {
if(frame==1) {
setting_named("gradient").bool_value=true;
setting_named("gradient color").color[0]=0;
setting_named("spin").bool_value=true;
setting_named("dynamic gap").bool_value=true;
setting_named("dynamic length").bool_value=true;
}
if(frame==2) {
setting_named("gradient").bool_value=false;
setting_named("spin").bool_value=false;
setting_named("dynamic gap").bool_value=false;
setting_named("dynamic length").bool_value=false;
}
if(frame==3) {
setting_named("black outline").bool_value=true;
setting_named("outline width").float_value=2;
setting_named("center dot").bool_value=true;
setting_named("spin").bool_value=true;
}
ImGui::NewFrame();cross.on_render();
ImDrawList* draw=ImGui::GetBackgroundDrawList();
if(frame<3) assert(draw->VtxBuffer.Size==16 && draw->IdxBuffer.Size==24);
else {
assert(draw->VtxBuffer.Size>32 && draw->IdxBuffer.Size>48);
bool black=false;
for(const auto& vertex:draw->VtxBuffer)
if(vertex.col==IM_COL32(0,0,0,255)) black=true;
assert(black);
}
for(const auto& vertex:draw->VtxBuffer) assert(std::isfinite(vertex.pos.x) && std::isfinite(vertex.pos.y));
for(auto index:draw->IdxBuffer) assert(index<draw->VtxBuffer.Size);
if(frame==1) {
assert(draw->VtxBuffer[0].col!=draw->VtxBuffer[1].col);
assert(std::fabs(draw->VtxBuffer[0].pos.y-draw->VtxBuffer[1].pos.y)>0.1f);
} else if(frame<3) {
assert(draw->VtxBuffer[0].col==draw->VtxBuffer[1].col);
assert(close_float(draw->VtxBuffer[0].pos.x,404) && close_float(draw->VtxBuffer[1].pos.x,412));
}
ImGui::Render();
}
cross.set_enabled(false);
draw_native();assert(native_crosshair_draws==2);
for(int i=0;i<5;++i) {
cross.set_enabled(true);draw_native();assert(native_crosshair_draws==2+i);
cross.set_enabled(false);draw_native();assert(native_crosshair_draws==3+i);
}
notifications::items.clear();
notifications::push("Trading","1 / 500 trade attempts",notifications::kind::info,0,"trade",0.1f);
notifications::push("Trading","2 / 500 trade attempts",notifications::kind::info,0,"trade",0.2f);
assert(notifications::items.size()==1 && notifications::items[0].progress==0.2f);
notifications::push("Trade row saved","Client position: 814, 425",notifications::kind::success,3);
notifications::push("Out of stock","Trading stopped and mouse released.",notifications::kind::warning,3);
for(auto& item:notifications::items) item.born-=0.4;
ImGui::NewFrame();notifications::draw();
assert(ImGui::GetForegroundDrawList()->VtxBuffer.Size>0);
for(const auto& vertex:ImGui::GetForegroundDrawList()->VtxBuffer) assert(std::isfinite(vertex.pos.x) && std::isfinite(vertex.pos.y));
ImGui::Render();
notifications::dismiss("trade");assert(notifications::items[0].duration>0);
for(auto& item:notifications::items) item.born-=20;
ImGui::NewFrame();notifications::draw();assert(notifications::items.empty());ImGui::Render();
ImGui::DestroyContext();
}
static void test_sprint() {
sprint_latch latch;
bool physically_down[256]{};
std::vector<std::pair<int,bool>> events;
bool success = true;
auto physical = [&](int key) { return physically_down[key]; };
auto send = [&](int key, bool down) { if (success) events.emplace_back(key,down); return success; };
latch.update(true,VK_LCONTROL,physical,send);
latch.update(true,VK_LCONTROL,physical,send);
assert(events.size()==1 && latch.held_key()==VK_LCONTROL);
latch.update(false,0,physical,send);
assert(events.size()==2 && !events.back().second && latch.held_key()==0);
physically_down[VK_LCONTROL]=true;
latch.update(true,VK_LCONTROL,physical,send);
assert(events.size()==2 && latch.held_key()==0);
physically_down[VK_LCONTROL]=false;
latch.update(true,VK_LCONTROL,physical,send);
latch.update(true,VK_RCONTROL,physical,send);
assert(events[3]==std::make_pair(VK_LCONTROL,false) && events[4]==std::make_pair(VK_RCONTROL,true));
success=false;
latch.update(false,0,physical,send);
assert(latch.held_key()==VK_RCONTROL); // Retry a failed key-up rather than losing ownership.
success=true;
latch.update(false,0,physical,send);
assert(latch.held_key()==0);
latch.update(true,VK_LCONTROL,physical,send);
physically_down[VK_LCONTROL]=true;
const auto before=events.size();
latch.update(false,0,physical,send);
assert(latch.held_key()==0 && events.size()==before); // No release of a physical key.
const LPARAM previous=SetMessageExtraInfo(static_cast<LPARAM>(input::sprint_input_tag));
input::observe_message(nullptr,WM_KEYDOWN,VK_CONTROL,0);
assert(!input::physical_keys[VK_LCONTROL]);
SetMessageExtraInfo(previous);
input::observe_message(nullptr,WM_KEYDOWN,VK_CONTROL,0);
assert(input::physical_keys[VK_LCONTROL]);
input::observe_message(nullptr,WM_KILLFOCUS,0,0);
assert(!input::physical_keys[VK_LCONTROL]);
}
static void write_code(unsigned char* target, const unsigned char* bytes, size_t size) {
DWORD old;
assert(VirtualProtect(target, size, PAGE_EXECUTE_READWRITE, &old));
memcpy(target, bytes, size);
DWORD ignored;
assert(VirtualProtect(target, size, old, &ignored));
FlushInstructionCache(GetCurrentProcess(), target, size);
}
#include "profile_tests.h"
#include "world_tests.h"
#include "media_glint_tests.h"
#include "inventory_tests.h"
#include "anti_afk_tests.h"
#include "server_hud_tests.h"
#include "hud_grid_tests.h"
int main() {
test_profiles();
test_world_math_and_hooks();
test_world_filter();
test_world_huds();
test_media_and_glint();
test_inventory_tools();
test_anti_afk();
test_server_hud();
test_hud_grid();
// Fail closed on zero or multiple executable matches.
assert(sigscan::find(sigs::get_fov, true) == fixture);
write_code(duplicate, fixture, sizeof(fixture));
assert(sigscan::find(sigs::get_fov, true) == nullptr);
unsigned char zero = 0;
write_code(duplicate, &zero, 1);
write_code(fixture, &zero, 1);
assert(sigscan::find(sigs::get_fov, true) == nullptr);
unsigned char push_rsi = 0x56;
write_code(fixture, &push_rsi, 1);
assert(MH_Initialize() == MH_OK);
test_viewmodel();
test_sprint();
test_crosshair_animation();
test_villager_trade();
test_crosshair_render();
write_code(duplicate, fixture, sizeof(fixture));
{
fov_changer unavailable;
unavailable.set_enabled(true);
assert(!unavailable.enabled());
}
write_code(duplicate, &zero, 1);
write_code(fixture, &zero, 1);
{
fov_changer unavailable;
unavailable.set_enabled(true);
assert(!unavailable.enabled());
}
write_code(fixture, &push_rsi, 1);
{
fov_changer module;
using getter = float(__fastcall*)(void*, float, bool);
auto get_fov = reinterpret_cast<getter>(static_cast<void*>(fixture));
// Match the pointer reads in the verified game's function entry.
alignas(16) unsigned char renderer[0x1200] = {};
alignas(16) unsigned char context[0x400] = {};
void* options_vtable[0x100] = {};
void* options = options_vtable;
*reinterpret_cast<void**>(renderer + 0x1188) = context;
*reinterpret_cast<void**>(context + 0x3f8) = &options;
assert(!module.enabled());
assert(get_fov(renderer, 0.5f, true) == 70.f);
module.set_enabled(true);
assert(module.enabled());
assert(get_fov(renderer, 0.5f, true) == 90.f);
assert(get_fov(renderer, 0.5f, false) == 70.f);
module.settings()[0].float_value = 110.f;
module.on_render();
assert(get_fov(renderer, 0.5f, true) == 110.f);
module.settings()[0].float_value = 200.f;
module.on_render();
assert(get_fov(renderer, 0.5f, true) == 130.f);
module.settings()[0].float_value = 1.f;
module.on_render();
assert(get_fov(renderer, 0.5f, true) == 30.f);
module.settings()[0].float_value = std::numeric_limits<float>::quiet_NaN();
module.on_render();
assert(get_fov(renderer, 0.5f, true) == 90.f);
for (int i = 0; i < 10; ++i) {
module.set_enabled(false);
assert(get_fov(renderer, 0.5f, true) == 70.f);
module.set_enabled(true);
assert(get_fov(renderer, 0.5f, true) == 90.f);
}
module.set_enabled(false);
assert(get_fov(renderer, 0.5f, true) == 70.f);
// Zoom shares the verified hook and must work with FOV changer disabled,
// compose with its override, and leave hand projection untouched.
zoom_effect::magnification=4.f;
const float zoomed=get_fov(renderer,0.5f,true);
assert(zoomed>0 && zoomed<30 && std::abs(zoomed-zoom_effect::apply(70,4))<.001f);
assert(get_fov(renderer,0.5f,false)==70.f);
module.set_enabled(true);
assert(std::abs(get_fov(renderer,0.5f,true)-zoom_effect::apply(90,4))<.001f);
module.set_enabled(false);
zoom_effect::magnification=1;
assert(get_fov(renderer,0.5f,true)==70.f);
assert(zoom_effect::apply(70,std::numeric_limits<float>::quiet_NaN())==70);
assert(MH_Uninitialize() == MH_OK);
}
std::cout << "PASS: unique/missing/ambiguous signatures, actual hook/trampoline, "
"FOV and independent main/offhand transforms/restoration, sprint ownership/release/rebinding, "
"physical versus injected input, crosshair rendering/native suppression, villager trading stops/cancellation, animated notifications\n";
}
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64"><Configuration>Debug</Configuration><Platform>x64</Platform></ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals"><WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration"><ConfigurationType>Application</ConfigurationType><PlatformToolset>v143</PlatformToolset></PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<PropertyGroup><OutDir>$(ProjectDir)..\build\tests\</OutDir><IntDir>$(OutDir)obj\</IntDir></PropertyGroup>
<ItemDefinitionGroup>
<ClCompile><LanguageStandard>stdcpp17</LanguageStandard><WarningLevel>Level3</WarningLevel><UndefinePreprocessorDefinitions>NDEBUG</UndefinePreprocessorDefinitions><AdditionalIncludeDirectories>$(ProjectDir)..\vendor\minhook\include;$(ProjectDir)..\vendor\imgui;$(ProjectDir)..\vendor\imgui\backends</AdditionalIncludeDirectories></ClCompile>
<Link><AdditionalDependencies>user32.lib;%(AdditionalDependencies)</AdditionalDependencies></Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="fov_changer_test.cc" />
<ClCompile Include="..\vendor\imgui\imgui.cpp" />
<ClCompile Include="..\vendor\imgui\imgui_draw.cpp" />
<ClCompile Include="..\vendor\imgui\imgui_tables.cpp" />
<ClCompile Include="..\vendor\imgui\imgui_widgets.cpp" />
<ClCompile Include="..\vendor\minhook\src\buffer.c" />
<ClCompile Include="..\vendor\minhook\src\hook.c" />
<ClCompile Include="..\vendor\minhook\src\trampoline.c" />
<ClCompile Include="..\vendor\minhook\src\hde\hde64.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include "../src/config/profiles.h"
inline void test_hud_grid() {
using namespace hud_editor;
drag gesture;gesture.begin({23,37},{100,100});
auto p=gesture.move({101,101},{100,30},{800,600},true,10);assert(p.x==20 && p.y==40);
// Repeated sub-grid mouse movements must eventually move the snapped card.
for(int i=1;i<=12;++i)p=gesture.move({100.f+i,100.f+i},{100,30},{800,600},true,10);
assert(p.x==40 && p.y==50);
p=gesture.move({112,112},{100,30},{800,600},false,10);assert(p.x==35 && p.y==49);
p=gesture.move({2000,2000},{107,37},{800,600},true,10);assert(p.x==693 && p.y==563);
p=gesture.move({-2000,-2000},{100,30},{800,600},true,10);assert(p.x==0 && p.y==0);
p=gesture.move({110,110},{900,700},{800,600},true,10);assert(p.x==0 && p.y==0);
const auto original=options;options={};module_manager manager;const auto defaults=config::capture(manager);
options={false,false,24};auto custom=config::capture(manager);config::snapshot decoded;
assert(config::decode(config::encode(custom),decoded));options={};config::apply(manager,defaults,decoded);
assert(!options.snap && !options.show_grid && options.grid_size==24);
decoded["[hud editor]"].settings["grid size"].numbers[0]=500;
config::apply(manager,defaults,decoded);assert(options.grid_size==64);
config::apply(manager,defaults,{});assert(options.snap && options.show_grid && options.grid_size==10);
options=original;
std::cout<<"PASS: HUD grid accumulated dragging, free movement, screen bounds and profile preferences\n";
}
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include "../src/game/inventory_tools.h"
namespace inventory_test {
inline std::vector<world::item> stock;
inline world::item cursor;
inline int transfers=0,swaps=0;
inline bool defer_swap=false;inline int pending_source=-1,pending_destination=-1;
inline std::vector<std::string> transferred_groups;
struct type {unsigned char padding[0xd8]{};std::string name;};
inline type native_type;
inline uintptr_t counter=reinterpret_cast<uintptr_t>(&native_type);
inline unsigned char stack[48]{};
inline uintptr_t __fastcall item(uintptr_t,const std::string* group,int index) {
const auto value=*group=="cursor_items" ? cursor : index>=0 && index<int(stock.size()) ? stock[index] : world::item{};
native_type.name=value.name;*reinterpret_cast<uintptr_t*>(stack+8)=reinterpret_cast<uintptr_t>(&counter);
stack[0x22]=static_cast<unsigned char>(value.count);return reinterpret_cast<uintptr_t>(stack);
}
inline void __fastcall swap(uintptr_t,const std::string*,int index) {
// Native full-take refuses to replace a different held item.
assert(!cursor.count);++swaps;std::swap(cursor,stock.at(index));
}
inline void __fastcall place(uintptr_t,const std::string*,int index) {
assert(cursor.count);++swaps;
if(defer_swap && stock.at(index).count){pending_destination=index;return;}
std::swap(cursor,stock.at(index));
}
inline void refresh(inventory_tools::snapshot& state) {
state.panels[0].items=stock;state.held=cursor;state.cursor=cursor.count>0;
}
inline void __fastcall transfer(uintptr_t,int amount,const std::string* group,int index){assert(amount==stock.at(index).count && cursor.count==0);transferred_groups.push_back(*group);stock[index]={};++transfers;}
inline uint32_t __fastcall tick(uintptr_t){return 7;}
inline void __fastcall decline(uintptr_t,int,const std::string*,int){++transfers;}
}
inline void test_inventory_tools() {
using namespace inventory_tools;using namespace inventory_test;
auto old_item=get_item;auto old_swap=swap_cursor;auto old_place=place_all;auto old_auto=auto_place;
get_item=&item;swap_cursor=&swap;place_all=&place;auto_place=&transfer;
alignas(8) unsigned char controller[0x12d0]{};*reinterpret_cast<uintptr_t*>(controller+0x12c0)=1;
const auto owner=reinterpret_cast<uintptr_t>(controller);
stock={{"stone",64},{"apple",12},{"dirt",8},{"apple",3},{}};cursor={};
snapshot state;state.controller=owner;state.panels={{"container_items",stock},{"inventory_items",stock}};
engine worker;worker.start({owner,action::sort,"container_items"});
for(int i=0;i<40 && worker.active();++i){refresh(state);worker.step(state,1000+i*100,true);}
assert(!worker.active() && cursor.count==0 && stock[0].name=="apple" && stock[1].name=="apple" && stock[2].name=="dirt" && stock[3].name=="stone" && stock[4].name.empty());
assert(stock[0].count==12 && stock[1].count==3 && stock[3].count==64);
worker.start({owner,action::sort,"container_items"});state.cursor=true;worker.step(state,5000,true);assert(!worker.active());state.cursor=false;
worker.start({owner,action::sort,"container_items"});worker.step(state,5000,false);assert(!worker.active());
worker.start({owner+8,action::sort,"container_items"});worker.step(state,5000,true);assert(!worker.active());
transfers=0;worker.start({owner,action::steal,""});
for(int i=0;i<10 && worker.active();++i){state.panels[0].items=stock;worker.step(state,6000+i*100,true);}
assert(transfers==4 && !worker.active());
stock={{"stone",64}};state.panels[0].items=stock;auto_place=&decline;transfers=0;
worker.start({owner,action::steal,""});worker.step(state,8000,true);worker.step(state,8200,true);worker.step(state,8800,true);
assert(transfers==1 && !worker.active() && stock[0].count==64);
// Real UI sequencing: pickup, cursor swap, place-back, each acknowledged on later ticks.
stock={{"stone",64},{"apple",12}};cursor={};refresh(state);defer_swap=true;swaps=0;
worker.start({owner,action::sort,"container_items"});worker.step(state,10000,true);
refresh(state);worker.step(state,10100,true);assert(swaps==2 && cursor.name=="apple");
refresh(state);worker.step(state,10200,true);assert(swaps==2 && worker.active());
std::swap(cursor,stock[pending_destination]);refresh(state);worker.step(state,10300,true);
assert(cursor.count==0);refresh(state);worker.step(state,10400,true);worker.step(state,10500,true);
assert(!worker.active() && stock[0].name=="apple" && stock[1].name=="stone");
// Rejected swaps return the picked-up stack instead of abandoning it.
stock={{"stone",64},{"apple",12}};cursor={};refresh(state);worker.start({owner,action::sort,"container_items"});
worker.step(state,12000,true);refresh(state);worker.step(state,12100,true);
refresh(state);worker.step(state,13700,true);assert(cursor.count==0);refresh(state);worker.step(state,13800,true);
assert(!worker.active() && stock[0].name=="stone" && stock[1].name=="apple");defer_swap=false;
// The reported failure: sorting must move all 10 arrows, not a half-stack of 5.
stock={{"stone",64},{"apple",7},{"arrow",10}};cursor={};refresh(state);swaps=0;
worker.start({owner,action::sort,"container_items"});worker.step(state,14000,true);
assert(cursor.name=="apple" && cursor.count==7 && stock[1].count==0);
bool whole_arrows_seen=false;
for(int i=1;i<20 && worker.active();++i) {
refresh(state);worker.step(state,14000+i*100,true);
if(cursor.name=="arrow"){assert(cursor.count==10);whole_arrows_seen=true;}
}
assert(whole_arrows_seen);
assert(!worker.active() && !cursor.count && stock[0].name=="apple" && stock[0].count==7 && stock[1].name=="arrow" && stock[1].count==10 && stock[2].count==64);
// Dump routes inventory and optional hotbar stacks through quick move.
stock={{"stone",64}};state.panels={{"container_items",{}},{"inventory_items",stock},{"hotbar_items",stock}};
auto_place=&transfer;transferred_groups.clear();include_hotbar=true;
worker.start({owner,action::dump,""});worker.step(state,11000,true);
state.panels[1].items=stock;worker.step(state,11100,true);
stock={{"apple",3}};state.panels[2].items=stock;worker.step(state,11200,true);
state.panels[2].items=stock;worker.step(state,11300,true);
assert(!worker.active() && cursor.count==0 && transferred_groups==std::vector<std::string>({"inventory_items","hotbar_items"}));include_hotbar=false;
assert(next_minimum({},0)==-1);
// Additional controllers must not cancel an operation owned by a fresh chest.
auto old_tick=original_tick;auto old_current=current;auto old_published=latest();const bool old_enabled=enabled;
original_tick=&inventory_test::tick;enabled=true;state.controller=owner;state.stamp=GetTickCount64();
{std::lock_guard lock(mutex);published=state;}
current.start({owner,action::sort,"container_items"});
assert(tick_detour(owner+1)==7 && current.active() && latest().controller==owner);
current.cancel(engine::stop_reason::requested);assert(current.last_stop==engine::stop_reason::requested);
current=old_current;original_tick=old_tick;enabled=old_enabled;
{std::lock_guard lock(mutex);published=old_published;}
get_item=old_item;swap_cursor=old_swap;place_all=old_place;auto_place=old_auto;
std::cout<<"PASS: inventory transfer/sort scheduling, separate same-name stacks, empty slots, cursor/focus/controller cancellation\n";
}
+60
View File
@@ -0,0 +1,60 @@
#pragma once
#include "../src/modules/glint_changer.h"
#include "../src/modules/music_player.h"
inline float glint_received[4]{};
inline const glint_effect::values* glint_forwarded=nullptr;
inline void __fastcall glint_test_setter(uintptr_t,uintptr_t,const glint_effect::values* values) {
glint_forwarded=values;memcpy(glint_received,values->data,sizeof(glint_received));
}
inline void test_media_and_glint() {
const HRESULT apartment=CoInitializeEx(nullptr,COINIT_MULTITHREADED);assert(SUCCEEDED(apartment));
std::vector<unsigned char> bmp(58);
const auto dword=[&](int offset,uint32_t value){memcpy(bmp.data()+offset,&value,4);};
bmp[0]='B';bmp[1]='M';dword(2,58);dword(10,54);dword(14,40);dword(18,1);dword(22,1);
bmp[26]=1;bmp[28]=24;dword(34,4);bmp[54]=7;bmp[55]=23;bmp[56]=200;
auto cover=media::decode_art(bmp);assert(cover && cover->width==1 && cover->height==1 && cover->rgba[0]==200 && cover->rgba[1]==23 && cover->rgba[2]==7 && cover->rgba[3]==255);
std::vector<unsigned char> bad={1,2,3};assert(!media::decode_art(bad));CoUninitialize();
alignas(8) unsigned char context[0x80]{},entries[32]{},definition[0x40]{};
const auto ctx=reinterpret_cast<uintptr_t>(context);
*reinterpret_cast<uintptr_t*>(context+0x30)=reinterpret_cast<uintptr_t>(entries);
*reinterpret_cast<uint16_t*>(context+0x3a)=2;
*reinterpret_cast<uintptr_t*>(entries+16)=reinterpret_cast<uintptr_t>(definition);
*reinterpret_cast<uint64_t*>(definition+0x28)=glint_effect::color_name;
uint16_t index=1;float original_values[]={.2f,.3f,.4f,.8f};glint_effect::values source{1,original_values};
const auto old=glint_effect::original;glint_effect::original=&glint_test_setter;
glint_effect::enabled=true;glint_effect::tint=IM_COL32(255,64,128,200);
glint_effect::detour(ctx,reinterpret_cast<uintptr_t>(&index),&source);
assert(glint_received[0]==1 && std::abs(glint_received[1]-64.f/255)<1e-6 && glint_received[3]==200.f/255);
assert(original_values[0]==.2f && original_values[3]==.8f && source.data==original_values);
*reinterpret_cast<uint64_t*>(definition+0x28)=123;
glint_effect::detour(ctx,reinterpret_cast<uintptr_t>(&index),&source);assert(glint_forwarded==&source && glint_received[0]==.2f);
*reinterpret_cast<uint64_t*>(definition+0x28)=glint_effect::color_name;
index=2;assert(!glint_effect::is_color(ctx,reinterpret_cast<uintptr_t>(&index),reinterpret_cast<uintptr_t>(&source)));
index=1;source.count=2;assert(!glint_effect::is_color(ctx,reinterpret_cast<uintptr_t>(&index),reinterpret_cast<uintptr_t>(&source)));
source.count=1;glint_effect::enabled=false;glint_effect::detour(ctx,reinterpret_cast<uintptr_t>(&index),&source);assert(glint_forwarded==&source);
assert(!glint_effect::is_color(0,0,0));glint_effect::original=old;
ImGui::CreateContext();auto& io=ImGui::GetIO();io.DisplaySize={1280,720};io.DeltaTime=.016f;
io.Fonts->AddFontDefault();unsigned char* pixels;int width,height;io.Fonts->GetTexDataAsRGBA32(&pixels,&width,&height);
ImGui::NewFrame();music_player player;media::snapshot state;
player.draw(state);state.available=true;state.playing=true;state.title="Track title";state.artist="Artist";state.app="test player";
state.duration=240;state.position=60;state.stamp=GetTickCount64();player.draw(state);
Microsoft::WRL::ComPtr<ID3D11Device> art_device;Microsoft::WRL::ComPtr<ID3D11DeviceContext> art_context;D3D_FEATURE_LEVEL art_level;
assert(SUCCEEDED(D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_WARP,nullptr,0,nullptr,0,D3D11_SDK_VERSION,&art_device,&art_level,&art_context)));
media_art::device=art_device.Get();state.art=cover;player.draw(state);media_art::device=nullptr;
g_menu_open=true;player.draw(state);g_menu_open=false;
assert(player.hud_drag_size().y<player.hud_size().y);
ImGui::Render();assert(ImGui::GetDrawData()->TotalVtxCount>100);
for(int i=0;i<ImGui::GetDrawData()->CmdListsCount;++i)for(const auto& v:ImGui::GetDrawData()->CmdLists[i]->VtxBuffer)assert(std::isfinite(v.pos.x) && std::isfinite(v.pos.y));
ImGui::DestroyContext();
// Read-only live Windows API smoke test: no playback commands are sent.
media::reader reader;reader.start();const auto deadline=GetTickCount64()+4500;
while(reader.latest().message=="Looking for a media player..." && GetTickCount64()<deadline)Sleep(20);
const auto live=reader.latest();assert(live.available || live.message!="Looking for a media player...");
const auto stopped=GetTickCount64();reader.stop();assert(GetTickCount64()-stopped<1500);
assert(!reader.latest().available);reader.start();reader.stop();
media::system().start();media::shutdown();assert(media::instance==nullptr);
std::cout<<"PASS: isolated glint uniform replacement/forwarding, music HUD geometry and live Windows media API shutdown ("<<(live.available ? "session available" : live.message)<<")\n";
}
+3
View File
@@ -0,0 +1,3 @@
// Verified CursorRenderer render prologue with a controlled draw callback.
__declspec(allocate(".fvtest")) unsigned char native_crosshair_fixture[] = {0x55, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x53, 0x48, 0x81, 0xec, 0x18, 0x05, 0x00, 0x00, 0x48, 0x8d, 0xac, 0x24, 0x80, 0x00, 0x00, 0x00, 0x0f, 0x29, 0xbd, 0x80, 0x04, 0x00, 0x00, 0x0f, 0x29, 0xb5, 0x70, 0x04, 0x00, 0x00, 0x48, 0xc7, 0x85, 0x68, 0x04, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x4d, 0x89, 0xce, 0x4c, 0x89, 0xc6, 0x48, 0x89, 0xd3, 0x48, 0x89, 0xcf, 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd0, 0x0f, 0x28, 0xb5, 0x70, 0x04, 0x00, 0x00, 0x0f, 0x28, 0xbd, 0x80, 0x04, 0x00, 0x00, 0x48, 0x81, 0xc4, 0x18, 0x05, 0x00, 0x00, 0x5b, 0x5f, 0x5e, 0x41, 0x5c, 0x41, 0x5d, 0x41, 0x5e, 0x41, 0x5f, 0x5d, 0xc3};
constexpr size_t native_crosshair_callback_offset=66;
+131
View File
@@ -0,0 +1,131 @@
#pragma once
#include "../src/config/profiles.h"
class profile_test_module : public module {
public:
int enables = 0, disables = 0, actions = 0;
bool running = false;
profile_test_module() : module("Test \"module\"", "", category::hud, VK_F2) {
add_toggle("switch", true);
add_float("float", 1.5f, -5, 5);
add_int("integer", 4, -10, 10);
add_mode("mode", {"first", "second"});
add_color("color", .1f, .2f, .3f, .4f);
add_key("key", VK_F6);
add_action("action", [this] { ++actions; });
add_text("name", "Player", 48);
}
void on_enable() override { ++enables; }
void on_disable() override { ++disables; running = false; if (config_save::request) config_save::request(); }
};
inline void test_profiles() {
using namespace config;
assert(valid_name("Survival build_2"));
for (const auto& name : {"", "../escape", "x/y", "x\\y", "CON", "Lpt1", "NUL", "trailing ", " leading", "foo.bar", "x:y"}) assert(!valid_name(name));
module_manager manager;
auto* m = manager.add<profile_test_module>(); m->set_enabled(true);
const auto defaults = capture(manager);
m->settings()[0].bool_value = false;
m->settings()[1].float_value = -3.25f;
m->settings()[2].int_value = 9;
m->settings()[3].int_value = 1;
m->settings()[4].color[3] = .75f;
m->settings()[5].int_value = VK_END;
m->settings()[7].text_value = "Local \"name\"";
m->set_toggle_key(VK_F12); m->hud_pos = ImVec2(333, 444);
const auto customized = capture(manager);
snapshot decoded;
const auto serialized = encode(customized);
assert(decode(serialized, decoded)); assert(encode(decoded) == serialized);
assert(decoded.begin()->second.settings.size() == 7); // actions never serialize
m->running = true;
apply(manager, defaults, decoded);
assert(!m->running && m->enabled() && m->actions == 0);
assert(m->toggle_key() == VK_F12 && m->hud_pos.x == 333 && m->hud_pos.y == 444);
assert(!m->settings()[0].bool_value && m->settings()[1].float_value == -3.25f);
assert(m->settings()[2].int_value == 9 && m->settings()[3].int_value == 1);
assert(m->settings()[4].color[3] == .75f && m->settings()[5].int_value == VK_END);
assert(m->settings()[7].text_value == "Local \"name\"");
// Missing options use defaults, unknown settings/modules are ignored, changed
// mode order resolves by name, and edited numeric values stay in GUI bounds.
snapshot partial;
auto& state = partial[m->name()]; state.enabled = false;
state.settings["float"] = customized.at(m->name()).settings.at("float"); state.settings["float"].numbers[0] = 999;
state.settings["integer"] = customized.at(m->name()).settings.at("integer"); state.settings["integer"].numbers[0] = -999;
state.settings["mode"] = customized.at(m->name()).settings.at("mode");
state.settings["unknown"] = {};
partial["Removed module"] = {};
std::swap(m->settings()[3].modes[0], m->settings()[3].modes[1]);
apply(manager, defaults, partial);
assert(!m->enabled() && m->settings()[0].bool_value);
assert(m->settings()[1].float_value == 5 && m->settings()[2].int_value == -10);
assert(m->settings()[3].int_value == 0); // second option is now index 0
std::swap(m->settings()[3].modes[0], m->settings()[3].modes[1]);
for (const auto& bad : {std::string("garbage"), serialized.substr(0, serialized.size() - 4), serialized + "junk\n",
std::string("AMNESIA_PROFILE 2\nend\n"), std::string("AMNESIA_PROFILE 1\nmodule \"bad\" 3 0 0 0\nend\n"),
std::string("AMNESIA_PROFILE 1\nmodule \"bad\" 1 0 nan 0\nend\n")}) {
snapshot preserved = customized; assert(!decode(bad, preserved)); assert(encode(preserved) == serialized);
}
apply(manager, defaults, customized);
const auto root = directory() / ("profile-test-" + std::to_string(GetCurrentProcessId()) + "-" + std::to_string(GetTickCount64()));
profile_manager service; service.initialize(manager, root);
assert(service.active() == "Default" && !service.dirty());
assert(fs::exists(root / "Default.profile"));
m->settings()[1].float_value = 2.75f;
service.tick(100); service.tick(100.5); assert(service.dirty());
service.tick(100.8); assert(!service.dirty());
assert(read(root / "Default.profile", decoded));
assert(decoded.at(m->name()).settings.at("float").numbers[0] == 2.75);
assert(service.create("Trading")); assert(!service.create("trading"));
m->settings()[1].float_value = -2;
m->running = true;
assert(service.switch_to("Default")); assert(!m->running);
assert(m->settings()[1].float_value == 2.75f);
assert(service.switch_to("Trading")); assert(m->settings()[1].float_value == -2);
assert(service.rename("Villager trades")); assert(!fs::exists(root / "Trading.profile"));
assert(service.active() == "Villager trades");
assert(atomic_write(root / "active.txt", "Missing profile\n"));
{
module_manager restarted; auto* restored = restarted.add<profile_test_module>();
profile_manager fallback; fallback.initialize(restarted, root, false);
assert(fallback.active() == "Default" && restored->settings()[1].float_value == 2.75f);
}
assert(atomic_write(root / "active.txt", "Villager trades\n"));
// Reinitializing restores the active profile, toggles, keys and settings.
{
module_manager restarted; auto* restored = restarted.add<profile_test_module>();
profile_manager second; second.initialize(restarted, root, false);
assert(second.active() == "Villager trades" && restored->enabled());
assert(restored->settings()[1].float_value == -2 && restored->toggle_key() == VK_F12);
}
// A temporary-file collision cannot truncate the existing saved profile.
const auto saved = encode(capture(manager));
assert(fs::create_directory(root / "Villager trades.profile.tmp"));
m->settings()[1].float_value = 4;
assert(!service.save(false)); assert(service.dirty());
assert(read(root / "Villager trades.profile", decoded)); assert(encode(decoded) == saved);
assert(fs::remove(root / "Villager trades.profile.tmp"));
assert(service.remove_active()); assert(service.active() == "Default");
assert(!service.remove_active()); assert(!service.rename("Renamed Default"));
assert(atomic_write(root / "Broken.profile", "damaged file\n"));
const auto before = encode(capture(manager));
assert(!service.switch_to("Broken")); assert(encode(capture(manager)) == before);
assert(atomic_write(root / "active.txt", "Broken\n"));
{
profile_manager damaged; damaged.initialize(manager, root, false);
assert(damaged.blocked()); damaged.tick(500); damaged.tick(510);
std::ifstream original(root / "Broken.profile"); std::string line; std::getline(original, line); assert(line == "damaged file");
assert(damaged.create("Recovery")); // fresh file preserves damaged one
damaged.shutdown();
}
// Debounce still saves during continuous edits after five seconds, then
// shutdown saves the enabled state before module destruction disables it.
assert(service.switch_to("Default"));
for (int i = 0; i < 7; ++i) { m->hud_pos.x = float(i + 20); service.tick(600 + i); }
assert(read(root / "Default.profile", decoded)); assert(decoded.at(m->name()).x == 25);
m->set_enabled(true); m->hud_pos.x = 900; service.shutdown();
m->set_enabled(false);
assert(read(root / "Default.profile", decoded)); assert(decoded.at(m->name()).enabled && decoded.at(m->name()).x == 900);
std::cout << "PASS: profile round-trip, defaults/modes/clamps, autosave, switching/cancellation, remembered profile, rename/delete, atomic failure and damaged-file preservation\n";
}
+5
View File
@@ -0,0 +1,5 @@
// Verified 26.52 entries and offhand call site with controlled callbacks.
__declspec(allocate(".fvtest")) unsigned char hands_fixture[] = {0x55, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x53, 0x48, 0x81, 0xec, 0x18, 0x02, 0x00, 0x00, 0x48, 0x8d, 0xac, 0x24, 0x80, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xbd, 0x80, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xb5, 0x70, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xad, 0x60, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xa5, 0x50, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x9d, 0x40, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x95, 0x30, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x8d, 0x20, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x85, 0x10, 0x01, 0x00, 0x00, 0x0f, 0x29, 0xbd, 0x00, 0x01, 0x00, 0x00, 0x0f, 0x29, 0xb5, 0xf0, 0x00, 0x00, 0x00, 0x48, 0xc7, 0x85, 0xe8, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x44, 0x88, 0x4d, 0x7f, 0x4d, 0x89, 0xc7, 0x48, 0x89, 0xd3, 0x48, 0x89, 0xce, 0x48, 0x8b, 0x89, 0x70, 0x01, 0x00, 0x00, 0x48, 0x8b, 0x01, 0x48, 0x8b, 0x80, 0xf8, 0x00, 0x00, 0x00, 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd0, 0x0f, 0x28, 0xb5, 0xf0, 0x00, 0x00, 0x00, 0x0f, 0x28, 0xbd, 0x00, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0x85, 0x10, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0xbd, 0x80, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0xb5, 0x70, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0xad, 0x60, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0xa5, 0x50, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0x9d, 0x40, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0x95, 0x30, 0x01, 0x00, 0x00, 0x44, 0x0f, 0x28, 0x8d, 0x20, 0x01, 0x00, 0x00, 0x48, 0x81, 0xc4, 0x18, 0x02, 0x00, 0x00, 0x5b, 0x5f, 0x5e, 0x41, 0x5c, 0x41, 0x5d, 0x41, 0x5e, 0x41, 0x5f, 0x5d, 0xc3};
__declspec(allocate(".fvtest")) unsigned char offhand_fixture[] = {0x55, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x56, 0x57, 0x53, 0x48, 0x81, 0xec, 0xd8, 0x03, 0x00, 0x00, 0x48, 0x8d, 0xac, 0x24, 0x80, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x8d, 0x40, 0x03, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x85, 0x30, 0x03, 0x00, 0x00, 0x0f, 0x29, 0xbd, 0x20, 0x03, 0x00, 0x00, 0x0f, 0x29, 0xb5, 0x10, 0x03, 0x00, 0x00, 0x48, 0xc7, 0x85, 0x08, 0x03, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x41, 0x80, 0x79, 0x23, 0x01, 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd0, 0x44, 0x0f, 0x28, 0x8d, 0x40, 0x03, 0x00, 0x00, 0x44, 0x0f, 0x28, 0x85, 0x30, 0x03, 0x00, 0x00, 0x0f, 0x28, 0xbd, 0x20, 0x03, 0x00, 0x00, 0x0f, 0x28, 0xb5, 0x10, 0x03, 0x00, 0x00, 0x48, 0x81, 0xc4, 0xd8, 0x03, 0x00, 0x00, 0x5b, 0x5f, 0x5e, 0x41, 0x5c, 0x41, 0x5d, 0x41, 0x5e, 0x41, 0x5f, 0x5d, 0xc3};
__declspec(allocate(".fvtest")) unsigned char offhand_call_fixture[] = {0x55, 0x57, 0x56, 0x41, 0x56, 0x48, 0x81, 0xec, 0x28, 0x02, 0x00, 0x00, 0x48, 0x8d, 0xac, 0x24, 0x80, 0x00, 0x00, 0x00, 0x48, 0x89, 0xcf, 0x48, 0x89, 0x55, 0xf8, 0x4c, 0x89, 0xc6, 0x4d, 0x89, 0xce, 0x48, 0x89, 0xf9, 0x48, 0x8b, 0x55, 0xf8, 0x49, 0x89, 0xf0, 0x4d, 0x89, 0xf1, 0xe8, 0xbb, 0x6c, 0xfe, 0xff, 0xc6, 0x85, 0xe0, 0x00, 0x00, 0x00, 0x00, 0xc7, 0x85, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x81, 0xc4, 0x28, 0x02, 0x00, 0x00, 0x41, 0x5e, 0x5e, 0x5f, 0x5d, 0xc3};
constexpr size_t hands_callback_offset=148, offhand_callback_offset=75, offhand_call_offset=33;
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include "../src/modules/server_hud.h"
inline void test_server_hud() {
assert(xp_math::next(0)==7 && xp_math::next(15)==37 && xp_math::next(16)==42);
assert(xp_math::next(30)==112 && xp_math::next(31)==121 && xp_math::remaining(28,.5f)==51);
assert(xp_math::remaining(0,1)==0 && xp_math::remaining(0,0)==7);
alignas(8) unsigned char attrs[80]{},values[272]{};uint32_t keys[]{4,5};
auto put=[](unsigned char* p,size_t off,auto value){memcpy(p+off,&value,sizeof(value));};
put(attrs,0,uintptr_t(keys));put(attrs,8,uintptr_t(keys+2));put(attrs,24,uintptr_t(values));put(attrs,32,uintptr_t(values+272));
put(values,0x70,28.f);put(values,136+0x70,.3f);put(values,0x7c,0.f);
int level;float progress;assert(world::read_xp_values(uintptr_t(attrs),level,progress) && level==28 && progress==.3f);
put(values,136+0x70,std::numeric_limits<float>::quiet_NaN());assert(!world::read_xp_values(uintptr_t(attrs),level,progress));
put(values,136+0x70,1.1f);assert(!world::read_xp_values(uintptr_t(attrs),level,progress));
struct node {uintptr_t next=0,previous=0;unsigned char uuid_and_entry[40]{};std::string name;};
static_assert(offsetof(node,name)==56);node head,a,b;a.name="Zoe";b.name="Alex";
head.next=uintptr_t(&a);a.next=uintptr_t(&b);b.next=uintptr_t(&head);
uintptr_t map[]{0,uintptr_t(&head),2};std::vector<std::string> names;
assert(world::read_roster_map(uintptr_t(map),names) && names==std::vector<std::string>({"Alex","Zoe"}));
b.next=uintptr_t(&a);assert(!world::read_roster_map(uintptr_t(map),names));b.next=uintptr_t(&head);
map[2]=1025;assert(!world::read_roster_map(uintptr_t(map),names));map[2]=0;head.next=uintptr_t(&head);
assert(world::read_roster_map(uintptr_t(map),names) && names.empty());
// Sparse UI views report capacity from their actual ItemStack vector.
alignas(8) unsigned char view[0x110]{},getter[]{0x48,0x8b,0x81,0x08,0x01,0,0};uintptr_t vt[5]{};vt[4]=uintptr_t(getter);
put(view,0,uintptr_t(vt));put(view,0x100,uintptr_t(0x100000));put(view,0x108,uintptr_t(0x100000+54*152));
assert(inventory_tools::view_count(uintptr_t(view))==54);
put(view,0x108,uintptr_t(0x100000+27*152));assert(inventory_tools::view_count(uintptr_t(view))==27);
put(view,0x108,uintptr_t(0x100001));assert(inventory_tools::view_count(uintptr_t(view))==-1);
getter[0]=0;assert(inventory_tools::view_count(uintptr_t(view))==-1);
ImGui::CreateContext();auto& io=ImGui::GetIO();io.DisplaySize={1280,720};io.DeltaTime=.016f;
io.Fonts->AddFontDefault();unsigned char* pixels;int w,h;io.Fonts->GetTexDataAsRGBA32(&pixels,&w,&h);
ImGui::NewFrame();g_menu_open=true;
world::frame frame;frame.valid=true;frame.stamp=GetTickCount64();frame.xp_known=true;frame.xp_level=28;frame.xp_progress=.3f;frame.roster_known=true;
for(int i=0;i<25;++i)frame.online_players.push_back("player "+std::to_string(i));world::publish(frame);
tab_list list;xp_progress_hud xp;list.on_render();xp.on_render();assert(list.hud_size().x==360 && xp.hud_size().y==54);
world::publish({});list.on_render();xp.on_render();list.on_disable();xp.on_disable();
assert(!world::collect_roster && !world::collect_xp);
ImGui::Render();auto* data=ImGui::GetDrawData();assert(data->TotalVtxCount>100);
for(int i=0;i<data->CmdListsCount;++i)for(auto& v:data->CmdLists[i]->VtxBuffer)assert(std::isfinite(v.pos.x) && std::isfinite(v.pos.y));
g_menu_open=false;ImGui::DestroyContext();
std::cout<<"PASS: sparse container capacity, online roster integrity, XP attributes/boundaries and HUD geometry\n";
}
+2
View File
@@ -0,0 +1,2 @@
// Verified hand-bob prologue with a controlled original transform.
__declspec(allocate(".fvtest")) unsigned char hand_fixture[] = {0x55, 0x56, 0x57, 0x53, 0x48, 0x81, 0xec, 0x28, 0x01, 0x00, 0x00, 0x48, 0x8d, 0xac, 0x24, 0x80, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xbd, 0x90, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x29, 0xb5, 0x80, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x29, 0x6d, 0x70, 0x44, 0x0f, 0x29, 0x65, 0x60, 0x44, 0x0f, 0x29, 0x5d, 0x50, 0x44, 0x0f, 0x29, 0x55, 0x40, 0x44, 0x0f, 0x29, 0x4d, 0x30, 0x44, 0x0f, 0x29, 0x45, 0x20, 0x0f, 0x29, 0x7d, 0x10, 0x0f, 0x29, 0x75, 0x00, 0x48, 0xc7, 0x45, 0xf8, 0xfe, 0xff, 0xff, 0xff, 0x0f, 0x28, 0xfa, 0x48, 0x89, 0xd6, 0x48, 0x8b, 0x89, 0x68, 0x11, 0x00, 0x00, 0xf3, 0x0f, 0x10, 0x46, 0x30, 0xf3, 0x0f, 0x58, 0x05, 0x47, 0x00, 0x00, 0x00, 0xf3, 0x0f, 0x11, 0x46, 0x30, 0x0f, 0x28, 0x75, 0x00, 0x0f, 0x28, 0x7d, 0x10, 0x44, 0x0f, 0x28, 0x45, 0x20, 0x44, 0x0f, 0x28, 0x4d, 0x30, 0x44, 0x0f, 0x28, 0x55, 0x40, 0x44, 0x0f, 0x28, 0x5d, 0x50, 0x44, 0x0f, 0x28, 0x65, 0x60, 0x44, 0x0f, 0x28, 0x6d, 0x70, 0x44, 0x0f, 0x28, 0xb5, 0x80, 0x00, 0x00, 0x00, 0x44, 0x0f, 0x28, 0xbd, 0x90, 0x00, 0x00, 0x00, 0x48, 0x81, 0xc4, 0x28, 0x01, 0x00, 0x00, 0x5b, 0x5f, 0x5e, 0x5d, 0xc3, 0x00, 0x00, 0x80, 0x3f};
+145
View File
@@ -0,0 +1,145 @@
#pragma once
#include "../src/modules/world_modules.h"
#include "../src/modules/fps_counter.h"
#include "../src/modules/keystrokes.h"
#include "../src/modules/watermark.h"
#include "../src/modules/cps_counter.h"
#include "../src/modules/clock.h"
#include "../src/modules/zoom.h"
#include "../src/modules/anti_afk.h"
inline float world_test_time(void*,int ticks,float alpha){return float(ticks)+alpha;}
inline world::color* world_test_fog(void*,world::color* output,const world::color* base,float brightness){*output=*base;output->r*=brightness;return output;}
inline const std::string* world_test_name(uintptr_t){static const std::string real="Original";return &real;}
inline void test_world_math_and_hooks() {
using namespace world;
float matrix[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};ImVec2 screen;
assert(project(matrix,{0,0,0},{0,0,-5},1,1,{800,600},screen));assert(screen.x==400 && screen.y==300);
assert(!project(matrix,{0,0,0},{0,0,5},1,1,{800,600},screen));
assert(!project(matrix,{0,0,0},{0,0,0},1,1,{800,600},screen));
ImVec2 end;assert(project_edge(matrix,{0,0,0},{0,0,1},{0,0,-5},1,1,{800,600},screen,end));
assert(!project_edge(matrix,{0,0,0},{0,0,1},{0,0,2},1,1,{800,600},screen,end));
const auto q=turn({},90,20);assert(std::abs(q.x*q.x+q.y*q.y+q.z*q.z+q.w*q.w-1)<1e-5f);
const auto original=quaternion{};const auto restored=turn(turn(original,90,0),-90,0);assert(std::abs(restored.w-1)<1e-5f);
// Orbit position follows camera orientation around a fixed player pivot.
const vec3 pivot{12,65,-8};const auto back=orbit_position(pivot,{},4);
assert(distance(back,pivot)==4 && back.z==-4 && back.x==12);
const auto side=orbit_position(pivot,turn({},90,0),4);
assert(std::abs(distance(side,pivot)-4)<1e-5f && std::abs(side.x-8)<1e-5f);
const auto front=orbit_position(pivot,turn({},180,0),4);
assert(std::abs(front.z+12)<1e-5f && std::abs(front.x-12)<1e-5f);
const auto full=orbit_position(pivot,turn({},360,0),4);assert(distance(full,back)<1e-5f);
const auto overhead=orbit_position(pivot,turn({},90,85),6);assert(std::abs(distance(overhead,pivot)-6)<1e-5f);
assert(pivot.x==12 && pivot.y==65 && pivot.z==-8);
// Player angle locking is independent of movement and camera orbit rotation.
player_look_lock angle_lock;std::array<float,4> player_rotation{15,70,14,69};
std::array<float,2> head_angle{70,69},body_angle{65,64},render_angle{15,70};vec3 moving_player{2,3,4};
auto apply_lock=[&](bool active,uintptr_t owner=1){return angle_lock.apply(owner,7,uintptr_t(&player_rotation),uintptr_t(&head_angle),uintptr_t(&body_angle),uintptr_t(&render_angle),active);};
assert(apply_lock(true));
player_rotation={80,-120,79,-119};head_angle={-120,-119};body_angle={-100,-99};render_angle={80,-120};moving_player.x+=5;
assert(apply_lock(true) && player_rotation[0]==15 && player_rotation[1]==70 && head_angle[0]==70 && body_angle[0]==65 && render_angle[1]==70);
assert(angle_lock.delta[0]==65 && angle_lock.delta[1]==170);
assert(apply_lock(true) && angle_lock.delta[0]==0 && angle_lock.delta[1]==0);
player_rotation={80,-120,79,-119};assert(apply_lock(true));
assert(angle_lock.delta[0]==0 && angle_lock.delta[1]==0); // cached target, mouse stopped
player_rotation={85,-110,84,-111};assert(apply_lock(true));
assert(angle_lock.delta[0]==5 && angle_lock.delta[1]==10); // new mouse movement only
assert(moving_player.x==7 && moving_player.y==3 && moving_player.z==4);
const auto camera_side=orbit_position(moving_player,turn({},120,0),4);assert(std::abs(distance(camera_side,moving_player)-4)<1e-5f);
assert(!apply_lock(false));player_rotation={20,90,20,90};assert(!apply_lock(false) && player_rotation[1]==90);
assert(apply_lock(true) && angle_lock.rotation[1]==90);
player_rotation={25,100,25,100};assert(apply_lock(true,2) && angle_lock.rotation[1]==100);
assert(weapon("diamond_sword") && weapon("crossbow") && weapon("netherite_axe") && !weapon("diamond_pickaxe") && !weapon("bread"));
assert(clean_name("\xc2\xa7" "aPlayer\n")=="Player");
assert(item_label("minecraft:diamond_helmet")=="diamond helmet");
auto old_time=original_time;original_time=&world_test_time;render_thread=GetCurrentThreadId();time_override=6000;
assert(time_detour(nullptr,18000,.5f)==6000.5f);time_override=-1;assert(time_detour(nullptr,18000,.5f)==18000.5f);
time_override=6000;render_thread=0;assert(time_detour(nullptr,18000,.5f)==18000.5f);time_override=-1;original_time=old_time;
auto old_fog=original_fog;original_fog=&world_test_fog;render_thread=GetCurrentThreadId();fog_enabled=true;fog_color=IM_COL32(255,0,0,255);
color input{.25f,.5f,.75f,1},result{};fog_detour(nullptr,&result,&input,1);assert(result.r==1 && result.g==0 && result.b==0 && result.a==1);
fog_enabled=false;fog_detour(nullptr,&result,&input,1);assert(result.r==input.r && result.g==input.g);original_fog=old_fog;
auto old_name=original_name;original_name=&world_test_name;local_actor=123;alias_enabled=true;set_alias("My local name");rendering=true;
assert(*name_detour(123)=="My local name");rendering=false;assert(*name_detour(123)=="Original");assert(*world_test_name(123)=="Original");
alias_enabled=false;original_name=old_name;local_actor=0;
// Real native get_at ABI using a controlled executable leaf with the
// verified payload-load prefix, sparse versions and packed membership.
const unsigned char bytes[]={0x48,0x8b,0x49,0x50,0x49,0x89,0xd0,0x49,0xc1,0xe8,0x07,0x83,0xe2,0x7f,0x8d,0x04,0xd5,0,0,0,0,0x4a,0x03,0x04,0xc1,0xc3};
auto* code=VirtualAlloc(nullptr,4096,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);assert(code);memcpy(code,bytes,sizeof(bytes));DWORD old;
assert(VirtualProtect(code,4096,PAGE_EXECUTE_READ,&old));FlushInstructionCache(GetCurrentProcess(),code,sizeof(bytes));
uintptr_t vt[]={reinterpret_cast<uintptr_t>(code)};uint32_t sparse[2048];std::fill(sparse,sparse+2048,0xffffffffu);
uint32_t packed[]={0x40003};sparse[3]=0x40000;uintptr_t pages[]={reinterpret_cast<uintptr_t>(sparse)};
uintptr_t payload[128]{};payload[0]=0x12345678;uintptr_t payload_pages[]={reinterpret_cast<uintptr_t>(payload)};
uintptr_t storage[16]{};storage[0]=reinterpret_cast<uintptr_t>(vt);storage[1]=reinterpret_cast<uintptr_t>(pages);storage[2]=storage[1]+8;
storage[4]=reinterpret_cast<uintptr_t>(packed);storage[5]=storage[4]+4;storage[10]=reinterpret_cast<uintptr_t>(payload_pages);
assert(component_at(reinterpret_cast<uintptr_t>(storage),0x40003)==reinterpret_cast<uintptr_t>(payload));
assert(!component_at(reinterpret_cast<uintptr_t>(storage),3));assert(!component_at(reinterpret_cast<uintptr_t>(storage),0x40004));
assert(!component_at(0,0x40003));assert(!component_at(1,0x40003));
// ActorRotation's real 16-byte getter has an index-copy prefix.
const unsigned char rotation_bytes[]={0x48,0x89,0xd0,0x48,0x8b,0x49,0x50,0x48,0xc1,0xea,0x07,0x83,0xe0,0x7f,0xc1,0xe0,0x04,0x48,0x03,0x04,0xd1,0xc3};
assert(VirtualProtect(code,4096,PAGE_READWRITE,&old));memcpy(code,rotation_bytes,sizeof(rotation_bytes));
assert(VirtualProtect(code,4096,PAGE_EXECUTE_READ,&old));FlushInstructionCache(GetCurrentProcess(),code,sizeof(rotation_bytes));
assert(component_at(reinterpret_cast<uintptr_t>(storage),0x40003)==reinterpret_cast<uintptr_t>(payload));
assert(!component_at(reinterpret_cast<uintptr_t>(storage),0x80003));
assert(VirtualFree(code,0,MEM_RELEASE));
std::cout<<"PASS: projection, freelook quaternion, weapon filtering, visual time/fog/name isolation and native ECS read-only access\n";
}
inline void test_world_filter() {
using namespace world_filter;
ComPtr<ID3D11Device> device;ComPtr<ID3D11DeviceContext> context;D3D_FEATURE_LEVEL level;
assert(SUCCEEDED(D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_WARP,nullptr,0,nullptr,0,D3D11_SDK_VERSION,&device,&level,&context)));
D3D11_TEXTURE2D_DESC desc{};desc.Width=32;desc.Height=32;desc.MipLevels=1;desc.ArraySize=1;desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count=1;desc.Usage=D3D11_USAGE_DEFAULT;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
ComPtr<ID3D11Texture2D> output;ComPtr<ID3D11RenderTargetView> target;
assert(SUCCEEDED(device->CreateTexture2D(&desc,nullptr,&output)));assert(SUCCEEDED(device->CreateRenderTargetView(output.Get(),nullptr,&target)));
ID3D11RenderTargetView* rt=target.Get();context->OMSetRenderTargets(1,&rt,nullptr);
const float white[4]={1,1,1,1};context->ClearRenderTargetView(rt,white);
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
D3D11_VIEWPORT viewport{2,3,20,18,0,1};context->RSSetViewports(1,&viewport);
enabled=true;tint=IM_COL32(255,128,64,255);brightness=.5f;
assert(apply(device.Get(),context.Get(),rt));
D3D11_PRIMITIVE_TOPOLOGY topology;context->IAGetPrimitiveTopology(&topology);assert(topology==D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
UINT count=1;D3D11_VIEWPORT restored{};context->RSGetViewports(&count,&restored);assert(restored.TopLeftX==2 && restored.Height==18);
desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;ComPtr<ID3D11Texture2D> staging;
assert(SUCCEEDED(device->CreateTexture2D(&desc,nullptr,&staging)));context->CopyResource(staging.Get(),output.Get());
D3D11_MAPPED_SUBRESOURCE mapped{};assert(SUCCEEDED(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped)));
auto* pixel=static_cast<unsigned char*>(mapped.pData)+16*mapped.RowPitch+16*4;
assert(std::abs(int(pixel[0])-128)<=1 && std::abs(int(pixel[1])-64)<=1 && std::abs(int(pixel[2])-32)<=1 && pixel[3]==255);
context->Unmap(staging.Get(),0);enabled=false;assert(!apply(device.Get(),context.Get(),rt));shutdown();
std::cout<<"PASS: actual D3D11 color/darkness shader and render-state restoration (WARP)\n";
}
inline void test_world_huds() {
ImGui::CreateContext();auto& io=ImGui::GetIO();io.DisplaySize={1280,720};io.DeltaTime=.016f;
io.Fonts->AddFontDefault();unsigned char* pixels;int width,height;io.Fonts->GetTexDataAsRGBA32(&pixels,&width,&height);
ImGui::NewFrame();
world::frame frame;frame.valid=true;frame.stamp=GetTickCount64();frame.world_id=1;frame.has_block=true;frame.block={-1,-1,-5};
frame.matrix[0]=frame.matrix[5]=frame.matrix[10]=frame.matrix[15]=1;
frame.local.position={0,1.62f,0};frame.local.held.name="diamond_sword";
for(int i=0;i<4;++i)frame.local.armor[i].name="diamond_helmet";
frame.has_target=true;frame.target.name="Actual player";frame.target.position={0,0,-5};frame.target.head={0,1,-5};
frame.target.health=12;frame.target.max_health=20;frame.target.health_known=true;frame.players.push_back(frame.target);
world::publish(frame);
fps_counter fps;watermark logo;keystrokes keys;cps_counter cps;clock_hud clock;
armor_hud armor;target_hud target;coordinates_hud coordinates;block_outlines outline;better_nametags tags;
module* hud_modules[]={&fps,&logo,&keys,&cps,&clock,&armor,&target,&coordinates,&outline,&tags};
for(auto* m:hud_modules)m->on_render();
anti_afk afk;afk.on_render();assert(afk.hud_size().x>0);afk.on_disable();
block_outlines::draw_selection(frame,frame.block,IM_COL32_WHITE,2,true);
assert(armor.hud_size().y>0 && target.hud_size().y>0);
const float compact_height=target.hud_size().y;
for(auto& setting:target.settings()) if(setting.name=="equipment")setting.bool_value=true;
target.on_render();assert(target.hud_size().y>compact_height);
// Unknown/zero maximum health must never produce invalid geometry.
frame.target.max_health=0;world::publish(frame);target.on_render();
frame.target.health_known=false;world::publish(frame);target.on_render();
zoom magnifier;zoom_effect::magnification=4;
g_menu_open=true;magnifier.on_render();assert(zoom_effect::magnification==1);
g_menu_open=false;zoom_effect::magnification=4;
magnifier.on_disable();assert(zoom_effect::magnification==1);
ImGui::Render();auto* data=ImGui::GetDrawData();assert(data->TotalVtxCount>100);
for(int i=0;i<data->CmdListsCount;++i)for(const auto& v:data->CmdLists[i]->VtxBuffer)assert(std::isfinite(v.pos.x) && std::isfinite(v.pos.y));
world::publish({});ImGui::DestroyContext();
std::cout<<"PASS: actual HUD/card, armor, target, coordinates, nametag and outlined-block geometry\n";
}