diff --git a/src/client.vcxproj b/src/client.vcxproj index f08d205..b91bdea 100644 --- a/src/client.vcxproj +++ b/src/client.vcxproj @@ -160,8 +160,16 @@ + + + + + + + + @@ -171,10 +179,32 @@ + + + + + + + + + + + + + + + + + + + + + + @@ -184,4 +214,7 @@ - \ No newline at end of file + + + + diff --git a/src/client.vcxproj.filters b/src/client.vcxproj.filters index 2499918..e585218 100644 --- a/src/client.vcxproj.filters +++ b/src/client.vcxproj.filters @@ -53,6 +53,13 @@ + + + + + + + @@ -62,14 +69,41 @@ + + + + + + + + + + + + + + + + + + + + + - \ No newline at end of file + + + + + + + diff --git a/src/config/profiles.h b/src/config/profiles.h new file mode 100644 index 0000000..b686b0e --- /dev/null +++ b/src/config/profiles.h @@ -0,0 +1,337 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 settings; + }; + using snapshot = std::map; + + 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 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(&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(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& 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(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 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; } diff --git a/src/config/save_bridge.h b/src/config/save_bridge.h new file mode 100644 index 0000000..89844c9 --- /dev/null +++ b/src/config/save_bridge.h @@ -0,0 +1,7 @@ +#pragma once +#include + +// Modules can request a save without depending on the profile manager or GUI. +namespace config_save { + inline std::function request; +} diff --git a/src/font_data.cc b/src/font_data.cc new file mode 100644 index 0000000..63afb5c --- /dev/null +++ b/src/font_data.cc @@ -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(k_font_size); } diff --git a/src/game/hook.h b/src/game/hook.h index 5e4604a..1c31a69 100644 --- a/src/game/hook.h +++ b/src/game/hook.h @@ -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,14 +28,16 @@ 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: void* target_ = nullptr; }; -} // namespace game \ No newline at end of file +} // namespace game diff --git a/src/game/inventory_tools.h b/src/game/inventory_tools.h new file mode 100644 index 0000000..ac196c1 --- /dev/null +++ b/src/game/inventory_tools.h @@ -0,0 +1,220 @@ +#pragma once +#include "world.h" +#include "../gui/notifications.h" +#include + +namespace inventory_tools { + struct panel {std::string group;std::vector items;}; + struct snapshot {uintptr_t controller=0;uint64_t stamp=0;std::string hover;bool cursor=false,busy=false;world::item held;std::vector panels;}; + enum class action {steal,dump,sort,stop}; + struct request {uintptr_t controller;action operation;std::string group;}; + inline std::atomic enabled{false},include_hotbar{false}; + inline std::atomic delay{75}; + inline std::atomic epoch{0}; + inline std::mutex mutex; + inline snapshot published; + inline std::deque 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(world::get(view)+4*8); + const std::array expected{0x48,0x8b,0x81,0x08,0x01,0,0}; + if(world::get>(getter)!=expected)return -1; + const auto first=world::get(view+0x100),last=world::get(view+0x108); + if(!first || last152*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(model+0x30); + const auto size=world::get(model+0x38);if(!head || size>256)return 0; + auto node=world::get(head); + for(size_t i=0;i(node+0x30),control=world::get(holder+0x10); + if(!control || world::get(control+8)<=0)return 0; + return world::get(holder+8); + } + node=world::get(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 const& items,int index) { + int best=-1; + for(int i=index;i(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;i0; + if(state.panels.empty())return {}; + const int hover_slot=world::get(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=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_slotitems.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=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(indexitems.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 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(sigscan::find(item_signature,true)); + auto_place=reinterpret_cast(sigscan::find(auto_signature,true)); + swap_cursor=reinterpret_cast(sigscan::find(swap_cursor_signature,true)); + place_all=reinterpret_cast(sigscan::find(place_signature,true)); + ready=get_item && swap_cursor && place_all && auto_place && + tick_hook.install("container tick",tick_signature,reinterpret_cast(&tick_detour),reinterpret_cast(&original_tick),true) && tick_hook.set_enabled(true); + } +} diff --git a/src/game/media.h b/src/game/media.h new file mode 100644 index 0000000..4d61260 --- /dev/null +++ b/src/game/media.h @@ -0,0 +1,164 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 rgba;}; + inline std::shared_ptr decode_art(std::vector& bytes) { + using Microsoft::WRL::ComPtr; + if(bytes.empty() || bytes.size()>4*1024*1024)return {}; + ComPtr factory;ComPtr stream;ComPtr decoder; + ComPtr frame;ComPtr scaler;ComPtr 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();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 players; + double position=0,duration=0,rate=1;uint64_t stamp=0; + std::shared_ptr 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 stopping_{false};std::mutex mutex_;std::condition_variable wake_; + snapshot state_;std::string preferred_;std::deque commands_; + template 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 cover;uint64_t art_attempt=0; + while(!stopping_) { + try { + snapshot result;result.message.clear();std::string preferred;std::deque 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 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;} +} diff --git a/src/game/signatures.h b/src/game/signatures.h index cf00308..52605f3 100644 --- a/src/game/signatures.h +++ b/src/game/signatures.h @@ -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 " @@ -38,4 +90,4 @@ namespace sigs { "48 3B 0D ?? ?? ?? ?? " "75 05 " "48 83 C4 38 C3"; -} \ No newline at end of file +} diff --git a/src/game/sigscan.h b/src/game/sigscan.h index 9e5f414..d0b5d2a 100644 --- a/src/game/sigscan.h +++ b/src/game/sigscan.h @@ -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): @@ -115,4 +122,4 @@ namespace sigscan { return instr + instr_len + rel; } -} // namespace sigscan \ No newline at end of file +} // namespace sigscan diff --git a/src/game/viewmodel_math.h b/src/game/viewmodel_math.h new file mode 100644 index 0000000..2abfb8f --- /dev/null +++ b/src/game/viewmodel_math.h @@ -0,0 +1,94 @@ +#pragma once +#include +#include + +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(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(static_cast(actor_context) + 0x28); + if (!render) return nullptr; + auto* screen = *reinterpret_cast(render + 0x18); + if (!screen) return nullptr; + auto** map = *reinterpret_cast(screen + 0x88); + const size_t capacity = *reinterpret_cast(screen + 0x90); + const size_t first = *reinterpret_cast(screen + 0x98); + const size_t size = *reinterpret_cast(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; + } + } + } +} diff --git a/src/game/world.h b/src/game/world.h new file mode 100644 index 0000000..175a89f --- /dev/null +++ b/src/game/world.h @@ -0,0 +1,417 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#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 inline bool read(uintptr_t address, T& out) { + if (address<0x10000 || address>0x7fffffffffff-sizeof(T)) return false; + __try { memcpy(&out,reinterpret_cast(address),sizeof(T));return true; } + __except(EXCEPTION_EXECUTE_HANDLER) {return false;} + } + template inline T get(uintptr_t address) {T out{};read(address,out);return out;} + template inline bool write(uintptr_t address,const T& value) { + if(address<0x10000) return false; + __try {memcpy(reinterpret_cast(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(registry+0x48), bucket_end=get(registry+0x50); + const auto begin=get(registry+0x68), end=get(registry+0x70); + if (!buckets || bucket_end<=buckets || bucket_end-buckets>0x100000 || !begin || end0x100000) return 0; + const size_t count=(bucket_end-buckets)/8, entries=(end-begin)/32; + if (!count || (count&(count-1))) return 0; + auto index=get(buckets+(type&(count-1))*8); + for(size_t step=0;step(entry+8)==type) return get(entry+16); + index=get(entry); + } + return 0; + } + inline uintptr_t component_at(uintptr_t storage,uint32_t entity) { + if(!storage) return 0; + const auto sparse=get(storage+8), end=get(storage+16); + const size_t page=(entity&0x3ffff)>>11; + if(!sparse || end0x100000 || page>=(end-sparse)/8) return 0; + const auto data=get(sparse+page*8); uint32_t packed; + if(!data || !read(data+(entity&0x7ff)*4,packed) || (packed^(entity&0xfffc0000))>0x3fffe) return 0; + const auto first=get(storage+32), last=get(storage+40); + const size_t index=packed&0x3ffff; + if(!first || last0x100000 || index>=(last-first)/4 || get(first+index*4)!=entity) return 0; + const auto fn=get(get(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 indexed{0x48,0x89,0xd0,0x48,0x8b,0x49,0x50}; + if(get(fn)!=0x50498b48 && get>(fn)!=indexed) return 0; + __try {return reinterpret_cast(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.capacity1048576) return {}; + uintptr_t bytes=value.capacity<16 ? address : get(address); + std::string out;out.reserve(size_t(value.size)); + for(size_t i=0;i armor{}; + }; + struct frame { + bool valid=false,has_block=false,has_target=false; + uint64_t stamp=0,world_id=0;actor local,target; + std::vector players; + std::vector 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 published=std::make_shared(); + inline std::mutex frame_mutex,alias_mutex; + inline std::atomic client{0}; + inline std::atomic render_thread{0}; + inline std::atomic collect_players{false},collect_roster{false},collect_xp{false}; + inline std::atomic time_override{-1}; + inline bool ready=false,camera_ready=false,time_ready=false,name_ready=false,fog_ready=false; + inline std::atomic fog_enabled{false}; + inline std::atomic fog_color{0}; + inline std::atomic hide_native_names{false}, alias_enabled{false}; + inline std::shared_ptr alias=std::make_shared("Player"); + inline std::atomic local_actor{0}; + inline thread_local bool rendering=false; + inline void (*after_world)()=nullptr; + inline std::shared_ptr latest() {std::lock_guard lock(frame_mutex);return published;} + inline void publish(frame value) {auto next=std::make_shared(std::move(value));std::lock_guard lock(frame_mutex);published=std::move(next);} + inline std::shared_ptr current_alias() {std::lock_guard lock(alias_mutex);return alias;} + inline void set_alias(std::string name) {auto next=std::make_shared(std::move(name));std::lock_guard 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(stack+8),type=get(counter); + if(!type) return value; + value.name=string(type+0xd8);value.count=get(stack+0x22); + if(!value.count) value.name.clear();return value; + } + inline uintptr_t inventory_item(uintptr_t container,int slot) { + const auto first=get(container+0x1a0),end=get(container+0x1a8); + if(!first || end152*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(player+0x5b8); + const auto container=get(inventory+0xb8); + const int selected=get(inventory+0x10); + const auto first=get(container+0x198),last=get(container+0x1a0); + if(!first || selected<0 || selected>8 || get(inventory+0xb0) || last152*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(sync),end=get(sync+8); + if(items && end>=items+5*8 && end-items<8192) value.name=clean_name(string(get(items+4*8)+16)); + const auto attrs=component(registry,id,"AttributesComponent"); + const auto keys=get(attrs),last=get(attrs+8),values=get(attrs+24),val_end=get(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(keys+i*4)==7) { + value.health=get(values+i*stride+0x7c);value.max_health=get(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(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(component(registry,id,"ActorOwnerComponent")); + value.held=read_item(carried_item(owner)); + } + return true; + } + inline bool read_roster_map(uintptr_t map,std::vector& names) { + const auto head=get(map+8),count=get(map+16); + if(!head || count>1024)return false; + auto node=get(head);std::vector result; + for(size_t i=0;i(node); + } + if(node!=head || get(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& names) { + const auto storage=pool(registry,hash("LevelComponent")); + const auto first=get(storage+32),last=get(storage+40); + if(!first || last-first!=4)return false; + const auto level=get(component_at(storage,get(first))); + return level && read_roster_map(get(level+0x4e0),names); + } + inline bool read_xp_values(uintptr_t attrs,int& level,float& progress) { + const auto keys=get(attrs),end=get(attrs+8); + const auto values=get(attrs+24),last=get(attrs+32); + if(!keys || end<=keys || end-keys>800 || (end-keys)%4 || !values || last(keys+4*i); + if(id==4)l=get(values+136*i+0x70); + if(id==5)p=get(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(ci+0x248),registry=registry_owner+0x30; + const auto entity=get(ci+0x258);out.world_id=registry_owner; + local_actor=get(component(registry,entity,"ActorOwnerComponent")); + const auto renderer=get(ci+0x1c0),camera=get(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(camera+0xf58);out.fov_y=get(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(component(registry,entity,"HitResultComponent")); + const auto hits=get(controller+8),hits_end=get(controller+16); + if(hits && hits_end>=hits+272 && hits_end-hits<272*64) { + const int type=get(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(hits+56);const auto target=get(hits+72); + const auto type_ptr=component(hit_owner+0x30,target,"ActorTypeComponent"); + if(hit_owner==registry_owner && get(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(owners+32),last=get(owners+40); + if(first && last>=first && last-first<=4*16384) for(auto at=first;at(at);if(id==entity || id==0xfffc0000) continue; + const auto type_ptr=component(registry,id,"ActorTypeComponent");if(get(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(_ReturnAddress())-reinterpret_cast(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 returned; + returned=current_alias();return returned.get(); + } + if(self!=local_actor.load() && hide_native_names) { + const auto reg=get(self+16);const auto id=get(self+24); + if(get(component(reg,id,"ActorTypeComponent"))==319) {static const std::string empty;return ∅} + } + } + return original_name(self); + } + struct player_look_lock { + bool held=false;uintptr_t owner=0;uint32_t entity=0; + std::array rotation{};std::array 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 r;std::array 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 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 pending_orbit_yaw{0},pending_orbit_pitch{0}; + inline void accumulate(std::atomic& 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(ci+0x248),registry=owner+0x30; + const auto id=get(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 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(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 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(&update_detour),reinterpret_cast(&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(&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(active),&image_base,nullptr); + if(function) get_camera=reinterpret_cast(image_base+function->BeginAddress); + } + camera_ready=get_camera && camera_hook.install("camera matrices",camera_matrix_signature,reinterpret_cast(&camera_detour),reinterpret_cast(&original_camera),true) && camera_hook.set_enabled(true); + perspective_ready=perspective_hook.install("view perspective",perspective_signature,reinterpret_cast(&perspective_detour),reinterpret_cast(&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(&time_detour),reinterpret_cast(&original_time),true) && time_hook.set_enabled(true); + name_ready=name_hook.install("visual player name",name_signature,reinterpret_cast(&name_detour),reinterpret_cast(&original_name),true) && name_hook.set_enabled(true); + fog_ready=fog_hook.install("dimension fog color",fog_signature,reinterpret_cast(&fog_detour),reinterpret_cast(&original_fog),true) && fog_hook.set_enabled(true); + game::log(std::string("world modules: ")+(ready ? "ready" : "unavailable")); + } +} diff --git a/src/game/world_filter.h b/src/game/world_filter.h new file mode 100644 index 0000000..969a41f --- /dev/null +++ b/src/game/world_filter.h @@ -0,0 +1,99 @@ +#pragma once +#include +#include +#include +#include +#include +#include "world.h" +#pragma comment(lib,"d3dcompiler.lib") +#pragma comment(lib,"d3d11.lib") + +namespace world_filter { + using Microsoft::WRL::ComPtr; + inline std::atomic enabled{false}; + inline std::atomic tint{0xffffffff}; + inline std::atomic brightness{1}; + inline ComPtr vs; + inline ComPtr ps; + inline ComPtr sampler; + inline ComPtr raster; + inline ComPtr depth; + inline ComPtr constants; + inline ComPtr copy; + inline ComPtr 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 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 resource;target->GetResource(&resource); + ComPtr 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,©))) 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 old_vs;ComPtr old_ps;ComPtr old_gs; + ComPtr old_hs;ComPtr old_ds; + ComPtr old_cb;ComPtr old_srv;ComPtr old_sampler; + ComPtr layout;ComPtr old_rs;ComPtr old_depth; + ComPtr blend;ComPtr dsv; + ID3D11RenderTargetView* targets[8]{};context->OMGetRenderTargets(8,targets,&dsv); + ID3D11ClassInstance* classes[5][256]{};UINT class_count[5]={256,256,256,256,256}; + ComPtr 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;iRelease(); + 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;} +} diff --git a/src/game/world_math.h b/src/game/world_math.h new file mode 100644 index 0000000..5cb54c7 --- /dev/null +++ b/src/game/world_math.h @@ -0,0 +1,71 @@ +#pragma once +#include +#include +#include +#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[i]); + if (c==0xc2 && i+2(name[i+1])==0xa7) {i+=2;continue;} + if (c==0xa7 && i+1=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; + } +} diff --git a/src/gui/clickgui.h b/src/gui/clickgui.h index 417e17a..e82cece 100644 --- a/src/gui/clickgui.h +++ b/src/gui/clickgui.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include #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;xAddLine({x,0},{x,io.DisplaySize.y},color); + for(float y=0;yAddLine({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( @@ -388,4 +501,4 @@ private: inline clickgui& gui() { static clickgui instance; return instance; -} \ No newline at end of file +} diff --git a/src/gui/fonts.h b/src/gui/fonts.h index 76bc3e9..eca003a 100644 --- a/src/gui/fonts.h +++ b/src/gui/fonts.h @@ -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 @@ -71,4 +72,4 @@ namespace fonts { io.FontDefault = body; } -} // namespace fonts \ No newline at end of file +} // namespace fonts diff --git a/src/gui/hud_card.h b/src/gui/hud_card.h new file mode 100644 index 0000000..a6a6ac9 --- /dev/null +++ b/src/gui/hud_card.h @@ -0,0 +1,34 @@ +#pragma once +#include +#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); + } +} diff --git a/src/gui/hud_editor.h b/src/gui/hud_editor.h new file mode 100644 index 0000000..3eef874 --- /dev/null +++ b/src/gui/hud_editor.h @@ -0,0 +1,23 @@ +#pragma once +#include +#include +#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); + } + }; +} diff --git a/src/gui/notifications.h b/src/gui/notifications.h new file mode 100644 index 0000000..5fe0bf5 --- /dev/null +++ b/src/gui/notifications.h @@ -0,0 +1,71 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include "fonts.h" +#include "theme.h" + +namespace notifications { + enum class kind { info,success,warning,error }; + inline double now() { return std::chrono::duration(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 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; + } + } +} diff --git a/src/input.h b/src/input.h index 8052e53..74cc270 100644 --- a/src/input.h +++ b/src/input.h @@ -1,6 +1,7 @@ #pragma once #include #include +#include #include "MinHook.h" #include "imgui.h" #include "imgui_impl_win32.h" @@ -11,13 +12,67 @@ inline std::atomic g_menu_open{ false }; namespace input { + inline constexpr ULONG_PTR sprint_input_tag = 0x414d535052494e54ull; + inline std::array, 256> physical_keys{}; + inline std::atomic activity_sequence{0}; + inline std::atomic 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{nullptr}; + inline std::atomic focus_lost_handler{nullptr}; + inline std::atomic freelook_enabled{false}, freelook_supported{false}, in_world{false}; + inline std::atomic freelook_key{VK_LMENU}, look_dx{0}, look_dy{0}; + inline std::atomic 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(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(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(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(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; } @@ -138,4 +209,4 @@ namespace input { } } -} // namespace input \ No newline at end of file +} // namespace input diff --git a/src/main.cc b/src/main.cc index ac1f9ce..5e02466 100644 --- a/src/main.cc +++ b/src/main.cc @@ -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()->set_enabled(true); modules().add()->set_enabled(true); @@ -125,6 +152,27 @@ DWORD WINAPI main_thread(LPVOID) { modules().add(); modules().add(); modules().add(); // scans for its signature here; can take a couple of seconds + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); + modules().add(); 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(); @@ -162,4 +214,4 @@ BOOL APIENTRY DllMain(HMODULE hmod, DWORD reason, LPVOID) { CreateThread(nullptr, 0, main_thread, nullptr, 0, nullptr); } return TRUE; -} \ No newline at end of file +} diff --git a/src/modules/anti_afk.h b/src/modules/anti_afk.h new file mode 100644 index 0000000..dc442c1 --- /dev/null +++ b/src/modules/anti_afk.h @@ -0,0 +1,74 @@ +#pragma once +#include "text_hud.h" +#include "anti_afk_engine.h" +#include "../input.h" +#include "../game/world.h" +#include +#include + +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); + } +}; diff --git a/src/modules/anti_afk_engine.h b/src/modules/anti_afk_engine.h new file mode 100644 index 0000000..94ab2f0 --- /dev/null +++ b/src/modules/anti_afk_engine.h @@ -0,0 +1,45 @@ +#pragma once +#include +#include +#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 void stop(Physical physical,Send send) { + jump_.update(false,0,physical,send);move_.update(false,0,physical,send);pulsing_=false; + } + template 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(now0 && 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(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; + }; +} diff --git a/src/modules/clock.h b/src/modules/clock.h new file mode 100644 index 0000000..29b6cc6 --- /dev/null +++ b/src/modules/clock.h @@ -0,0 +1,28 @@ +#pragma once +#include +#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_; +}; diff --git a/src/modules/cps_counter.h b/src/modules/cps_counter.h new file mode 100644 index 0000000..846b966 --- /dev/null +++ b/src/modules/cps_counter.h @@ -0,0 +1,45 @@ +#pragma once +#include +#include +#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 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"; + } +}; diff --git a/src/modules/crosshair.h b/src/modules/crosshair.h index 4c6ced3..6d09061 100644 --- a/src/modules/crosshair.h +++ b/src/modules/crosshair.h @@ -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(&native_detour),reinterpret_cast(&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()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(idx)); + dl->PrimWriteIdx(static_cast(idx+1)); + dl->PrimWriteIdx(static_cast(idx+2)); + dl->PrimWriteIdx(static_cast(idx)); + dl->PrimWriteIdx(static_cast(idx+2)); + dl->PrimWriteIdx(static_cast(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; -}; \ No newline at end of file + static std::vector 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 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; +}; diff --git a/src/modules/crosshair_animation.h b/src/modules/crosshair_animation.h new file mode 100644 index 0000000..3b9087c --- /dev/null +++ b/src/modules/crosshair_animation.h @@ -0,0 +1,41 @@ +#pragma once +#include +#include + +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(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(phase),easing)*6.283185307179586f; + } +} diff --git a/src/modules/fov_changer.h b/src/modules/fov_changer.h new file mode 100644 index 0000000..339d751 --- /dev/null +++ b/src/modules/fov_changer.h @@ -0,0 +1,67 @@ +#pragma once +#include +#include +#include +#include "module.h" +#include "../game/hook.h" +#include "../game/signatures.h" + +namespace zoom_effect { + inline std::atomic supported{false}; + inline std::atomic 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(&detour), reinterpret_cast(&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 override_degrees_{0.f}; + game::game_hook hook_; +}; diff --git a/src/modules/fps_counter.h b/src/modules/fps_counter.h index a201057..c0affce 100644 --- a/src/modules/fps_counter.h +++ b/src/modules/fps_counter.h @@ -1,66 +1,13 @@ #pragma once #include -#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); - } - - 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); + char value[24]; snprintf(value, sizeof(value), "%.0f", ImGui::GetIO().Framerate); + text_ = value; draw_text(); } - -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; -}; \ No newline at end of file +}; diff --git a/src/modules/glint_changer.h b/src/modules/glint_changer.h new file mode 100644 index 0000000..d6f79d4 --- /dev/null +++ b/src/modules/glint_changer.h @@ -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 enabled{false}; + inline std::atomic 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(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(&glint_effect::detour),reinterpret_cast(&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; +}; diff --git a/src/modules/inventory_tools.h b/src/modules/inventory_tools.h new file mode 100644 index 0000000..09f158f --- /dev/null +++ b/src/modules/inventory_tools.h @@ -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 left_owned_{false},middle_owned_{false}; + inline static std::atomic 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+312 || 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; + } +}; diff --git a/src/modules/keystrokes.h b/src/modules/keystrokes.h index 8e31c74..afa7cbe 100644 --- a/src/modules/keystrokes.h +++ b/src/modules/keystrokes.h @@ -1,13 +1,13 @@ #pragma once #include -#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,17 +57,17 @@ 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)), theme::u32(text), label); } -}; \ No newline at end of file +}; diff --git a/src/modules/macro.h b/src/modules/macro.h index 02eefd6..92bacb4 100644 --- a/src/modules/macro.h +++ b/src/modules/macro.h @@ -1,295 +1,240 @@ #pragma once #include #include -#include -#include -#include #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"); } - + 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."); + } + 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 (g_menu_open) { - if (mode_ != mode::idle) stop("menu opened"); + 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; + } + 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(); + } + if(!engine_.running()) { + for(int i=1;i<=4;++i) if(edge(i)) capture(static_cast(i)); + } + sync_keys(); + if(pending_!=pending::none) { + if(pending_at_==0) pending_at_=time+capture_delay_->float_value; + if(notifications_->bool_value && timefloat_value)); + } + 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); + } + } + 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();} + } +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); + } + 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; + } + 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"); + } + 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 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_scoreint_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; } - handle_hotkeys(); - if (mode_ == mode::recording) record_frame(); - else if (mode_ == mode::playing) play_frame(); - draw_status(); + save(); } - -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 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(); + 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; } - if (play && !play_key_was_down_) { - if (mode_ == mode::playing) stop("stopped"); - else if (mode_ == mode::idle) start_playing(); + 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 (stp && !stop_key_was_down_) stop("stopped"); - - rec_key_was_down_ = rec; - play_key_was_down_ = play; - stop_key_was_down_ = stp; + 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 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 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 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 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 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; + 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"); } - - // ---------------- 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; + 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); } - - 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; + 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; } - - 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: - return false; - } - } - - 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)); - } - - 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; - } - SendInput(1, &in, sizeof(INPUT)); - } - - 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)); - } - - 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; - } - } - - // ---------------- 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(); - } - 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(); - } - else if (now() < status_until_) { - snprintf(buf, sizeof(buf), "%s", status_); - } - else { - snprintf(buf, sizeof(buf), "Macro | F9 record F10 play End stop (%d events)", (int)events_.size()); - } - - 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); - } -}; \ No newline at end of file +}; diff --git a/src/modules/module.h b/src/modules/module.h index c3df6a9..83d3a70 100644 --- a/src/modules/module.h +++ b/src/modules/module.h @@ -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 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 modes, int selected = 0) { setting& s = settings_.emplace_back(); s.name = std::move(name); @@ -130,4 +148,4 @@ private: bool enabled_ = false; bool key_was_down_ = false; std::deque settings_; -}; \ No newline at end of file +}; diff --git a/src/modules/module_manager.h b/src/modules/module_manager.h index 13d8e9a..9035bc0 100644 --- a/src/modules/module_manager.h +++ b/src/modules/module_manager.h @@ -15,7 +15,14 @@ public: const std::vector>& 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_) @@ -39,4 +46,4 @@ private: inline module_manager& modules() { static module_manager instance; return instance; -} \ No newline at end of file +} diff --git a/src/modules/music_player.h b/src/modules/music_player.h new file mode 100644 index 0000000..3b55290 --- /dev/null +++ b/src/modules/music_player.h @@ -0,0 +1,96 @@ +#pragma once +#include "text_hud.h" +#include "../input.h" +#include "../game/media.h" +#include + +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 uploaded_; + Microsoft::WRL::ComPtr image_; + void upload(std::shared_ptr 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 texture; + if(SUCCEEDED(media_art::device->CreateTexture2D(&desc,&data,&texture)))media_art::device->CreateShaderResourceView(texture.Get(),nullptr,&image_); + } +}; diff --git a/src/modules/server_hud.h b/src/modules/server_hud.h new file mode 100644 index 0000000..bff4d8d --- /dev/null +++ b/src/modules/server_hud.h @@ -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;iPushClipRect({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}; +}; diff --git a/src/modules/setting.h b/src/modules/setting.h index a371042..acd8f88 100644 --- a/src/modules/setting.h +++ b/src/modules/setting.h @@ -1,16 +1,20 @@ #pragma once #include #include +#include -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 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 modes; float color[4] = { 1.f, 1.f, 1.f, 1.f }; -}; \ No newline at end of file +}; diff --git a/src/modules/sprint_latch.h b/src/modules/sprint_latch.h new file mode 100644 index 0000000..41af347 --- /dev/null +++ b/src/modules/sprint_latch.h @@ -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 + 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; +}; diff --git a/src/modules/text_hud.h b/src/modules/text_hud.h new file mode 100644 index 0000000..37c15c4 --- /dev/null +++ b/src/modules/text_hud.h @@ -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_; +}; diff --git a/src/modules/toggle_sprint.h b/src/modules/toggle_sprint.h new file mode 100644 index 0000000..24ee372 --- /dev/null +++ b/src/modules/toggle_sprint.h @@ -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(vk); + event.ki.wScan = static_cast(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); + } +}; diff --git a/src/modules/trade_io.h b/src/modules/trade_io.h new file mode 100644 index 0000000..ef598d7 --- /dev/null +++ b/src/modules/trade_io.h @@ -0,0 +1,63 @@ +#pragma once +#include +#include +#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& 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(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 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; + } +}; diff --git a/src/modules/trade_profile.h b/src/modules/trade_profile.h new file mode 100644 index 0000000..b59562b --- /dev/null +++ b/src/modules/trade_profile.h @@ -0,0 +1,62 @@ +#pragma once +#include +#include +#include +#include +#include +#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(&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; + } +} diff --git a/src/modules/viewmodel.h b/src/modules/viewmodel.h new file mode 100644 index 0000000..539a239 --- /dev/null +++ b/src/modules/viewmodel.h @@ -0,0 +1,150 @@ +#pragma once +#include +#include +#include +#include +#include +#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(&bob_detour), + reinterpret_cast(&original_bob_), true)) + set_description("unavailable: hand transform signature missing or ambiguous"); + draw_hook_.install("render_hands", sigs::render_hands, reinterpret_cast(&draw_detour), + reinterpret_cast(&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(&offhand_detour), reinterpret_cast(&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 frame_{1}; + setting* settings_[12]{}; + setting* separate_ = nullptr; + std::array, 12> values_{}; + std::atomic 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); + } +}; diff --git a/src/modules/villager_trade.h b/src/modules/villager_trade.h new file mode 100644 index 0000000..61b8d42 --- /dev/null +++ b/src/modules/villager_trade.h @@ -0,0 +1,108 @@ +#pragma once +#include +#include +#include + +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=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; + }; +} diff --git a/src/modules/watermark.h b/src/modules/watermark.h index af2c457..ad2f832 100644 --- a/src/modules/watermark.h +++ b/src/modules/watermark.h @@ -1,66 +1,13 @@ #pragma once #include -#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); - } - - 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); + char value[24]; snprintf(value, sizeof(value), "%.0f fps", ImGui::GetIO().Framerate); + text_ = value; draw_text(); } - -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; -}; \ No newline at end of file +}; diff --git a/src/modules/world_modules.h b/src/modules/world_modules.h new file mode 100644 index 0000000..5304c03 --- /dev/null +++ b/src/modules/world_modules.h @@ -0,0 +1,258 @@ +#pragma once +#include +#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<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 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> 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;ibool_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_; +}; diff --git a/src/modules/zoom.h b/src/modules/zoom.h new file mode 100644 index 0000000..0f952a0 --- /dev/null +++ b/src/modules/zoom.h @@ -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; +}; diff --git a/tests/PROFILES.md b/tests/PROFILES.md new file mode 100644 index 0000000..438a741 --- /dev/null +++ b/tests/PROFILES.md @@ -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. diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..65a34fe --- /dev/null +++ b/tests/README.md @@ -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. diff --git a/tests/VILLAGER_MACRO.md b/tests/VILLAGER_MACRO.md new file mode 100644 index 0000000..febfa70 --- /dev/null +++ b/tests/VILLAGER_MACRO.md @@ -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. diff --git a/tests/WORLD_MODULES.md b/tests/WORLD_MODULES.md new file mode 100644 index 0000000..6fcbd92 --- /dev/null +++ b/tests/WORLD_MODULES.md @@ -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. diff --git a/tests/anti_afk_tests.h b/tests/anti_afk_tests.h new file mode 100644 index 0000000..7100534 --- /dev/null +++ b/tests/anti_afk_tests.h @@ -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> 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(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"; +} diff --git a/tests/fov_changer_test.cc b/tests/fov_changer_test.cc new file mode 100644 index 0000000..d60c1e8 --- /dev/null +++ b/tests/fov_changer_test.cc @@ -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 +#include +#include +#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(static_cast(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(&hands_callback); + write_code(hands_fixture + hands_callback_offset, reinterpret_cast(&callback), sizeof(callback)); + callback = reinterpret_cast(&offhand_callback); + write_code(offhand_fixture + offhand_callback_offset, reinterpret_cast(&callback), sizeof(callback)); + const int32_t displacement = static_cast(offhand_fixture - (offhand_call_fixture + offhand_call_offset + 18)); + write_code(offhand_call_fixture + offhand_call_offset + 14, + reinterpret_cast(&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(context+0x28)=render; + *reinterpret_cast(render+0x18)=screen; + *reinterpret_cast(screen+0x88)=map; + *reinterpret_cast(screen+0x90)=1; + *reinterpret_cast(screen+0xa0)=1; + void* vtable[0x100]{}; void* client=vtable; + *reinterpret_cast(renderer+0x170)=&client; + viewmodel module; + using draw_fn=void(__fastcall*)(void*,void*,void*,unsigned char); + auto draw=reinterpret_cast(static_cast(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(static_cast(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> 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(1) && b==reinterpret_cast(2) && + c==reinterpret_cast(3) && d==reinterpret_cast(4)); + ++native_crosshair_draws; +} +static void test_crosshair_render() { + const uintptr_t callback=reinterpret_cast(&native_crosshair_callback); + write_code(native_crosshair_fixture+native_crosshair_callback_offset, + reinterpret_cast(&callback),sizeof(callback)); + using native_draw_fn=void(__fastcall*)(void*,void*,void*,void*); + auto native_draw=reinterpret_cast(static_cast(native_crosshair_fixture)); + auto draw_native=[&] { native_draw(reinterpret_cast(1),reinterpret_cast(2), + reinterpret_cast(3),reinterpret_cast(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(indexVtxBuffer.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> 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(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(static_cast(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(renderer + 0x1188) = context; + *reinterpret_cast(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::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::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"; +} + diff --git a/tests/fov_changer_test.vcxproj b/tests/fov_changer_test.vcxproj new file mode 100644 index 0000000..526a82f --- /dev/null +++ b/tests/fov_changer_test.vcxproj @@ -0,0 +1,27 @@ + + + + Debugx64 + + 10.0 + + Applicationv143 + + $(ProjectDir)..\build\tests\$(OutDir)obj\ + + stdcpp17Level3NDEBUG$(ProjectDir)..\vendor\minhook\include;$(ProjectDir)..\vendor\imgui;$(ProjectDir)..\vendor\imgui\backends + user32.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + diff --git a/tests/hud_grid_tests.h b/tests/hud_grid_tests.h new file mode 100644 index 0000000..7d2b215 --- /dev/null +++ b/tests/hud_grid_tests.h @@ -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"; +} diff --git a/tests/inventory_tests.h b/tests/inventory_tests.h new file mode 100644 index 0000000..76579bf --- /dev/null +++ b/tests/inventory_tests.h @@ -0,0 +1,100 @@ +#pragma once +#include "../src/game/inventory_tools.h" + +namespace inventory_test { + inline std::vector 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 transferred_groups; + struct type {unsigned char padding[0xd8]{};std::string name;}; + inline type native_type; + inline uintptr_t counter=reinterpret_cast(&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(stack+8)=reinterpret_cast(&counter); + stack[0x22]=static_cast(value.count);return reinterpret_cast(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(controller+0x12c0)=1; + const auto owner=reinterpret_cast(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({"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"; +} diff --git a/tests/media_glint_tests.h b/tests/media_glint_tests.h new file mode 100644 index 0000000..c016e34 --- /dev/null +++ b/tests/media_glint_tests.h @@ -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 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 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(context); + *reinterpret_cast(context+0x30)=reinterpret_cast(entries); + *reinterpret_cast(context+0x3a)=2; + *reinterpret_cast(entries+16)=reinterpret_cast(definition); + *reinterpret_cast(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(&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(definition+0x28)=123; + glint_effect::detour(ctx,reinterpret_cast(&index),&source);assert(glint_forwarded==&source && glint_received[0]==.2f); + *reinterpret_cast(definition+0x28)=glint_effect::color_name; + index=2;assert(!glint_effect::is_color(ctx,reinterpret_cast(&index),reinterpret_cast(&source))); + index=1;source.count=2;assert(!glint_effect::is_color(ctx,reinterpret_cast(&index),reinterpret_cast(&source))); + source.count=1;glint_effect::enabled=false;glint_effect::detour(ctx,reinterpret_cast(&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 art_device;Microsoft::WRL::ComPtr 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().yTotalVtxCount>100); + for(int i=0;iCmdListsCount;++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()(); 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_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_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"; +} diff --git a/tests/separate_hand_fixture.h b/tests/separate_hand_fixture.h new file mode 100644 index 0000000..01ee4a9 --- /dev/null +++ b/tests/separate_hand_fixture.h @@ -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; diff --git a/tests/server_hud_tests.h b/tests/server_hud_tests.h new file mode 100644 index 0000000..9191e26 --- /dev/null +++ b/tests/server_hud_tests.h @@ -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::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 names; + assert(world::read_roster_map(uintptr_t(map),names) && names==std::vector({"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;iCmdListsCount;++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"; +} diff --git a/tests/viewmodel_fixture.h b/tests/viewmodel_fixture.h new file mode 100644 index 0000000..fd28500 --- /dev/null +++ b/tests/viewmodel_fixture.h @@ -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}; diff --git a/tests/world_tests.h b/tests/world_tests.h new file mode 100644 index 0000000..69de6b2 --- /dev/null +++ b/tests/world_tests.h @@ -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 ℜ} + +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 player_rotation{15,70,14,69}; + std::array 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(code)};uint32_t sparse[2048];std::fill(sparse,sparse+2048,0xffffffffu); + uint32_t packed[]={0x40003};sparse[3]=0x40000;uintptr_t pages[]={reinterpret_cast(sparse)}; + uintptr_t payload[128]{};payload[0]=0x12345678;uintptr_t payload_pages[]={reinterpret_cast(payload)}; + uintptr_t storage[16]{};storage[0]=reinterpret_cast(vt);storage[1]=reinterpret_cast(pages);storage[2]=storage[1]+8; + storage[4]=reinterpret_cast(packed);storage[5]=storage[4]+4;storage[10]=reinterpret_cast(payload_pages); + assert(component_at(reinterpret_cast(storage),0x40003)==reinterpret_cast(payload)); + assert(!component_at(reinterpret_cast(storage),3));assert(!component_at(reinterpret_cast(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(storage),0x40003)==reinterpret_cast(payload)); + assert(!component_at(reinterpret_cast(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 device;ComPtr 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 output;ComPtr 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 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(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;iCmdListsCount;++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"; +}