added a SHIT ton of modules

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

No files matched your search

+10 -7
View File
@@ -13,11 +13,12 @@ namespace game {
class game_hook {
public:
// creates the hook DISABLED; returns false if the signature is empty or not found
bool install(const char* name, const char* signature, void* detour, void** original) {
bool install(const char* name, const char* signature, void* detour, void** original,
bool require_unique = false) {
if (!signature || !*signature) { log(std::string(name) + ": no signature set"); return false; }
uint8_t* addr = sigscan::find(signature);
if (!addr) { log(std::string(name) + ": signature not found (game updated?)"); return false; }
uint8_t* addr = sigscan::find(signature, require_unique);
if (!addr) { log(std::string(name) + ": signature missing or ambiguous (game updated?)"); return false; }
if (MH_CreateHook(addr, detour, original) != MH_OK) { log(std::string(name) + ": MH_CreateHook failed"); return false; }
@@ -27,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
} // namespace game
+220
View File
@@ -0,0 +1,220 @@
#pragma once
#include "world.h"
#include "../gui/notifications.h"
#include <deque>
namespace inventory_tools {
struct panel {std::string group;std::vector<world::item> items;};
struct snapshot {uintptr_t controller=0;uint64_t stamp=0;std::string hover;bool cursor=false,busy=false;world::item held;std::vector<panel> panels;};
enum class action {steal,dump,sort,stop};
struct request {uintptr_t controller;action operation;std::string group;};
inline std::atomic<bool> enabled{false},include_hotbar{false};
inline std::atomic<int> delay{75};
inline std::atomic<uint64_t> epoch{0};
inline std::mutex mutex;
inline snapshot published;
inline std::deque<request> requests;
inline bool ready=false;
using tick_fn=uint32_t(__fastcall*)(uintptr_t);
using item_fn=uintptr_t(__fastcall*)(uintptr_t,const std::string*,int);
using slot_fn=void(__fastcall*)(uintptr_t,const std::string*,int);
using auto_fn=void(__fastcall*)(uintptr_t,int,const std::string*,int);
inline tick_fn original_tick=nullptr;
inline item_fn get_item=nullptr;inline slot_fn swap_cursor=nullptr,place_all=nullptr;inline auto_fn auto_place=nullptr;
inline game::game_hook tick_hook;
inline snapshot latest(){std::lock_guard lock(mutex);return published;}
inline bool fresh(snapshot const& state){return state.controller && GetTickCount64()-state.stamp<150;}
inline void queue(action operation,std::string group="") {
std::lock_guard lock(mutex);
if(fresh(published) && requests.size()<4)requests.push_back({published.controller,operation,std::move(group)});
}
inline void reset(){++epoch;std::lock_guard lock(mutex);requests.clear();published={};}
inline bool playing_ui() {
// Bedrock can draw its own UI cursor while the Windows cursor is hidden.
// The live container tick/snapshot establishes whether a screen is open.
return enabled && !g_menu_open && is_game_focused();
}
inline int view_count(uintptr_t view) {
const auto getter=world::get<uintptr_t>(world::get<uintptr_t>(view)+4*8);
const std::array<uint8_t,7> expected{0x48,0x8b,0x81,0x08,0x01,0,0};
if(world::get<std::array<uint8_t,7>>(getter)!=expected)return -1;
const auto first=world::get<uintptr_t>(view+0x100),last=world::get<uintptr_t>(view+0x108);
if(!first || last<first || last-first>152*256 || (last-first)%152)return -1;
return int((last-first)/152);
}
inline uintptr_t group_view(uintptr_t model,std::string const& group) {
const auto head=world::get<uintptr_t>(model+0x30);
const auto size=world::get<uintptr_t>(model+0x38);if(!head || size>256)return 0;
auto node=world::get<uintptr_t>(head);
for(size_t i=0;i<size && node && node!=head;++i) {
if(world::string(node+0x10)==group) {
const auto holder=world::get<uintptr_t>(node+0x30),control=world::get<uintptr_t>(holder+0x10);
if(!control || world::get<int>(control+8)<=0)return 0;
return world::get<uintptr_t>(holder+8);
}
node=world::get<uintptr_t>(node);
}
return 0;
}
inline int guarded_count(uintptr_t model,const std::string* group){return view_count(group_view(model,*group));}
inline uintptr_t guarded_item(uintptr_t model,const std::string* group,int slot){__try{return get_item(model,group,slot);}__except(EXCEPTION_EXECUTE_HANDLER){return 0;}}
inline bool guarded_action(slot_fn fn,uintptr_t controller,const std::string* group,int slot) {
__try{fn(controller,group,slot);return true;}__except(EXCEPTION_EXECUTE_HANDLER){return false;}
}
inline const panel* find(snapshot const& state,std::string const& group){for(auto const& panel:state.panels)if(panel.group==group)return &panel;return nullptr;}
inline int next_minimum(std::vector<world::item> const& items,int index) {
int best=-1;
for(int i=index;i<int(items.size());++i)if(!items[i].name.empty() && (best<0 || items[i].name<items[best].name))best=i;
return best;
}
inline snapshot capture(uintptr_t controller) {
snapshot state;state.controller=controller;state.stamp=GetTickCount64();state.hover=world::string(controller+0x1098);
const auto model=world::get<uintptr_t>(controller+0x12c0);if(!model)return {};
for(const char* name:{"container_items","inventory_items","hotbar_items"}) {
const std::string group=name;const int count=guarded_count(model,&group);
if(count<=0 || count>54)continue;
panel panel;panel.group=group;
for(int i=0;i<count;++i)panel.items.push_back(world::read_item(guarded_item(model,&group,i)));
state.panels.push_back(std::move(panel));
}
const std::string cursor="cursor_items";
const int cursor_count=guarded_count(model,&cursor);
state.held=world::read_item(guarded_item(model,&cursor,0));
state.cursor=cursor_count!=1 || state.held.count>0;
if(state.panels.empty())return {};
const int hover_slot=world::get<int>(controller+0x10b8);
const auto* hovered=find(state,state.hover);
if(!hovered || hover_slot<0 || hover_slot>=int(hovered->items.size()))state.hover.clear();
return state;
}
struct engine {
uintptr_t controller=0;action operation=action::stop;std::string group;int index=0;
uint64_t due=0,wait_stamp=0;bool hotbar=false,awaiting=false;
std::string wait_group,wait_name;int wait_slot=0,wait_count=0;
enum class phase {idle,pickup,swap,putback,recover};
phase sort_phase=phase::idle;int sort_source=0,sort_destination=0;world::item sort_taken,sort_displaced;
uint64_t phase_stamp=0;
static bool same(world::item const& a,world::item const& b){return a.name==b.name && a.count==b.count;}
enum class stop_reason {none,completed,focus,controller,cursor,timeout,action_failed,requested,disabled};
stop_reason last_stop=stop_reason::none;
void cancel(stop_reason reason=stop_reason::completed){if(active())last_stop=reason;sort_phase=phase::idle;controller=0;operation=action::stop;group.clear();index=0;awaiting=false;}
void start(request const& request){last_stop=stop_reason::none;sort_phase=phase::idle;controller=request.controller;operation=request.operation;group=request.group;index=0;due=0;hotbar=false;awaiting=false;}
bool active() const{return controller && operation!=action::stop;}
void step(snapshot const& state,uint64_t now,bool eligible=playing_ui()) {
if(!active())return;
if(state.controller!=controller || !eligible){cancel(state.controller!=controller ? stop_reason::controller : stop_reason::focus);return;}
if(sort_phase!=phase::idle) {
if(now<due)return;
const auto* panel=find(state,group);
if(!panel || sort_source>=int(panel->items.size()) || sort_destination>=int(panel->items.size())){cancel();return;}
const bool timeout=now-phase_stamp>1500;
if(sort_phase==phase::pickup) {
if(same(state.held,sort_taken) && panel->items[sort_source].count==0) {
if(!guarded_action(place_all,controller,&group,sort_destination)){cancel(stop_reason::action_failed);notifications::push("Sorting stopped","The swap action failed.",notifications::kind::warning);return;}
sort_phase=phase::swap;phase_stamp=now;due=now+std::clamp(delay.load(),30,500);
} else if(timeout){cancel(stop_reason::timeout);notifications::push("Sorting stopped","Pick-up was not confirmed.",notifications::kind::warning);}
} else if(sort_phase==phase::swap) {
if(same(panel->items[sort_destination],sort_taken) && same(state.held,sort_displaced)) {
if(state.held.count) {
if(!guarded_action(place_all,controller,&group,sort_source)){cancel();return;}
sort_phase=phase::putback;phase_stamp=now;due=now+std::clamp(delay.load(),30,500);
} else {sort_phase=phase::idle;++index;}
} else if(timeout) {
if(same(state.held,sort_taken) && panel->items[sort_source].count==0) {
guarded_action(place_all,controller,&group,sort_source);sort_phase=phase::recover;phase_stamp=now;
} else {cancel();notifications::push("Sorting stopped","Place the held stack before trying again.",notifications::kind::warning);}
}
} else if(!state.cursor && same(panel->items[sort_source],sort_phase==phase::recover ? sort_taken : sort_displaced)) {
if(sort_phase==phase::recover){cancel();notifications::push("Sorting stopped","The swap was declined; the stack was returned.",notifications::kind::warning);}
else {sort_phase=phase::idle;++index;}
} else if(timeout){cancel(stop_reason::timeout);notifications::push("Sorting stopped","Place the held stack before trying again.",notifications::kind::warning);}
return;
}
if(state.cursor){cancel(stop_reason::cursor);return;}
if(awaiting) {
const auto* panel=find(state,wait_group);
const bool unchanged=panel && wait_slot<int(panel->items.size()) && panel->items[wait_slot].name==wait_name && panel->items[wait_slot].count>=wait_count;
if(unchanged) {
if(now-wait_stamp>750){cancel();notifications::push("Transfer stopped","The destination may be full, or the server declined the transfer.",notifications::kind::warning);}
return;
}
awaiting=false;
}
if(now<due)return;due=now+std::clamp(delay.load(),30,500);
if(operation!=action::sort) {
group=operation==action::steal ? "container_items" : hotbar ? "hotbar_items" : "inventory_items";
const auto* source=find(state,group);
if(!find(state,"container_items")){cancel();return;}
if(!source || index>=int(source->items.size())) {
if(operation==action::dump && !hotbar && include_hotbar){hotbar=true;index=0;return;}
cancel();return;
}
const int slot=index++;const auto& item=source->items[slot];if(item.name.empty())return;
auto_place(controller,item.count,&group,slot);
awaiting=true;wait_group=group;wait_slot=slot;wait_count=item.count;wait_name=item.name;wait_stamp=now;
} else {
const auto* source=find(state,group);if(!source){cancel();return;}
while(index<int(source->items.size())) {
const int best=next_minimum(source->items,index);
if(best<0){cancel();return;}
if(best==index || source->items[best].name==source->items[index].name){++index;continue;}
// Full pickup and placement are separate native actions.
// Taking onto an occupied cursor cannot replace an unlike stack.
sort_source=best;sort_destination=index;sort_taken=source->items[best];sort_displaced=source->items[index];
if(!guarded_action(swap_cursor,controller,&group,best)){cancel();return;}
sort_phase=phase::pickup;phase_stamp=now;return;
}
cancel();
}
}
};
inline engine current;
inline uint32_t __fastcall tick_detour(uintptr_t controller) {
const auto result=original_tick(controller);
// A screen can tick more than one controller. Only the controller that
// owns the queued operation may advance or replace its snapshot.
if(current.active() && current.controller!=controller) {
const auto owned=latest();
if(owned.controller==current.controller && GetTickCount64()-owned.stamp<500)return result;
current.cancel(engine::stop_reason::controller);
}
static thread_local bool processing=false;
if(processing)return result;
struct processing_guard {bool& flag;processing_guard(bool& value):flag(value){flag=true;}~processing_guard(){flag=false;}} guard(processing);
static uint64_t observed_epoch=0;
const auto generation=epoch.load();if(generation!=observed_epoch){current.cancel();observed_epoch=generation;}
if(!enabled){current.cancel(engine::stop_reason::disabled);reset();return result;}
// Native transactions can stall a tick longer than the display freshness
// limit. The per-phase acknowledgement timeout governs an active sort.
auto state=capture(controller);
if(!playing_ui())current.cancel(engine::stop_reason::focus);
std::deque<request> pending;
{std::lock_guard lock(mutex);pending.swap(requests);}
for(auto const& request:pending)if(request.controller==controller) {
if(request.operation==action::stop)current.cancel(engine::stop_reason::requested);
else if(playing_ui() && !state.cursor && !current.active()) {
auto chosen=request;
if(chosen.operation==action::sort && chosen.group.empty())chosen.group=state.hover;
if(chosen.operation!=action::sort || chosen.group=="container_items" || chosen.group=="inventory_items")current.start(chosen);
}
}
current.step(state,GetTickCount64());state.busy=current.active();
{std::lock_guard lock(mutex);published=std::move(state);}
return result;
}
// Signatures are generated from independently inspected 26.52 functions.
inline constexpr const char* tick_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC C8 00 00 00 48 8D AC 24 80 00 00 00 0F 29 75 30 48 C7 45 28 FE FF FF FF 48 89 CE 48 8D B9 F8 11 00 00 C6 45 F8 00 48 81 C1 38 12 00 00 E8 AF 9F A7 FF 48 8D 4D B0 E8 E6 A1 A6 FF 48 8D 55 B0 48 89 F9 E8 9A 95 A6 FF 83 BE 04 0C 00 00 02 8B 86 30";
inline constexpr const char* item_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 83 EC 38 48 8D 6C 24 30 48 C7 45 00 FE FF FF FF 44 89 C6 48 89 D7 48 8B 5A 10 48 83 7A 18 10 72 03 48 8B 3F 48 85 DB 74 24 89 D8 83 E0 03 48 BA B3 01 00 00 00 01 00 00 48 83 FB 04 73 1E 49 B9 25 23 22 84 E4 9C F2 CB 45 31 C0 EB 62 49 BA 25 23 22 84";
inline constexpr const char* auto_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 48 01 00 00 48 8D AC 24 80 00 00 00 48 C7 85 C0 00 00 00 FE FF FF FF 44 89 CE 4C 89 C7 41 89 D6 48 89 CB 48 8B 01 48 8B 80 38 01 00 00 FF 15 96 05 30 0A 84 C0 0F 84 0F 04 00 00 4C 8D 7D 38 4C 89 F9 48 89 FA 41 89 F0 E8 A4 96 3B FE 48 8B 8B C0 12 00 00 48 8B 01 48 8B 40 40 4C 89 FA FF 15 65";
inline constexpr const char* swap_cursor_signature="55 41 57 41 56 41 55 41 54 56 57 53 48 83 EC 68 48 8D 6C 24 60 48 C7 45 00 FE FF FF FF 44 89 C7 48 89 D3 48 89 CE 48 8B 01 48 8B 80 38 01 00 00 FF 15 52 12 30 0A 84 C0 0F 84 6E 02 00 00 4C 8D B6 48 10 00 00 48 83 BE 58 10 00 00 00 0F 95 C0 44 8B 8E 68 10 00 00 41 83 F9 FF 0F 95 C1 20 C1";
inline constexpr const char* place_signature="55 41 57 41 56 41 54 56 57 53 48 81 EC F0 00 00 00 48 8D AC 24 80 00 00 00 48 C7 45 68 FE FF FF FF 44 89 C7 48 89 D3 48 89 CE 48 8B 01 48 8B 80 38 01 00 00 FF 15 6E 0C 30 0A 84 C0 0F 84 8D 01 00 00 48 83 BE 58 10 00 00 00 74 55 83 BE 68 10 00 00 FF 74 4C 4C 8D B6 20 10 00 00 4C 8B BE 20";
inline void initialize() {
if(ready)return;
get_item=reinterpret_cast<item_fn>(sigscan::find(item_signature,true));
auto_place=reinterpret_cast<auto_fn>(sigscan::find(auto_signature,true));
swap_cursor=reinterpret_cast<slot_fn>(sigscan::find(swap_cursor_signature,true));
place_all=reinterpret_cast<slot_fn>(sigscan::find(place_signature,true));
ready=get_item && swap_cursor && place_all && auto_place &&
tick_hook.install("container tick",tick_signature,reinterpret_cast<void*>(&tick_detour),reinterpret_cast<void**>(&original_tick),true) && tick_hook.set_enabled(true);
}
}
+164
View File
@@ -0,0 +1,164 @@
#pragma once
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Media.Control.h>
#include <winrt/Windows.Storage.Streams.h>
#include <wincodec.h>
#include <wrl/client.h>
#include <memory>
#include <atomic>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <string>
#include <vector>
#include <algorithm>
#pragma comment(lib,"windowsapp.lib")
#pragma comment(lib,"windowscodecs.lib")
#pragma comment(lib,"ole32.lib")
namespace media {
struct artwork {unsigned width=0,height=0;std::vector<unsigned char> rgba;};
inline std::shared_ptr<const artwork> decode_art(std::vector<unsigned char>& bytes) {
using Microsoft::WRL::ComPtr;
if(bytes.empty() || bytes.size()>4*1024*1024)return {};
ComPtr<IWICImagingFactory> factory;ComPtr<IWICStream> stream;ComPtr<IWICBitmapDecoder> decoder;
ComPtr<IWICBitmapFrameDecode> frame;ComPtr<IWICBitmapScaler> scaler;ComPtr<IWICFormatConverter> converter;
if(FAILED(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory))) ||
FAILED(factory->CreateStream(&stream)) || FAILED(stream->InitializeFromMemory(bytes.data(),DWORD(bytes.size()))) ||
FAILED(factory->CreateDecoderFromStream(stream.Get(),nullptr,WICDecodeMetadataCacheOnLoad,&decoder)) ||
FAILED(decoder->GetFrame(0,&frame)))return {};
UINT w=0,h=0;if(FAILED(frame->GetSize(&w,&h)) || !w || !h || w>16384 || h>16384)return {};
const double scale=(std::min)(1.,256./(std::max)(w,h));
w=(std::max)(1u,unsigned(w*scale));h=(std::max)(1u,unsigned(h*scale));
if(FAILED(factory->CreateBitmapScaler(&scaler)) || FAILED(scaler->Initialize(frame.Get(),w,h,WICBitmapInterpolationModeFant)) ||
FAILED(factory->CreateFormatConverter(&converter)) || FAILED(converter->Initialize(scaler.Get(),GUID_WICPixelFormat32bppRGBA,
WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom)))return {};
auto result=std::make_shared<artwork>();result->width=w;result->height=h;result->rgba.resize(w*h*4);
if(FAILED(converter->CopyPixels(nullptr,w*4,UINT(result->rgba.size()),result->rgba.data())))return {};
return result;
}
struct snapshot {
bool available=false,playing=false,previous=false,next=false,pause=false;
std::string title,artist,app,message="Looking for a media player...";
std::vector<std::string> players;
double position=0,duration=0,rate=1;uint64_t stamp=0;
std::shared_ptr<const artwork> art;
};
enum class command {previous,pause,next};
struct request {command action;std::string app;};
class reader {
public:
~reader(){stop();}
void start(){if(worker_.joinable())return;stopping_=false;worker_=std::thread([this]{run();});}
void stop(){stopping_=true;wake_.notify_all();if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_);commands_.clear();state_={};}
snapshot latest(){std::lock_guard lock(mutex_);return state_;}
void prefer(const std::string& app){std::lock_guard lock(mutex_);preferred_=app;}
void send(command action){std::lock_guard lock(mutex_);if(state_.available && commands_.size()<8){commands_.push_back({action,state_.app});wake_.notify_all();}}
private:
std::thread worker_;std::atomic<bool> stopping_{false};std::mutex mutex_;std::condition_variable wake_;
snapshot state_;std::string preferred_;std::deque<request> commands_;
template<class Operation> bool finish(Operation const& op) {
using winrt::Windows::Foundation::AsyncStatus;
const auto deadline=GetTickCount64()+3000;
while(op.Status()==AsyncStatus::Started) {
if(stopping_ || GetTickCount64()>deadline){op.Cancel();return false;}
std::unique_lock lock(mutex_);wake_.wait_for(lock,std::chrono::milliseconds(20),[this]{return stopping_.load();});
}
if(!stopping_ && op.Status()==AsyncStatus::Error)op.GetResults();
return !stopping_ && op.Status()==AsyncStatus::Completed;
}
static std::string utf8(winrt::hstring const& value) {return winrt::to_string(value);}
void publish(snapshot state){std::lock_guard lock(mutex_);state_=std::move(state);}
void run() {
using namespace winrt::Windows::Media::Control;
bool initialized=false;
try {
winrt::init_apartment(winrt::apartment_type::multi_threaded);initialized=true;
{
auto pending=GlobalSystemMediaTransportControlsSessionManager::RequestAsync();
if(!finish(pending))throw winrt::hresult_error(E_ABORT);
auto manager=pending.GetResults();std::string art_key;
std::shared_ptr<const artwork> cover;uint64_t art_attempt=0;
while(!stopping_) {
try {
snapshot result;result.message.clear();std::string preferred;std::deque<request> commands;
{std::lock_guard lock(mutex_);preferred=preferred_;commands.swap(commands_);}
auto sessions=manager.GetSessions();auto selected=manager.GetCurrentSession();
for(auto const& session:sessions) {
const auto app=utf8(session.SourceAppUserModelId());result.players.push_back(app);
if(!preferred.empty() && app==preferred)selected=session;
}
if(!preferred.empty() && (!selected || utf8(selected.SourceAppUserModelId())!=preferred))selected=nullptr;
if(selected) {
result.app=utf8(selected.SourceAppUserModelId());
for(auto const& command:commands) {
// A queued click must never control a different player after a session switch.
if(command.app!=result.app || stopping_)continue;
auto op=command.action==media::command::previous ? selected.TrySkipPreviousAsync() :
command.action==media::command::next ? selected.TrySkipNextAsync() : selected.TryTogglePlayPauseAsync();
if(finish(op) && !op.GetResults())result.message="Player declined that control";
}
auto properties=selected.TryGetMediaPropertiesAsync();
if(!finish(properties))throw winrt::hresult_error(E_ABORT);
auto info=properties.GetResults();
result.title=utf8(info.Title());result.artist=utf8(info.Artist());
const auto key=result.app+"\n"+result.title+"\n"+result.artist+"\n"+utf8(info.AlbumTitle());
if(key!=art_key || (!cover && GetTickCount64()-art_attempt>10000)) {
art_key=key;cover.reset();art_attempt=GetTickCount64();
try {
if(auto thumbnail=info.Thumbnail()) {
auto opening=thumbnail.OpenReadAsync();
if(finish(opening)) {
auto stream=opening.GetResults();const auto size=stream.Size();
if(size>0 && size<=4*1024*1024) {
auto data=winrt::Windows::Storage::Streams::DataReader(stream);
auto loading=data.LoadAsync(uint32_t(size));
if(finish(loading) && loading.GetResults()==size) {
std::vector<unsigned char> bytes(size);data.ReadBytes(bytes);cover=decode_art(bytes);
}
}
}
}
} catch(winrt::hresult_error const&) {cover.reset();}
}
result.art=cover;
auto playback=selected.GetPlaybackInfo();auto controls=playback.Controls();
result.playing=playback.PlaybackStatus()==GlobalSystemMediaTransportControlsSessionPlaybackStatus::Playing;
result.previous=controls.IsPreviousEnabled();result.next=controls.IsNextEnabled();
result.pause=controls.IsPlayPauseToggleEnabled();
if(auto rate=playback.PlaybackRate())result.rate=std::clamp(rate.Value(),0.,16.);
const auto time=selected.GetTimelineProperties();
const double start=double(time.StartTime().count())/1e7;
result.duration=(std::max)(0.,double(time.EndTime().count())/1e7-start);
result.position=std::clamp(double(time.Position().count())/1e7-start,0.,result.duration);
if(result.playing) {
const double elapsed=double((winrt::clock::now()-time.LastUpdatedTime()).count())/1e7;
if(elapsed>=0 && elapsed<86400)result.position=std::clamp(result.position+elapsed*result.rate,0.,result.duration);
}
result.available=true;result.stamp=GetTickCount64();
if(result.title.empty())result.title="Untitled track";
} else result.message=preferred.empty() ? "No active media session" : "Selected player is unavailable";
publish(std::move(result));
} catch(winrt::hresult_error const& error) {
if(!stopping_) {snapshot result;result.message="Media unavailable: "+utf8(error.message());publish(std::move(result));}
}
std::unique_lock lock(mutex_);
wake_.wait_for(lock,std::chrono::milliseconds(500),[this]{return stopping_ || !commands_.empty();});
}
}
} catch(winrt::hresult_error const& error) {
if(!stopping_){snapshot result;result.message="Windows media access unavailable: "+utf8(error.message());publish(std::move(result));}
} catch(...) {
snapshot result;result.message="Windows media access unavailable";publish(std::move(result));
}
if(initialized)winrt::uninit_apartment();
}
};
// Explicit lifetime: joining a COM worker from a DLL static destructor
// would run under the loader lock. The exported unload path owns shutdown.
inline reader* instance=nullptr;
inline reader& system(){if(!instance)instance=new reader;return *instance;}
inline void shutdown(){delete instance;instance=nullptr;}
}
+53 -1
View File
@@ -5,6 +5,58 @@
// These are specific to one game version and must be re-found after every update.
namespace sigs {
// CursorRenderer::render in 1.26.5203.0. Identified from the cursor_renderer
// factory/vtable; body constructs "ui_crosshair". Four pointer arguments, void return.
inline constexpr const char* render_native_crosshair =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 18 05 00 00 "
"48 8D AC 24 80 00 00 00 0F 29 BD 80 04 00 00 0F 29 B5 70 04 00 00 "
"48 C7 85 68 04 00 00 FE FF FF FF 4D 89 CE 4C 89 C6 48 89 D3 48 89 CF";
// 26.52 first-person ItemInHandRenderer render entry, RVA 0x47ca240.
inline constexpr const char* render_hands =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC 18 02 00 00 "
"48 8D AC 24 80 00 00 00 44 0F 29 BD 80 01 00 00 "
"44 0F 29 B5 70 01 00 00 44 0F 29 AD 60 01 00 00 "
"44 0F 29 A5 50 01 00 00 44 0F 29 9D 40 01 00 00 "
"44 0F 29 95 30 01 00 00 44 0F 29 8D 20 01 00 00 "
"44 0F 29 85 10 01 00 00 0F 29 BD 00 01 00 00 0F 29 B5 F0 00 00 00 "
"48 C7 85 E8 00 00 00 FE FF FF FF 44 88 4D 7F 4D 89 C7 "
"48 89 D3 48 89 CE 48 8B 89 70 01 00 00 48 8B 01 48 8B 80 F8 00 00 00";
// Shared item draw entry, RVA 0x47b5ba0. Filter to the offhand call below.
inline constexpr const char* render_offhand_item =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC D8 03 00 00 "
"48 8D AC 24 80 00 00 00 44 0F 29 8D 40 03 00 00 "
"44 0F 29 85 30 03 00 00 0F 29 BD 20 03 00 00 "
"0F 29 B5 10 03 00 00 48 C7 85 08 03 00 00 FE FF FF FF "
"41 80 79 23 01";
// Offhand item from Player's second hand slot (+0xf0), inside render_hands.
// The E8 is at +13 and its return address is at +18 (RVA 0x47ceee5).
inline constexpr const char* offhand_draw_call =
"48 89 F9 48 8B 55 F8 49 89 F0 4D 89 F1 E8 ?? ?? ?? ?? "
"C6 85 E0 00 00 00 00 C7 85 88 00 00 00 00 00 00 00";
// 1.26.5203.0, RVA 0x46bda60. Sole direct caller is the first-person
// projection path (getFov(..., false)); RDX is a writable float[16], XMM2 is alpha.
inline constexpr const char* hand_bob =
"55 56 57 53 48 81 EC 28 01 00 00 48 8D AC 24 80 00 00 00 "
"44 0F 29 BD 90 00 00 00 44 0F 29 B5 80 00 00 00 "
"44 0F 29 6D 70 44 0F 29 65 60 44 0F 29 5D 50 "
"44 0F 29 55 40 44 0F 29 4D 30 44 0F 29 45 20 "
"0F 29 7D 10 0F 29 75 00 48 C7 45 F8 FE FF FF FF "
"0F 28 FA 48 89 D6 48 8B 89 68 11 00 00";
// GameRenderer::getFov(void* renderer, float frame_alpha, bool world_projection).
// Verified in the running 1.26.5203.0 executable: reads video.fov (option 0x2f),
// returns degrees, and clamps vanilla FOV to [5, 130]. Unique function entry.
inline constexpr const char* get_fov =
"56 57 53 48 83 EC 60 "
"44 0F 29 44 24 50 0F 29 7C 24 40 0F 29 74 24 30 "
"44 89 C3 0F 28 F1 48 89 CE 45 84 C0 "
"0F 84 ?? ?? ?? ?? "
"48 8B 86 88 11 00 00 48 8B 88 F8 03 00 00 "
"48 8B 01 48 8B 80 D8 00 00 00 "
"48 8D 54 24 28 41 B8 2F 00 00 00";
// a function that returns the brightness setting as a float
inline constexpr const char* get_gamma =
"48 8B 49 58 66 66 66 2E 0F 1F 84 00 00 00 00 00 "
@@ -38,4 +90,4 @@ namespace sigs {
"48 3B 0D ?? ?? ?? ?? "
"75 05 "
"48 83 C4 38 C3";
}
}
+11 -4
View File
@@ -77,7 +77,7 @@ namespace sigscan {
}
// searches the executable sections of the game's main module
inline uint8_t* find(const char* ida_pattern) {
inline uint8_t* find(const char* ida_pattern, bool require_unique = false) {
pattern pat;
if (!parse(ida_pattern, pat)) return nullptr;
@@ -85,6 +85,7 @@ namespace sigscan {
auto* dos = (IMAGE_DOS_HEADER*)base;
auto* nt = (IMAGE_NT_HEADERS*)(base + dos->e_lfanew);
const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt);
uint8_t* found = nullptr;
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue;
@@ -100,12 +101,18 @@ namespace sigscan {
const bool readable = mbi.State == MEM_COMMIT && !(mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD));
if (readable) {
if (uint8_t* hit = scan_range(p, region_end, pat)) return hit;
uint8_t* next = p;
while (uint8_t* hit = scan_range(next, region_end, pat)) {
if (!require_unique) return hit;
if (found) return nullptr;
found = hit;
next = hit + 1;
}
}
p = region_end;
}
}
return nullptr;
return found;
}
// for patterns that land on a RIP-relative instruction (e.g. a call or lea):
@@ -115,4 +122,4 @@ namespace sigscan {
return instr + instr_len + rel;
}
} // namespace sigscan
} // namespace sigscan
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#include <cmath>
#include <cstring>
namespace game {
inline void multiply_matrix(const float* a, const float* b, float* out) {
float result[16]{};
for (int col = 0; col < 4; ++col)
for (int row = 0; row < 4; ++row)
for (int k = 0; k < 4; ++k) result[col*4+row] += a[k*4+row] * b[col*4+k];
std::memcpy(out, result, sizeof(result));
}
inline bool inverse_matrix(const float* matrix, float* inverse) {
double rows[4][8]{};
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
if (!std::isfinite(matrix[c*4+r])) return false;
rows[r][c] = matrix[c*4+r];
}
rows[r][4+r] = 1;
}
for (int col = 0; col < 4; ++col) {
int pivot = col;
for (int r = col+1; r < 4; ++r)
if (std::fabs(rows[r][col]) > std::fabs(rows[pivot][col])) pivot = r;
if (std::fabs(rows[pivot][col]) < 1.e-10) return false;
for (int c = 0; c < 8; ++c) { const double v = rows[col][c]; rows[col][c] = rows[pivot][c]; rows[pivot][c] = v; }
const double divisor = rows[col][col];
for (double& v : rows[col]) v /= divisor;
for (int r = 0; r < 4; ++r) {
if (r == col) continue;
const double factor = rows[r][col];
for (int c = 0; c < 8; ++c) rows[r][c] -= factor * rows[col][c];
}
}
for (int r = 0; r < 4; ++r) for (int c = 0; c < 4; ++c)
inverse[c*4+r] = static_cast<float>(rows[r][4+c]);
return true;
}
// Verified 26.52: BaseActorRenderContext+0x28 -> render context+0x18 ->
// ScreenContext. World MatrixStack has a deque of one matrix per block at +0x80.
inline float* viewmodel_world_matrix(void* actor_context, unsigned char** screen_out = nullptr) {
if (!actor_context) return nullptr;
auto* render = *reinterpret_cast<unsigned char**>(static_cast<unsigned char*>(actor_context) + 0x28);
if (!render) return nullptr;
auto* screen = *reinterpret_cast<unsigned char**>(render + 0x18);
if (!screen) return nullptr;
auto** map = *reinterpret_cast<float***>(screen + 0x88);
const size_t capacity = *reinterpret_cast<size_t*>(screen + 0x90);
const size_t first = *reinterpret_cast<size_t*>(screen + 0x98);
const size_t size = *reinterpret_cast<size_t*>(screen + 0xa0);
if (!map || !capacity || capacity > 65536 || (capacity & (capacity-1)) || !size) return nullptr;
if (screen_out) *screen_out = screen;
return map[(first + size - 1) & (capacity - 1)];
}
class viewmodel_matrix_scope {
public:
explicit viewmodel_matrix_scope(void* context) : matrix(viewmodel_world_matrix(context, &screen_)) {
if (matrix) std::memcpy(saved, matrix, sizeof(saved));
}
~viewmodel_matrix_scope() {
if (matrix) { std::memcpy(matrix, saved, sizeof(saved)); dirty(); }
}
void dirty() { if (screen_) screen_[0xb8] = 1; }
float* matrix;
float saved[16]{};
private:
unsigned char* screen_ = nullptr;
};
// Render matrices are column-major float[16].
inline void transform_viewmodel(float* matrix, const float* translation, const float* rotation) {
if (!matrix) return;
// Translate in the current local basis (M * T).
for (int row = 0; row < 4; ++row)
matrix[12 + row] += matrix[row] * translation[0] +
matrix[4 + row] * translation[1] + matrix[8 + row] * translation[2];
constexpr float radians = 0.017453292519943295f;
// Local pitch, yaw, roll: M * Rx * Ry * Rz. Translation remains the pivot.
const int first[] = {1, 2, 0}, second[] = {2, 0, 1};
for (int axis = 0; axis < 3; ++axis) {
if (rotation[axis] == 0.f) continue;
const float c = std::cos(rotation[axis] * radians), s = std::sin(rotation[axis] * radians);
for (int row = 0; row < 4; ++row) {
const int a = first[axis] * 4 + row, b = second[axis] * 4 + row;
const float old_a = matrix[a], old_b = matrix[b];
matrix[a] = old_a * c + old_b * s;
matrix[b] = old_b * c - old_a * s;
}
}
}
}
+417
View File
@@ -0,0 +1,417 @@
#pragma once
#include <windows.h>
#include <atomic>
#include <memory>
#include <mutex>
#include <vector>
#include <array>
#include <intrin.h>
#include "world_math.h"
#include "hook.h"
#include "../input.h"
// Verified 1.26.5203.0 read-only ECS access. Do not instantiate an external
// EnTT registry: Bedrock uses different sparse/payload page sizes.
namespace world {
inline constexpr const char* client_update_signature =
"55 41 57 41 56 41 55 41 54 56 57 53 48 81 EC F8 04 00 00 48 8D AC 24 80 00 00 00 "
"48 C7 85 70 04 00 00 FE FF FF FF 89 D3 48 89 CE 48 8B 01 48 8B 80 68 0C 00 00";
inline constexpr const char* camera_matrix_signature =
"41 57 41 56 41 54 56 57 53 48 81 EC 08 01 00 00 44 0F 29 AC 24 F0 00 00 00 "
"44 0F 29 A4 24 E0 00 00 00 44 0F 29 9C 24 D0 00 00 00";
inline constexpr const char* active_camera_signature =
"48 8D 7B 30 48 89 F9 BA 2B 77 9E 11 E8 ?? ?? ?? ?? 48 8B 48 20 48 39 48 28 74 74 8B 01";
inline constexpr const char* time_signature =
"48 63 C2 48 69 C8 F1 19 76 05 48 89 CA 48 C1 EA 3F 48 C1 F9 29 01 D1 69 C9 C0 5D 00 00 29 C8 F3 0F 2A C0 F3 0F 58 C2";
inline constexpr const char* name_signature =
"56 48 83 EC 20 48 8B 81 28 01 00 00 48 85 C0 74 4A 8B 50 08 48 8B 08 29 CA "
"81 E2 F8 FF 07 00 48 8D 05 ?? ?? ?? ?? 83 FA 21 72 2A 48 8B 71 20";
inline constexpr const char* fog_signature =
"48 89 D0 41 0F 10 00 0F 11 02 F3 0F 10 05 ?? ?? ?? ?? F3 0F 59 C3 F3 0F 58 05 ?? ?? ?? ?? "
"F3 0F 10 0A F3 0F 59 C8 F3 0F 11 0A F3 0F 59 42 04 F3 0F 11 42 04";
template<class T> inline bool read(uintptr_t address, T& out) {
if (address<0x10000 || address>0x7fffffffffff-sizeof(T)) return false;
__try { memcpy(&out,reinterpret_cast<const void*>(address),sizeof(T));return true; }
__except(EXCEPTION_EXECUTE_HANDLER) {return false;}
}
template<class T> inline T get(uintptr_t address) {T out{};read(address,out);return out;}
template<class T> inline bool write(uintptr_t address,const T& value) {
if(address<0x10000) return false;
__try {memcpy(reinterpret_cast<void*>(address),&value,sizeof(T));return true;}
__except(EXCEPTION_EXECUTE_HANDLER) {return false;}
}
inline constexpr uint32_t hash(const char* name) {
uint32_t value=2166136261u;for(;*name;++name) value=(value^uint8_t(*name))*16777619u;return value;
}
inline uintptr_t pool(uintptr_t registry,uint32_t type) {
const auto buckets=get<uintptr_t>(registry+0x48), bucket_end=get<uintptr_t>(registry+0x50);
const auto begin=get<uintptr_t>(registry+0x68), end=get<uintptr_t>(registry+0x70);
if (!buckets || bucket_end<=buckets || bucket_end-buckets>0x100000 || !begin || end<begin || end-begin>0x100000) return 0;
const size_t count=(bucket_end-buckets)/8, entries=(end-begin)/32;
if (!count || (count&(count-1))) return 0;
auto index=get<uintptr_t>(buckets+(type&(count-1))*8);
for(size_t step=0;step<entries && index<entries;++step) {
const auto entry=begin+index*32;
if(get<uint32_t>(entry+8)==type) return get<uintptr_t>(entry+16);
index=get<uintptr_t>(entry);
}
return 0;
}
inline uintptr_t component_at(uintptr_t storage,uint32_t entity) {
if(!storage) return 0;
const auto sparse=get<uintptr_t>(storage+8), end=get<uintptr_t>(storage+16);
const size_t page=(entity&0x3ffff)>>11;
if(!sparse || end<sparse || end-sparse>0x100000 || page>=(end-sparse)/8) return 0;
const auto data=get<uintptr_t>(sparse+page*8); uint32_t packed;
if(!data || !read(data+(entity&0x7ff)*4,packed) || (packed^(entity&0xfffc0000))>0x3fffe) return 0;
const auto first=get<uintptr_t>(storage+32), last=get<uintptr_t>(storage+40);
const size_t index=packed&0x3ffff;
if(!first || last<first || last-first>0x100000 || index>=(last-first)/4 || get<uint32_t>(first+index*4)!=entity) return 0;
const auto fn=get<uintptr_t>(get<uintptr_t>(storage));
// Slot zero is the native read-only get_at(size_t), accounting for each
// component's own stride. Validate its verified payload-load prefix.
// Sixteen-byte components use a verified getter with an index-copy
// instruction before the payload load (ActorRotationComponent).
const std::array<uint8_t,7> indexed{0x48,0x89,0xd0,0x48,0x8b,0x49,0x50};
if(get<uint32_t>(fn)!=0x50498b48 && get<std::array<uint8_t,7>>(fn)!=indexed) return 0;
__try {return reinterpret_cast<uintptr_t(__fastcall*)(uintptr_t,size_t)>(fn)(storage,index);}
__except(EXCEPTION_EXECUTE_HANDLER) {return 0;}
}
inline uintptr_t component(uintptr_t registry,uint32_t entity,const char* type) {return component_at(pool(registry,hash(type)),entity);}
inline std::string string(uintptr_t address,size_t limit=96) {
struct native_string { char data[16];uint64_t size,capacity; } value;
if(!read(address,value) || value.size>limit || value.capacity<value.size || value.capacity>1048576) return {};
uintptr_t bytes=value.capacity<16 ? address : get<uintptr_t>(address);
std::string out;out.reserve(size_t(value.size));
for(size_t i=0;i<value.size;++i) {char c;if(!read(bytes+i,c) || !c) return {};out+=c;}
return out;
}
struct item {std::string name;int count=0;};
struct actor {
uint32_t id=0;std::string name;vec3 position{},feet{},head{},velocity{};
float health=0,max_health=0;bool health_known=false;
item held;std::array<item,4> armor{};
};
struct frame {
bool valid=false,has_block=false,has_target=false;
uint64_t stamp=0,world_id=0;actor local,target;
std::vector<actor> players;
std::vector<std::string> online_players;bool roster_known=false,xp_known=false;int xp_level=0;float xp_progress=0;
vec3 block{},camera{};float matrix[16]{},fov_x=1,fov_y=1;
};
inline std::shared_ptr<const frame> published=std::make_shared<frame>();
inline std::mutex frame_mutex,alias_mutex;
inline std::atomic<uintptr_t> client{0};
inline std::atomic<DWORD> render_thread{0};
inline std::atomic<bool> collect_players{false},collect_roster{false},collect_xp{false};
inline std::atomic<int> time_override{-1};
inline bool ready=false,camera_ready=false,time_ready=false,name_ready=false,fog_ready=false;
inline std::atomic<bool> fog_enabled{false};
inline std::atomic<uint32_t> fog_color{0};
inline std::atomic<bool> hide_native_names{false}, alias_enabled{false};
inline std::shared_ptr<const std::string> alias=std::make_shared<const std::string>("Player");
inline std::atomic<uintptr_t> local_actor{0};
inline thread_local bool rendering=false;
inline void (*after_world)()=nullptr;
inline std::shared_ptr<const frame> latest() {std::lock_guard<std::mutex> lock(frame_mutex);return published;}
inline void publish(frame value) {auto next=std::make_shared<frame>(std::move(value));std::lock_guard<std::mutex> lock(frame_mutex);published=std::move(next);}
inline std::shared_ptr<const std::string> current_alias() {std::lock_guard<std::mutex> lock(alias_mutex);return alias;}
inline void set_alias(std::string name) {auto next=std::make_shared<const std::string>(std::move(name));std::lock_guard<std::mutex> lock(alias_mutex);alias=std::move(next);}
inline bool fresh(const frame& value) {return value.valid && GetTickCount64()-value.stamp<500;}
inline item read_item(uintptr_t stack) {
item value;if(!stack) return value;
const auto counter=get<uintptr_t>(stack+8),type=get<uintptr_t>(counter);
if(!type) return value;
value.name=string(type+0xd8);value.count=get<uint8_t>(stack+0x22);
if(!value.count) value.name.clear();return value;
}
inline uintptr_t inventory_item(uintptr_t container,int slot) {
const auto first=get<uintptr_t>(container+0x1a0),end=get<uintptr_t>(container+0x1a8);
if(!first || end<first || end-first>152*256 || slot<0 || size_t(slot)>=(end-first)/152) return 0;
return first+152*slot;
}
inline uintptr_t carried_item(uintptr_t player) {
const auto inventory=get<uintptr_t>(player+0x5b8);
const auto container=get<uintptr_t>(inventory+0xb8);
const int selected=get<int>(inventory+0x10);
const auto first=get<uintptr_t>(container+0x198),last=get<uintptr_t>(container+0x1a0);
if(!first || selected<0 || selected>8 || get<uint8_t>(inventory+0xb0) || last<first || last-first>152*256 || size_t(selected)>=(last-first)/152) return 0;
return first+152*selected;
}
inline bool read_actor(uintptr_t registry,uint32_t id,actor& value,bool equipment=true) {
auto state=component(registry,id,"StateVectorComponent");
if(!state || !read(state,value.position) || !finite(value.position)) return false;
value.id=id;read(state+24,value.velocity);
auto bounds=component(registry,id,"AABBShapeComponent");
vec3 min{},max{};
value.feet={value.position.x,value.position.y-1.62f,value.position.z};
if(read(bounds,min) && read(bounds+12,max) && finite(max) && max.y-min.y>0 && max.y-min.y<5) {
value.feet={(min.x+max.x)*.5f,min.y,(min.z+max.z)*.5f};
value.head={(min.x+max.x)*.5f,max.y+.3f,(min.z+max.z)*.5f};
}
else value.head={value.position.x,value.position.y+.3f,value.position.z};
const auto sync=component(registry,id,"SynchedActorDataComponent");
const auto items=get<uintptr_t>(sync),end=get<uintptr_t>(sync+8);
if(items && end>=items+5*8 && end-items<8192) value.name=clean_name(string(get<uintptr_t>(items+4*8)+16));
const auto attrs=component(registry,id,"AttributesComponent");
const auto keys=get<uintptr_t>(attrs),last=get<uintptr_t>(attrs+8),values=get<uintptr_t>(attrs+24),val_end=get<uintptr_t>(attrs+32);
if(keys && last>keys && last-keys<=800 && values && val_end>values) {
const size_t count=(last-keys)/4,stride=(val_end-values)/count;
if(stride==136) for(size_t i=0;i<count;++i) if(get<uint32_t>(keys+i*4)==7) {
value.health=get<float>(values+i*stride+0x7c);value.max_health=get<float>(values+i*stride+0x78);
value.health_known=std::isfinite(value.health) && std::isfinite(value.max_health) && value.max_health>0 && value.max_health<=2048 && value.health>=0 && value.health<=value.max_health;break;
}
}
if(equipment) {
auto equip=component(registry,id,"ActorEquipmentComponent");auto armor=get<uintptr_t>(equip+8);
for(int i=0;i<4;++i) value.armor[i]=read_item(inventory_item(armor,i));
// The player's selected stack is accessed through its actual
// inventory reference rather than through item-renderer copies.
const auto owner=get<uintptr_t>(component(registry,id,"ActorOwnerComponent"));
value.held=read_item(carried_item(owner));
}
return true;
}
inline bool read_roster_map(uintptr_t map,std::vector<std::string>& names) {
const auto head=get<uintptr_t>(map+8),count=get<uintptr_t>(map+16);
if(!head || count>1024)return false;
auto node=get<uintptr_t>(head);std::vector<std::string> result;
for(size_t i=0;i<count;++i) {
if(!node || node==head)return false;
auto name=clean_name(string(node+56));if(name.empty())return false;
result.push_back(std::move(name));node=get<uintptr_t>(node);
}
if(node!=head || get<uintptr_t>(map+16)!=count)return false;
std::sort(result.begin(),result.end());names=std::move(result);return true;
}
inline bool read_roster(uintptr_t registry,std::vector<std::string>& names) {
const auto storage=pool(registry,hash("LevelComponent"));
const auto first=get<uintptr_t>(storage+32),last=get<uintptr_t>(storage+40);
if(!first || last-first!=4)return false;
const auto level=get<uintptr_t>(component_at(storage,get<uint32_t>(first)));
return level && read_roster_map(get<uintptr_t>(level+0x4e0),names);
}
inline bool read_xp_values(uintptr_t attrs,int& level,float& progress) {
const auto keys=get<uintptr_t>(attrs),end=get<uintptr_t>(attrs+8);
const auto values=get<uintptr_t>(attrs+24),last=get<uintptr_t>(attrs+32);
if(!keys || end<=keys || end-keys>800 || (end-keys)%4 || !values || last<values || last-values!=(end-keys)/4*136)return false;
float l=-1,p=-1;
for(size_t i=0;i<(end-keys)/4;++i) {
const auto id=get<uint32_t>(keys+4*i);
if(id==4)l=get<float>(values+136*i+0x70);
if(id==5)p=get<float>(values+136*i+0x70);
}
if(!std::isfinite(l) || l<0 || l>24791 || l!=std::floor(l) || !std::isfinite(p) || p<0 || p>1)return false;
level=int(l);progress=p;return true;
}
inline void capture(uintptr_t ci) {
frame out;out.stamp=GetTickCount64();
const auto registry_owner=get<uintptr_t>(ci+0x248),registry=registry_owner+0x30;
const auto entity=get<uint32_t>(ci+0x258);out.world_id=registry_owner;
local_actor=get<uintptr_t>(component(registry,entity,"ActorOwnerComponent"));
const auto renderer=get<uintptr_t>(ci+0x1c0),camera=get<uintptr_t>(renderer+0x468);
if(!registry_owner || !camera || !read_actor(registry,entity,out.local) || !read(camera+0x660,out.camera) || !read(ci+0x420,out.matrix)) {input::in_world=false;publish(std::move(out));return;}
out.fov_x=get<float>(camera+0xf58);out.fov_y=get<float>(camera+0xf6c);
out.valid=finite(out.camera) && std::isfinite(out.fov_x) && std::isfinite(out.fov_y) && out.fov_x>0 && out.fov_y>0;
const auto controller=get<uintptr_t>(component(registry,entity,"HitResultComponent"));
const auto hits=get<uintptr_t>(controller+8),hits_end=get<uintptr_t>(controller+16);
if(hits && hits_end>=hits+272 && hits_end-hits<272*64) {
const int type=get<int>(hits+24);
if(type==0) {
struct block_position{int x,y,z;} block;
if(read(hits+32,block)) {out.block={float(block.x),float(block.y),float(block.z)};out.has_block=true;}
} else if(type==1) {
const auto hit_owner=get<uintptr_t>(hits+56);const auto target=get<uint32_t>(hits+72);
const auto type_ptr=component(hit_owner+0x30,target,"ActorTypeComponent");
if(hit_owner==registry_owner && get<int>(type_ptr)==319) out.has_target=read_actor(registry,target,out.target);
}
}
if(collect_players) {
const auto owners=pool(registry,hash("ActorOwnerComponent"));
const auto first=get<uintptr_t>(owners+32),last=get<uintptr_t>(owners+40);
if(first && last>=first && last-first<=4*16384) for(auto at=first;at<last && out.players.size()<128;at+=4) {
const auto id=get<uint32_t>(at);if(id==entity || id==0xfffc0000) continue;
const auto type_ptr=component(registry,id,"ActorTypeComponent");if(get<int>(type_ptr)!=319) continue;
actor other;if(read_actor(registry,id,other,false) && distance(other.position,out.local.position)<=128 && !other.name.empty()) out.players.push_back(std::move(other));
}
}
if(out.valid && collect_roster)out.roster_known=read_roster(registry,out.online_players);
if(out.valid && collect_xp)out.xp_known=read_xp_values(component(registry,entity,"AttributesComponent"),out.xp_level,out.xp_progress);
input::in_world=out.valid;
publish(std::move(out));
}
inline game::game_hook update_hook,camera_hook,time_hook,name_hook,fog_hook;
inline void* level_target=nullptr;
using update_fn=bool(__fastcall*)(uintptr_t,bool);
using level_fn=int64_t(__fastcall*)(uintptr_t,void*,int64_t);
using camera_fn=void(__fastcall*)(uintptr_t,void*,float);
using time_fn=float(__fastcall*)(void*,int,float);
using active_fn=void*(__fastcall*)(void*,uintptr_t);
using name_fn=const std::string*(__fastcall*)(uintptr_t);
struct color {float r,g,b,a;};
using fog_fn=color*(__fastcall*)(void*,color*,const color*,float);
inline update_fn original_update=nullptr;
inline level_fn original_level=nullptr;
inline camera_fn original_camera=nullptr;
inline time_fn original_time=nullptr;
inline active_fn get_camera=nullptr;
inline name_fn original_name=nullptr;
inline fog_fn original_fog=nullptr;
inline color* __fastcall fog_detour(void* self,color* output,const color* base,float brightness) {
auto* result=original_fog(self,output,base,brightness);
if(result && fog_enabled && GetCurrentThreadId()==render_thread.load()) {
const auto color=fog_color.load(); const float blend=float((color>>24)&255)/255.f;
result->r+=(float(color&255)/255.f-result->r)*blend;
result->g+=(float((color>>8)&255)/255.f-result->g)*blend;
result->b+=(float((color>>16)&255)/255.f-result->b)*blend;
}
return result;
}
inline const std::string* __fastcall name_detour(uintptr_t self) {
const auto address=reinterpret_cast<uintptr_t>(_ReturnAddress())-reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
const bool visual=GetCurrentThreadId()==render_thread.load() &&
(rendering || (address>=0x4600000 && address<0x4900000) || (address>=0x8c00000 && address<0x9000000));
if(visual) {
if(self==local_actor.load() && alias_enabled) {
thread_local std::shared_ptr<const std::string> returned;
returned=current_alias();return returned.get();
}
if(self!=local_actor.load() && hide_native_names) {
const auto reg=get<uintptr_t>(self+16);const auto id=get<uint32_t>(self+24);
if(get<int>(component(reg,id,"ActorTypeComponent"))==319) {static const std::string empty;return &empty;}
}
}
return original_name(self);
}
struct player_look_lock {
bool held=false;uintptr_t owner=0;uint32_t entity=0;
std::array<float,4> rotation{};std::array<float,2> head{},body{},render{},delta{},last_native{};
bool apply(uintptr_t identity,uint32_t id,uintptr_t rot,uintptr_t head_at,uintptr_t body_at,uintptr_t render_at,bool active) {
delta={};
if(!active){held=false;owner=0;return false;}
const bool continuing=held && owner==identity && entity==id;
if(!continuing) {
std::array<float,4> r;std::array<float,2> h,b,v;
if(!read(rot,r) || !read(head_at,h) || !read(body_at,b) || !read(render_at,v))return false;
for(float value:r)if(!std::isfinite(value))return false;
for(float value:h)if(!std::isfinite(value))return false;
for(float value:b)if(!std::isfinite(value))return false;
rotation={r[0],r[1],r[0],r[1]};head={h[0],h[0]};body={b[0],b[0]};render={r[0],r[1]};
last_native={r[0],r[1]};held=true;owner=identity;entity=id;
}
if(continuing) {
std::array<float,4> current;
if(!read(rot,current) || !std::isfinite(current[0]) || !std::isfinite(current[1]))return false;
// Bedrock may reapply its cached absolute look target every tick.
// Consume target changes once; ignore our own restored baseline.
if(current[0]!=rotation[0] || current[1]!=rotation[1]) {
delta={current[0]-last_native[0],std::remainder(current[1]-last_native[1],360.f)};
last_native={current[0],current[1]};
}
}
return write(rot,rotation) && write(head_at,head) && write(body_at,body) && write(render_at,render);
}
};
inline player_look_lock frozen_look;
inline std::mutex player_look_mutex;
inline std::atomic<float> pending_orbit_yaw{0},pending_orbit_pitch{0};
inline void accumulate(std::atomic<float>& target,float delta) {
auto previous=target.load();while(!target.compare_exchange_weak(previous,previous+delta)){}
}
inline void sync_player_look(uintptr_t ci) {
std::lock_guard lock(player_look_mutex);
if(!input::freelook_active()){frozen_look.held=false;frozen_look.owner=0;pending_orbit_yaw=0;pending_orbit_pitch=0;return;}
const auto owner=get<uintptr_t>(ci+0x248),registry=owner+0x30;
const auto id=get<uint32_t>(ci+0x258);if(!owner)return;
const bool applied=frozen_look.apply(owner,id,component(registry,id,"ActorRotationComponent"),
component(registry,id,"ActorHeadRotationComponent"),component(registry,id,"MobBodyRotationComponent"),
component(registry,id,"RenderRotationComponent"),true);
if(applied) {
accumulate(pending_orbit_pitch,frozen_look.delta[0]);
accumulate(pending_orbit_yaw,frozen_look.delta[1]);
}
}
inline bool __fastcall update_detour(uintptr_t self,bool initial) {
client=self;sync_player_look(self);
const auto result=original_update(self,initial);sync_player_look(self);return result;
}
inline int64_t __fastcall level_detour(uintptr_t self,void* context,int64_t parameters) {
render_thread=GetCurrentThreadId();sync_player_look(client.load());const bool previous=rendering;rendering=true;
const auto result=original_level(self,context,parameters);
capture(client.load());if(after_world) after_world();rendering=previous;return result;
}
struct active_context {uintptr_t owner,registry;uint32_t entity;uint8_t padding[4];bool valid;uint8_t tail[7];};
inline uintptr_t active_camera(uintptr_t ci) {
active_context context{};
__try {if(get_camera) get_camera(&context,ci);}
__except(EXCEPTION_EXECUTE_HANDLER) {return 0;}
return context.valid ? component(context.registry,context.entity,"MinecraftCamera::CameraComponent") : 0;
}
inline game::game_hook perspective_hook;
inline bool perspective_ready=false;
using perspective_fn=int(__fastcall*)(uintptr_t);
inline perspective_fn original_perspective=nullptr;
inline std::atomic<float> orbit_distance{4.f};
inline int __fastcall perspective_detour(uintptr_t options) {
sync_player_look(client.load());
const int native=original_perspective(options);
return input::freelook_active() ? 1 : native;
}
inline constexpr const char* perspective_signature="48 83 EC 38 48 8B 05 45 2C 82 10 48 31 E0 48 89 44 24 30 48 8B 01 48 8B 40 08 48 8D 54 24 28 41 B8 03 00 00 00 FF 15 4D 46 14 0E 48 8B 4C 24 28 48 89 C8 48 8B 49 08 48 8B 89 38 02 00 00 48 85 C9 75 ED 8B 40 18 48 8B 4C 24 30 48 31 E1 48 3B 0D FB 2B 82 10 75 05 48 83 C4";
inline std::mutex look_mutex;
inline quaternion saved_orientation{};
inline float yaw=0,pitch=0;
inline bool was_looking=false;
inline void __fastcall camera_detour(uintptr_t self,void* context,float alpha) {
render_thread=GetCurrentThreadId();const auto ci=get<uintptr_t>(self+0x1168);
sync_player_look(ci);
const bool looking=input::freelook_active();
const auto camera=looking ? active_camera(ci) : 0;
quaternion original{},replacement{};vec3 original_position{};bool changed=false,moved=false;
{
std::lock_guard<std::mutex> lock(look_mutex);
const auto frame=latest();
if(camera && fresh(*frame) && read(camera+0x30,original) && read(camera+0x40,original_position) && finite(original_position)) {
if(!was_looking) {saved_orientation=original;yaw=pitch=0;input::look_dx=0;input::look_dy=0;}
yaw=std::remainder(yaw+pending_orbit_yaw.exchange(0)*(input::look_sensitivity.load()/.15f),360.f);
pitch=std::clamp(pitch+pending_orbit_pitch.exchange(0)*(input::look_sensitivity.load()/.15f),-85.f,85.f);
replacement=turn(saved_orientation,yaw,pitch);
const auto position=orbit_position(frame->local.position,replacement,orbit_distance.load());
changed=write(camera+0x30,replacement);
if(changed)moved=write(camera+0x40,position);
}
was_looking=looking && camera;
}
original_camera(self,context,alpha);
if(changed) {
write(camera+0x30,original);
if(moved)write(camera+0x40,original_position);
}
}
inline float __fastcall time_detour(void* self,int ticks,float alpha) {
const int chosen=time_override.load();
return original_time(self,chosen>=0 && GetCurrentThreadId()==render_thread.load() ? chosen : ticks,alpha);
}
inline void initialize() {
bool update_ok=update_hook.install("client world context",client_update_signature,reinterpret_cast<void*>(&update_detour),reinterpret_cast<void**>(&original_update),true);
auto call=sigscan::find("E8 ?? ?? ?? ?? 45 31 E4 48 83 BE A8 01 00 00 00",true);
if(call) {
level_target=sigscan::resolve_rip(call,1,5);
if(MH_CreateHook(level_target,&level_detour,reinterpret_cast<void**>(&original_level))!=MH_OK) level_target=nullptr;
}
ready=update_ok && level_target && update_hook.set_enabled(true) && MH_EnableHook(level_target)==MH_OK;
auto active=sigscan::find(active_camera_signature,true);
if(active) {
DWORD64 image_base=0;
auto function=RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(active),&image_base,nullptr);
if(function) get_camera=reinterpret_cast<active_fn>(image_base+function->BeginAddress);
}
camera_ready=get_camera && camera_hook.install("camera matrices",camera_matrix_signature,reinterpret_cast<void*>(&camera_detour),reinterpret_cast<void**>(&original_camera),true) && camera_hook.set_enabled(true);
perspective_ready=perspective_hook.install("view perspective",perspective_signature,reinterpret_cast<void*>(&perspective_detour),reinterpret_cast<void**>(&original_perspective),true) && perspective_hook.set_enabled(true);
input::freelook_supported=camera_ready && perspective_ready;
time_ready=time_hook.install("visual time",time_signature,reinterpret_cast<void*>(&time_detour),reinterpret_cast<void**>(&original_time),true) && time_hook.set_enabled(true);
name_ready=name_hook.install("visual player name",name_signature,reinterpret_cast<void*>(&name_detour),reinterpret_cast<void**>(&original_name),true) && name_hook.set_enabled(true);
fog_ready=fog_hook.install("dimension fog color",fog_signature,reinterpret_cast<void*>(&fog_detour),reinterpret_cast<void**>(&original_fog),true) && fog_hook.set_enabled(true);
game::log(std::string("world modules: ")+(ready ? "ready" : "unavailable"));
}
}
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <d3d11.h>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <atomic>
#include "world.h"
#pragma comment(lib,"d3dcompiler.lib")
#pragma comment(lib,"d3d11.lib")
namespace world_filter {
using Microsoft::WRL::ComPtr;
inline std::atomic<bool> enabled{false};
inline std::atomic<uint32_t> tint{0xffffffff};
inline std::atomic<float> brightness{1};
inline ComPtr<ID3D11VertexShader> vs;
inline ComPtr<ID3D11PixelShader> ps;
inline ComPtr<ID3D11SamplerState> sampler;
inline ComPtr<ID3D11RasterizerState> raster;
inline ComPtr<ID3D11DepthStencilState> depth;
inline ComPtr<ID3D11Buffer> constants;
inline ComPtr<ID3D11Texture2D> copy;
inline ComPtr<ID3D11ShaderResourceView> view;
inline ID3D11Device* owner=nullptr;
inline bool initialize(ID3D11Device* device) {
if(owner==device && vs && ps && constants && sampler && raster && depth) return true;
owner=device;
const char* source=R"(
Texture2D image:register(t0);SamplerState sampleImage:register(s0);
cbuffer settings:register(b0){float4 color;float4 light;}
struct Vertex{float4 position:SV_POSITION;float2 uv:TEXCOORD0;};
Vertex vertex(uint id:SV_VertexID){Vertex v;v.uv=float2((id<<1)&2,id&2);v.position=float4(v.uv*float2(2,-2)+float2(-1,1),0,1);return v;}
float4 pixel(Vertex v):SV_TARGET{float4 c=image.Sample(sampleImage,v.uv);c.rgb*=lerp(float3(1,1,1),color.rgb,color.a)*light.x;return c;}
)";
ComPtr<ID3DBlob> vertex,pixel,error;
if(FAILED(D3DCompile(source,strlen(source),nullptr,nullptr,nullptr,"vertex","vs_4_0",0,0,&vertex,&error)) ||
FAILED(D3DCompile(source,strlen(source),nullptr,nullptr,nullptr,"pixel","ps_4_0",0,0,&pixel,&error))) return false;
if(FAILED(device->CreateVertexShader(vertex->GetBufferPointer(),vertex->GetBufferSize(),nullptr,&vs)) ||
FAILED(device->CreatePixelShader(pixel->GetBufferPointer(),pixel->GetBufferSize(),nullptr,&ps))) return false;
D3D11_SAMPLER_DESC sd{};sd.Filter=D3D11_FILTER_MIN_MAG_MIP_LINEAR;sd.AddressU=sd.AddressV=sd.AddressW=D3D11_TEXTURE_ADDRESS_CLAMP;sd.MaxLOD=D3D11_FLOAT32_MAX;
D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=true;
D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;
D3D11_BUFFER_DESC bd{};bd.ByteWidth=32;bd.Usage=D3D11_USAGE_DEFAULT;bd.BindFlags=D3D11_BIND_CONSTANT_BUFFER;
return SUCCEEDED(device->CreateSamplerState(&sd,&sampler)) && SUCCEEDED(device->CreateRasterizerState(&rs,&raster)) &&
SUCCEEDED(device->CreateDepthStencilState(&ds,&depth)) && SUCCEEDED(device->CreateBuffer(&bd,nullptr,&constants));
}
inline bool apply(ID3D11Device* device,ID3D11DeviceContext* context,ID3D11RenderTargetView* target) {
if(!enabled || !initialize(device)) return false;
ComPtr<ID3D11Resource> resource;target->GetResource(&resource);
ComPtr<ID3D11Texture2D> texture;if(FAILED(resource.As(&texture))) return false;
D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
D3D11_RENDER_TARGET_VIEW_DESC td{};target->GetDesc(&td);
if(desc.SampleDesc.Count!=1 || desc.ArraySize!=1 || desc.MipLevels!=1) return false;
D3D11_TEXTURE2D_DESC previous{};if(copy) copy->GetDesc(&previous);
if(!copy || previous.Width!=desc.Width || previous.Height!=desc.Height || previous.Format!=desc.Format) {
copy.Reset();view.Reset();desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;desc.CPUAccessFlags=0;desc.MiscFlags=0;desc.Usage=D3D11_USAGE_DEFAULT;
if(FAILED(device->CreateTexture2D(&desc,nullptr,&copy))) return false;
D3D11_SHADER_RESOURCE_VIEW_DESC srv{};srv.Format=td.Format;srv.ViewDimension=D3D11_SRV_DIMENSION_TEXTURE2D;srv.Texture2D.MipLevels=1;
if(FAILED(device->CreateShaderResourceView(copy.Get(),&srv,&view))) {copy.Reset();return false;}
}
context->CopyResource(copy.Get(),texture.Get());
ComPtr<ID3D11VertexShader> old_vs;ComPtr<ID3D11PixelShader> old_ps;ComPtr<ID3D11GeometryShader> old_gs;
ComPtr<ID3D11HullShader> old_hs;ComPtr<ID3D11DomainShader> old_ds;
ComPtr<ID3D11Buffer> old_cb;ComPtr<ID3D11ShaderResourceView> old_srv;ComPtr<ID3D11SamplerState> old_sampler;
ComPtr<ID3D11InputLayout> layout;ComPtr<ID3D11RasterizerState> old_rs;ComPtr<ID3D11DepthStencilState> old_depth;
ComPtr<ID3D11BlendState> blend;ComPtr<ID3D11DepthStencilView> dsv;
ID3D11RenderTargetView* targets[8]{};context->OMGetRenderTargets(8,targets,&dsv);
ID3D11ClassInstance* classes[5][256]{};UINT class_count[5]={256,256,256,256,256};
ComPtr<ID3D11DeviceContext1> extended;context->QueryInterface(IID_PPV_ARGS(&extended));
UINT first_constant=0,constant_count=0;
UINT stencil=0,mask=0,count=16;float factor[4]{};D3D11_VIEWPORT ports[16]{};D3D11_PRIMITIVE_TOPOLOGY topology;
context->VSGetShader(&old_vs,classes[0],&class_count[0]);context->PSGetShader(&old_ps,classes[1],&class_count[1]);context->GSGetShader(&old_gs,classes[2],&class_count[2]);
context->HSGetShader(&old_hs,classes[3],&class_count[3]);context->DSGetShader(&old_ds,classes[4],&class_count[4]);
if(extended) extended->PSGetConstantBuffers1(0,1,&old_cb,&first_constant,&constant_count);
else context->PSGetConstantBuffers(0,1,&old_cb);
context->PSGetShaderResources(0,1,&old_srv);context->PSGetSamplers(0,1,&old_sampler);
context->IAGetInputLayout(&layout);context->IAGetPrimitiveTopology(&topology);context->RSGetState(&old_rs);context->RSGetViewports(&count,ports);
context->OMGetDepthStencilState(&old_depth,&stencil);context->OMGetBlendState(&blend,factor,&mask);
const auto color=tint.load();float data[8]={float(color&255)/255,float((color>>8)&255)/255,float((color>>16)&255)/255,float(color>>24)/255,
brightness.load(),0,0,0};context->UpdateSubresource(constants.Get(),0,nullptr,data,0,0);
ID3D11Buffer* cb=constants.Get();ID3D11ShaderResourceView* srv=view.Get();ID3D11SamplerState* sm=sampler.Get();
D3D11_VIEWPORT port{0,0,float(desc.Width),float(desc.Height),0,1};
context->OMSetRenderTargets(1,&target,nullptr);context->OMSetDepthStencilState(depth.Get(),0);context->OMSetBlendState(nullptr,nullptr,0xffffffff);
context->RSSetState(raster.Get());context->RSSetViewports(1,&port);context->IASetInputLayout(nullptr);context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
context->VSSetShader(vs.Get(),nullptr,0);context->PSSetShader(ps.Get(),nullptr,0);context->GSSetShader(nullptr,nullptr,0);context->HSSetShader(nullptr,nullptr,0);context->DSSetShader(nullptr,nullptr,0);
context->PSSetConstantBuffers(0,1,&cb);context->PSSetShaderResources(0,1,&srv);context->PSSetSamplers(0,1,&sm);context->Draw(3,0);
srv=nullptr;context->PSSetShaderResources(0,1,&srv);
context->OMSetRenderTargets(8,targets,dsv.Get());context->OMSetDepthStencilState(old_depth.Get(),stencil);context->OMSetBlendState(blend.Get(),factor,mask);
context->RSSetState(old_rs.Get());context->RSSetViewports(count,ports);context->IASetInputLayout(layout.Get());context->IASetPrimitiveTopology(topology);
context->VSSetShader(old_vs.Get(),classes[0],class_count[0]);context->PSSetShader(old_ps.Get(),classes[1],class_count[1]);context->GSSetShader(old_gs.Get(),classes[2],class_count[2]);context->HSSetShader(old_hs.Get(),classes[3],class_count[3]);context->DSSetShader(old_ds.Get(),classes[4],class_count[4]);
cb=old_cb.Get();srv=old_srv.Get();sm=old_sampler.Get();
if(extended) extended->PSSetConstantBuffers1(0,1,&cb,&first_constant,&constant_count);
else context->PSSetConstantBuffers(0,1,&cb);
context->PSSetShaderResources(0,1,&srv);context->PSSetSamplers(0,1,&sm);
for(int stage=0;stage<5;++stage) for(UINT i=0;i<class_count[stage];++i) if(classes[stage][i]) classes[stage][i]->Release();
for(auto* rt:targets) if(rt) rt->Release();return true;
}
inline void shutdown() {enabled=false;vs.Reset();ps.Reset();sampler.Reset();raster.Reset();depth.Reset();constants.Reset();copy.Reset();view.Reset();owner=nullptr;}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <algorithm>
#include <cmath>
#include <string>
#include "imgui.h"
namespace world {
struct vec3 { float x = 0, y = 0, z = 0; };
struct quaternion { float x = 0, y = 0, z = 0, w = 1; };
inline bool finite(vec3 p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
inline float distance(vec3 a, vec3 b) { return std::sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z)); }
inline quaternion multiply(quaternion a, quaternion b) {
return {a.w*b.x+a.x*b.w+a.y*b.z-a.z*b.y, a.w*b.y-a.x*b.z+a.y*b.w+a.z*b.x,
a.w*b.z+a.x*b.y-a.y*b.x+a.z*b.w, a.w*b.w-a.x*b.x-a.y*b.y-a.z*b.z};
}
inline quaternion turn(quaternion q, float yaw, float pitch) {
constexpr float rad = 3.14159265359f / 360.f;
q = multiply(multiply({0, std::sin(-yaw*rad), 0, std::cos(yaw*rad)}, q),
{std::sin(-pitch*rad), 0, 0, std::cos(pitch*rad)});
const float length = std::sqrt(q.x*q.x+q.y*q.y+q.z*q.z+q.w*q.w);
if (!std::isfinite(length) || length < .01f) return {};
return {q.x/length,q.y/length,q.z/length,q.w/length};
}
inline vec3 camera_back(quaternion q) {
return {2*(q.x*q.z+q.w*q.y),2*(q.y*q.z-q.w*q.x),1-2*(q.x*q.x+q.y*q.y)};
}
inline vec3 orbit_position(vec3 pivot,quaternion orientation,float radius) {
const auto back=camera_back(orientation);
return {pivot.x+back.x*radius,pivot.y+back.y*radius,pivot.z+back.z*radius};
}
inline bool project(const float* matrix, vec3 camera, vec3 point, float fov_x, float fov_y, ImVec2 size, ImVec2& result) {
if (!finite(camera) || !finite(point) || size.x <= 0 || size.y <= 0) return false;
const vec3 p{point.x-camera.x,point.y-camera.y,point.z-camera.z};
const float x=matrix[0]*p.x+matrix[1]*p.y+matrix[2]*p.z+matrix[3];
const float y=matrix[4]*p.x+matrix[5]*p.y+matrix[6]*p.z+matrix[7];
const float z=matrix[8]*p.x+matrix[9]*p.y+matrix[10]*p.z+matrix[11];
if (!std::isfinite(z) || z >= -.02f || !std::isfinite(fov_x) || !std::isfinite(fov_y)) return false;
result = {size.x*.5f*(1+x/-z*fov_x), size.y*.5f*(1-y/-z*fov_y)};
return std::isfinite(result.x) && std::isfinite(result.y) && std::abs(result.x)<100000 && std::abs(result.y)<100000;
}
inline bool project_edge(const float* matrix,vec3 camera,vec3 a,vec3 b,float fov_x,float fov_y,ImVec2 size,ImVec2& first,ImVec2& second) {
const auto depth=[&](vec3 p){return matrix[8]*(p.x-camera.x)+matrix[9]*(p.y-camera.y)+matrix[10]*(p.z-camera.z)+matrix[11];};
float za=depth(a),zb=depth(b);constexpr float clip_plane=-.025f;
if(!std::isfinite(za) || !std::isfinite(zb) || (za>=clip_plane && zb>=clip_plane))return false;
if(za>=clip_plane || zb>=clip_plane) {
const float t=(clip_plane-za)/(zb-za);
const vec3 clipped{a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t,a.z+(b.z-a.z)*t};
if(za>=clip_plane)a=clipped;else b=clipped;
}
if(!project(matrix,camera,a,fov_x,fov_y,size,first) || !project(matrix,camera,b,fov_x,fov_y,size,second))return false;
return true;
}
inline std::string clean_name(const std::string& name) {
std::string result;
for (size_t i=0;i<name.size() && result.size()<96;++i) {
const auto c=static_cast<unsigned char>(name[i]);
if (c==0xc2 && i+2<name.size() && static_cast<unsigned char>(name[i+1])==0xa7) {i+=2;continue;}
if (c==0xa7 && i+1<name.size()) {++i;continue;}
if (c>=32 && c!=127) result+=name[i];
}
return result;
}
inline bool weapon(const std::string& name) {
return name.find("sword")!=std::string::npos || name.find("axe")!=std::string::npos && name.find("pickaxe")==std::string::npos ||
name.find("bow")!=std::string::npos || name.find("trident")!=std::string::npos || name.find("mace")!=std::string::npos || name.find("spear")!=std::string::npos;
}
inline std::string item_label(std::string name) {
if (auto colon=name.find(':');colon!=std::string::npos) name.erase(0,colon+1);
std::replace(name.begin(),name.end(),'_',' '); return name.empty() ? "empty" : name;
}
}