Загрузка данных


#include "Aimbot.hpp"

#ifdef USE_VMPROTECT
#include "VMProtectSDK.h"
#endif

__declspec(noinline) float GetSmoothStep(float SmoothFactor) {
    if (SmoothFactor > 0) {
        if (SmoothFactor >= 98 && SmoothFactor <= 100) return 0.5f  / SmoothFactor;
        if (SmoothFactor >= 80 && SmoothFactor < 98)  return 1.8f  / SmoothFactor;
        if (SmoothFactor >= 60 && SmoothFactor < 80)  return 2.0f  / SmoothFactor;
        if (SmoothFactor >= 40 && SmoothFactor < 60)  return 2.2f  / SmoothFactor;
        if (SmoothFactor >= 20 && SmoothFactor < 40)  return 2.5f  / SmoothFactor;
        return 3.0f / SmoothFactor;
    }
    return 1.0f;
}

// -----------------------------------------------------------------------
// Карта GTA5: X/Y ~[-10000, 10000], Z [-300, 3000].
// Защита от stale pointer — если позиция вышла за границы, указатель протух.
// -----------------------------------------------------------------------
static bool IsValidWorldPosition(const D3DXVECTOR3& pos)
{
    if (std::isnan(pos.x) || std::isnan(pos.y) || std::isnan(pos.z)) return false;
    if (std::isinf(pos.x) || std::isinf(pos.y) || std::isinf(pos.z)) return false;
    if (pos.x == 0.0f && pos.y == 0.0f && pos.z == 0.0f)             return false;
    if (pos.x < -10000.f || pos.x > 10000.f)                          return false;
    if (pos.y < -10000.f || pos.y > 10000.f)                          return false;
    if (pos.z <   -300.f || pos.z >  3000.f)                          return false;
    return true;
}

// -----------------------------------------------------------------------
// Возвращает указатель на активную камеру.
// Используется ТОЛЬКО для чтения позиции камеры при FOV-чеке в Start().
// Сначала проверяем ADS-камеру (+0x2D8), потом обычную (+0x2C0).
// -----------------------------------------------------------------------
uintptr_t Core::Features::cAimbot::GetActiveCamera()
{
    const uintptr_t base = Core::SDK::Pointers::pCamGamePlayDirector;

    const uintptr_t ADSCam    = Mem.Read<uintptr_t>(base + 0x2D8);
    const uintptr_t FollowCam = Mem.Read<uintptr_t>(base + 0x2C0);

    if (ADSCam)
    {
        const D3DXVECTOR3 pos = Mem.Read<D3DXVECTOR3>(ADSCam + 0x60);
        if (IsValidWorldPosition(pos))
            return ADSCam;
    }

    if (FollowCam)
    {
        const D3DXVECTOR3 pos = Mem.Read<D3DXVECTOR3>(FollowCam + 0x60);
        if (IsValidWorldPosition(pos))
            return FollowCam;
    }

    return 0;
}

// -----------------------------------------------------------------------
// SetViewAngles — теперь через SendInput (симуляция движения мыши).
//
// ПОЧЕМУ НЕ ПИШЕМ В ПАМЯТЬ КАМЕРЫ:
// +0x40 и +0x3D0 — это ВЫХОДНЫЕ регистры камерной системы GTA5.
// Движок перезаписывает их каждый кадр на основе своих внутренних углов.
// Любая наша запись туда уничтожается через ~1мс → дёргание → заморозка.
//
// SendInput(MOUSEEVENTF_MOVE) подаёт относительное движение мыши на том же
// уровне что и физическая мышь. Движок принимает его без конфликта,
// работает одинаково в 1-м лице / 3-м лице / ADS.
// -----------------------------------------------------------------------
void Core::Features::cAimbot::SetViewAngles(CPed* Ped, D3DXVECTOR3 BonePos)
{
#ifdef USE_VMPROTECT
    VMProtectBeginMutation("SetViewAngles");
#endif

    // Переводим 3D-позицию кости в 2D экранные координаты
    D3DXVECTOR2 ScreenBonePos = Core::SDK::Game::WorldToScreen(BonePos);

    if (!Core::SDK::Game::IsOnScreen(ScreenBonePos))
        return;

    // Дельта от центра экрана до цели (в пикселях)
    float dx = ScreenBonePos.x - g_Variables.g_vGameWindowCenter.x;
    float dy = ScreenBonePos.y - g_Variables.g_vGameWindowCenter.y;

    // Проверяем что цель вообще на экране с разумными координатами
    if (std::isnan(dx) || std::isnan(dy) || std::isinf(dx) || std::isinf(dy))
        return;

    // Применяем сглаживание: чем больше AimbotSpeed (0-100),
    // тем больше шаг за тик и тем резче наводка.
    // При AimbotSpeed=100 → step=0.005 (очень плавно)
    // При AimbotSpeed=1  → step=3.0   (почти мгновенно)
    const float SmoothFactor    = std::clamp(static_cast<float>(g_Config.Aimbot->AimbotSpeed), 0.0f, 100.0f);
    const float LocalSmoothStep = GetSmoothStep(SmoothFactor);

    const LONG moveX = static_cast<LONG>(dx * LocalSmoothStep);
    const LONG moveY = static_cast<LONG>(dy * LocalSmoothStep);

    // Если дельта меньше 1 пикселя — нечего двигать
    // (цель уже под прицелом)
    if (moveX == 0 && moveY == 0)
        return;

    INPUT input      = {};
    input.type       = INPUT_MOUSE;
    input.mi.dwFlags = MOUSEEVENTF_MOVE; // относительное движение
    input.mi.dx      = moveX;
    input.mi.dy      = moveY;

    SendInput(1, &input, sizeof(INPUT));

#ifdef USE_VMPROTECT
    VMProtectEnd();
#endif
}

void Core::Features::cAimbot::Start()
{
#ifdef USE_VMPROTECT
    VMProtectBeginMutation("AimbotLoop");
#endif

    uintptr_t LastKnownCam      = 0;
    auto      LastCamSwitchTime = std::chrono::steady_clock::now();
    const int CAM_COOLDOWN_MS   = 500;

    while (true)
    {
        if (g_Config.Aimbot->Enabled
            && g_Config.Aimbot->KeyBind
            && (GetAsyncKeyState(g_Config.Aimbot->KeyBind) & 0x8000)
            && GetForegroundWindow() != g_Variables.g_hCheatWindow)
        {
            // Детект смены камеры (нажатие V / переход в ADS)
            uintptr_t CurrentCam = GetActiveCamera();
            if (CurrentCam != LastKnownCam)
            {
                LastKnownCam      = CurrentCam;
                LastCamSwitchTime = std::chrono::steady_clock::now();
                std::this_thread::sleep_for(std::chrono::nanoseconds(1));
                continue;
            }

            // Пауза после смены — новый объект камеры инициализируется не мгновенно
            const auto msSinceSwitch = std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::steady_clock::now() - LastCamSwitchTime).count();

            if (msSinceSwitch < CAM_COOLDOWN_MS)
            {
                std::this_thread::sleep_for(std::chrono::nanoseconds(1));
                continue;
            }

            CPed* Ped = Core::SDK::Game::GetClosestPed(
                g_Config.Aimbot->MaxDistance,
                g_Config.Aimbot->IgnoreNPCs,
                g_Config.Aimbot->OnlyVisible);

            if (!Ped)
            {
                std::this_thread::sleep_for(std::chrono::nanoseconds(1));
                continue;
            }

            D3DXVECTOR3 HeadPos       = Ped->GetBonePosDefault(0 /*Head*/);
            D3DXVECTOR2 ScreenHeadPos = Core::SDK::Game::WorldToScreen(HeadPos);

            if (Core::SDK::Game::IsOnScreen(ScreenHeadPos))
            {
                const int Fov = static_cast<int>(std::hypot(
                    ScreenHeadPos.x - g_Variables.g_vGameWindowCenter.x,
                    ScreenHeadPos.y - g_Variables.g_vGameWindowCenter.y));

                if (Fov < g_Config.Aimbot->FOV)
                {
                    // +0.08f по Z — небольшой сдвиг вверх к центру черепа
                    SetViewAngles(Ped, HeadPos + D3DXVECTOR3(0, 0, 0.08f));
                }
            }
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(1));
    }

#ifdef USE_VMPROTECT
    VMProtectEnd();
#endif
}