Update Nemirtingas overlay to latest.

This commit is contained in:
Mr_Goldberg 2022-08-05 02:06:42 -04:00
parent df94c38b0f
commit c17fb0c931
No known key found for this signature in database
GPG key ID: 8597D87419DEF278
82 changed files with 48737 additions and 59872 deletions

View file

@ -1,146 +1,198 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "DX10_Hook.h"
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
#ifdef EMU_OVERLAY
#include <imgui.h>
#include <impls/windows/imgui_impl_dx10.h>
#include <backends/imgui_impl_dx10.h>
DX10_Hook* DX10_Hook::_inst = nullptr;
bool DX10_Hook::start_hook()
template<typename T>
inline void SafeRelease(T*& pUnk)
{
bool res = true;
if (!hooked)
if (pUnk != nullptr)
{
if (!Windows_Hook::Inst()->start_hook())
pUnk->Release();
pUnk = nullptr;
}
}
bool DX10_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
if (!_Hooked)
{
if (Present == nullptr || ResizeTarget == nullptr || ResizeBuffers == nullptr)
{
SPDLOG_WARN("Failed to hook DirectX 11: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
PRINT_DEBUG("Hooked DirectX 10\n");
hooked = true;
_WindowsHooked = true;
Renderer_Detector::Inst().renderer_found(this);
SPDLOG_INFO("Hooked DirectX 10");
_Hooked = true;
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)DX10_Hook::Present, &DX10_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)DX10_Hook::ResizeTarget, &DX10_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)DX10_Hook::ResizeBuffers, &DX10_Hook::MyResizeBuffers)
std::make_pair<void**, void*>(&(PVOID&)Present , &DX10_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)ResizeTarget , &DX10_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)ResizeBuffers, &DX10_Hook::MyResizeBuffers)
);
if (Present1 != nullptr)
{
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)Present1, &DX10_Hook::MyPresent1)
);
}
EndHook();
get_steam_client()->steam_overlay->HookReady();
}
return res;
return true;
}
void DX10_Hook::resetRenderState()
bool DX10_Hook::IsStarted()
{
if (initialized)
return _Hooked;
}
void DX10_Hook::_ResetRenderState()
{
if (_Initialized)
{
mainRenderTargetView->Release();
OverlayHookReady(false);
ImGui_ImplDX10_Shutdown();
Windows_Hook::Inst()->resetRenderState();
Windows_Hook::Inst()->_ResetRenderState();
ImGui::DestroyContext();
initialized = false;
SafeRelease(mainRenderTargetView);
SafeRelease(pDevice);
_Initialized = false;
}
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void DX10_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
void DX10_Hook::_PrepareForOverlay(IDXGISwapChain* pSwapChain)
{
DXGI_SWAP_CHAIN_DESC desc;
pSwapChain->GetDesc(&desc);
if (!initialized)
if (!_Initialized)
{
if (FAILED(pSwapChain->GetDevice(IID_PPV_ARGS(&pDevice))))
return;
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
ID3D10Texture2D* pBackBuffer;
ID3D10Texture2D* pBackBuffer = nullptr;
pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
pDevice->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView);
if (pBackBuffer == nullptr)
{
pDevice->Release();
return;
}
pDevice->CreateRenderTargetView(pBackBuffer, nullptr, &mainRenderTargetView);
pBackBuffer->Release();
ImGui::CreateContext();
ImGui_ImplDX10_Init(pDevice);
pDevice->Release();
get_steam_client()->steam_overlay->CreateFonts();
initialized = true;
_Initialized = true;
OverlayHookReady(true);
}
if (ImGui_ImplDX10_NewFrame())
if (ImGui_ImplDX10_NewFrame() && Windows_Hook::Inst()->_PrepareForOverlay(desc.OutputWindow))
{
Windows_Hook::Inst()->prepareForOverlay(desc.OutputWindow);
ImGui::NewFrame();
get_steam_client()->steam_overlay->OverlayProc();
OverlayProc();
ImGui::Render();
pDevice->OMSetRenderTargets(1, &mainRenderTargetView, NULL);
pDevice->OMSetRenderTargets(1, &mainRenderTargetView, nullptr);
ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData());
}
}
HRESULT STDMETHODCALLTYPE DX10_Hook::MyPresent(IDXGISwapChain *_this, UINT SyncInterval, UINT Flags)
{
DX10_Hook::Inst()->prepareForOverlay(_this);
return (_this->*DX10_Hook::Inst()->Present)(SyncInterval, Flags);
auto inst= DX10_Hook::Inst();
inst->_PrepareForOverlay(_this);
return (_this->*inst->Present)(SyncInterval, Flags);
}
HRESULT STDMETHODCALLTYPE DX10_Hook::MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters)
{
DX10_Hook::Inst()->resetRenderState();
return (_this->*DX10_Hook::Inst()->ResizeTarget)(pNewTargetParameters);
auto inst= DX10_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeTarget)(pNewTargetParameters);
}
HRESULT STDMETHODCALLTYPE DX10_Hook::MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags)
{
DX10_Hook::Inst()->resetRenderState();
return (_this->*DX10_Hook::Inst()->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
auto inst= DX10_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
}
HRESULT STDMETHODCALLTYPE DX10_Hook::MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters)
{
auto inst = DX10_Hook::Inst();
inst->_PrepareForOverlay(_this);
return (_this->*inst->Present1)(SyncInterval, Flags, pPresentParameters);
}
DX10_Hook::DX10_Hook():
initialized(false),
hooked(false),
_Initialized(false),
_Hooked(false),
_WindowsHooked(false),
pDevice(nullptr),
mainRenderTargetView(nullptr),
Present(nullptr),
ResizeBuffers(nullptr),
ResizeTarget(nullptr)
ResizeTarget(nullptr),
Present1(nullptr)
{
_library = LoadLibrary(DX10_DLL);
}
DX10_Hook::~DX10_Hook()
{
PRINT_DEBUG("DX10 Hook removed\n");
//SPDLOG_INFO("DX10 Hook removed");
if (initialized)
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
mainRenderTargetView->Release();
ImGui_ImplDX10_InvalidateDeviceObjects();
ImGui::DestroyContext();
initialized = false;
_Initialized = false;
}
FreeLibrary(reinterpret_cast<HMODULE>(_library));
_inst = nullptr;
}
@ -152,21 +204,85 @@ DX10_Hook* DX10_Hook::Inst()
return _inst;
}
const char* DX10_Hook::get_lib_name() const
std::string DX10_Hook::GetLibraryName() const
{
return DX10_DLL;
return LibraryName;
}
void DX10_Hook::loadFunctions(IDXGISwapChain *pSwapChain)
void DX10_Hook::LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(Present1) Present1Fcn)
{
void** vTable;
vTable = *reinterpret_cast<void***>(pSwapChain);
#define LOAD_FUNC(X) (void*&)X = vTable[(int)IDXGISwapChainVTable::X]
LOAD_FUNC(Present);
LOAD_FUNC(ResizeBuffers);
LOAD_FUNC(ResizeTarget);
#undef LOAD_FUNC
Present = PresentFcn;
ResizeBuffers = ResizeBuffersFcn;
ResizeTarget = ResizeTargetFcn;
Present1 = Present1Fcn;
}
#endif//EMU_OVERLAY
std::weak_ptr<uint64_t> DX10_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
ID3D10ShaderResourceView** resource = new ID3D10ShaderResourceView*(nullptr);
// Create texture
D3D10_TEXTURE2D_DESC desc = {};
desc.Width = static_cast<UINT>(width);
desc.Height = static_cast<UINT>(height);
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D10_USAGE_DEFAULT;
desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D10Texture2D* pTexture = nullptr;
D3D10_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
pDevice->CreateTexture2D(&desc, &subResource, &pTexture);
if (pTexture != nullptr)
{
// Create texture view
D3D10_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
pDevice->CreateShaderResourceView(pTexture, &srvDesc, resource);
// Release Texure, the shader resource increases the reference count.
pTexture->Release();
}
if (*resource == nullptr)
return std::shared_ptr<uint64_t>();
auto ptr = std::shared_ptr<uint64_t>((uint64_t*)resource, [](uint64_t* handle)
{
if (handle != nullptr)
{
ID3D10ShaderResourceView** resource = reinterpret_cast<ID3D10ShaderResourceView**>(handle);
(*resource)->Release();
delete resource;
}
});
_ImageResources.emplace(ptr);
return ptr;
}
void DX10_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
auto ptr = resource.lock();
if (ptr)
{
auto it = _ImageResources.find(ptr);
if (it != _ImageResources.end())
_ImageResources.erase(it);
}
}

View file

@ -1,51 +1,80 @@
#ifndef __INCLUDED_DX10_HOOK_H__
#define __INCLUDED_DX10_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#ifdef EMU_OVERLAY
#pragma once
#include "../internal_includes.h"
#include <d3d10.h>
#include "DirectX_VTables.h"
#include <dxgi1_2.h>
class DX10_Hook : public Base_Hook
class DX10_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
#define DX10_DLL "d3d10.dll"
static constexpr const char *DLL_NAME = "d3d10.dll";
private:
static DX10_Hook* _inst;
// Variables
bool hooked;
bool initialized;
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
ID3D10Device* pDevice;
ID3D10RenderTargetView* mainRenderTargetView;
std::set<std::shared_ptr<uint64_t>> _ImageResources;
// Functions
DX10_Hook();
void resetRenderState();
void prepareForOverlay(IDXGISwapChain *pSwapChain);
void _ResetRenderState();
void _PrepareForOverlay(IDXGISwapChain *pSwapChain);
// Hook to render functions
static HRESULT STDMETHODCALLTYPE MyPresent(IDXGISwapChain* _this, UINT SyncInterval, UINT Flags);
static HRESULT STDMETHODCALLTYPE MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters);
static HRESULT STDMETHODCALLTYPE MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags);
static HRESULT STDMETHODCALLTYPE MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters);
decltype(&IDXGISwapChain::Present) Present;
decltype(&IDXGISwapChain::ResizeBuffers) ResizeBuffers;
decltype(&IDXGISwapChain::ResizeTarget) ResizeTarget;
decltype(&IDXGISwapChain1::Present1) Present1;
public:
std::string LibraryName;
virtual ~DX10_Hook();
bool start_hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static DX10_Hook* Inst();
virtual const char* get_lib_name() const;
virtual std::string GetLibraryName() const;
void loadFunctions(IDXGISwapChain *pSwapChain);
void LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(Present1) Present1Fcn);
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};
#endif//EMU_OVERLAY
#endif//__INCLUDED_DX10_HOOK_H__

View file

@ -1,16 +1,41 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "DX11_Hook.h"
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
#ifdef EMU_OVERLAY
#include <imgui.h>
#include <impls/windows/imgui_impl_dx11.h>
#include <backends/imgui_impl_dx11.h>
DX11_Hook* DX11_Hook::_inst = nullptr;
HRESULT GetDeviceAndCtxFromSwapchain(IDXGISwapChain* pSwapChain, ID3D11Device** ppDevice, ID3D11DeviceContext** ppContext)
template<typename T>
inline void SafeRelease(T*& pUnk)
{
if (pUnk != nullptr)
{
pUnk->Release();
pUnk = nullptr;
}
}
static HRESULT GetDeviceAndCtxFromSwapchain(IDXGISwapChain* pSwapChain, ID3D11Device** ppDevice, ID3D11DeviceContext** ppContext)
{
HRESULT ret = pSwapChain->GetDevice(IID_PPV_ARGS(ppDevice));
@ -20,177 +45,192 @@ HRESULT GetDeviceAndCtxFromSwapchain(IDXGISwapChain* pSwapChain, ID3D11Device**
return ret;
}
bool DX11_Hook::start_hook()
bool DX11_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
bool res = true;
if (!hooked)
if (!_Hooked)
{
if (!Windows_Hook::Inst()->start_hook())
if (Present == nullptr || ResizeTarget == nullptr || ResizeBuffers == nullptr)
{
SPDLOG_WARN("Failed to hook DirectX 11: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
PRINT_DEBUG("Hooked DirectX 11\n");
hooked = true;
_WindowsHooked = true;
Renderer_Detector::Inst().renderer_found(this);
SPDLOG_INFO("Hooked DirectX 11");
_Hooked = true;
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)DX11_Hook::Present, &DX11_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)DX11_Hook::ResizeTarget, &DX11_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)DX11_Hook::ResizeBuffers, &DX11_Hook::MyResizeBuffers)
std::make_pair<void**, void*>(&(PVOID&)Present , &DX11_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)ResizeTarget , &DX11_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)ResizeBuffers, &DX11_Hook::MyResizeBuffers)
);
if (Present1 != nullptr)
{
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)Present1, &DX11_Hook::MyPresent1)
);
}
EndHook();
get_steam_client()->steam_overlay->HookReady();
}
return res;
return true;
}
void DX11_Hook::resetRenderState()
bool DX11_Hook::IsStarted()
{
if (initialized)
{
if (mainRenderTargetView) {
mainRenderTargetView->Release();
mainRenderTargetView = NULL;
}
return _Hooked;
}
pContext->Release();
void DX11_Hook::_ResetRenderState()
{
if (_Initialized)
{
OverlayHookReady(false);
ImGui_ImplDX11_Shutdown();
Windows_Hook::Inst()->resetRenderState();
ImGui::DestroyContext();
Windows_Hook::Inst()->_ResetRenderState();
//ImGui::DestroyContext();
initialized = false;
SafeRelease(mainRenderTargetView);
SafeRelease(pContext);
SafeRelease(pDevice);
_Initialized = false;
}
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void DX11_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
void DX11_Hook::_PrepareForOverlay(IDXGISwapChain* pSwapChain)
{
DXGI_SWAP_CHAIN_DESC desc;
pSwapChain->GetDesc(&desc);
if (!initialized)
if (!_Initialized)
{
ID3D11Device* pDevice = nullptr;
pDevice = nullptr;
if (FAILED(GetDeviceAndCtxFromSwapchain(pSwapChain, &pDevice, &pContext)))
return;
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
ID3D11Texture2D* pBackBuffer;
pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
ID3D11RenderTargetView *get_targets[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = {};
pContext->OMGetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, get_targets, NULL);
bool bind_target = true;
for (unsigned i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) {
if (get_targets[i]) {
ID3D11Resource *res = NULL;
get_targets[i]->GetResource(&res);
if (res) {
if (res == (ID3D11Resource*)pBackBuffer) {
bind_target = false;
}
res->Release();
}
get_targets[i]->Release();
} else {
break;
}
}
if (bind_target) {
pDevice->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView);
}
pBackBuffer->Release();
pDevice->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView);
//ID3D11RenderTargetView* targets[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = {};
//pContext->OMGetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, NULL);
//bool bind_target = true;
//
//for (unsigned i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT && targets[i] != nullptr; ++i)
//{
// ID3D11Resource* res = NULL;
// targets[i]->GetResource(&res);
// if (res)
// {
// if (res == (ID3D11Resource*)pBackBuffer)
// {
// pDevice->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView);
// }
//
// res->Release();
// }
//
// targets[i]->Release();
//}
SafeRelease(pBackBuffer);
if (mainRenderTargetView == nullptr)
return;
if(ImGui::GetCurrentContext() == nullptr)
ImGui::CreateContext();
ImGui_ImplDX11_Init(pDevice, pContext);
pDevice->Release();
get_steam_client()->steam_overlay->CreateFonts();
initialized = true;
_Initialized = true;
OverlayHookReady(true);
}
if (ImGui_ImplDX11_NewFrame())
if (ImGui_ImplDX11_NewFrame() && Windows_Hook::Inst()->_PrepareForOverlay(desc.OutputWindow))
{
Windows_Hook::Inst()->prepareForOverlay(desc.OutputWindow);
ImGui::NewFrame();
get_steam_client()->steam_overlay->OverlayProc();
OverlayProc();
ImGui::Render();
if (mainRenderTargetView) {
if (mainRenderTargetView)
{
pContext->OMSetRenderTargets(1, &mainRenderTargetView, NULL);
}
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
}
HRESULT STDMETHODCALLTYPE DX11_Hook::MyPresent(IDXGISwapChain *_this, UINT SyncInterval, UINT Flags)
{
DX11_Hook::Inst()->prepareForOverlay(_this);
return (_this->*DX11_Hook::Inst()->Present)(SyncInterval, Flags);
auto inst = DX11_Hook::Inst();
inst->_PrepareForOverlay(_this);
return (_this->*inst->Present)(SyncInterval, Flags);
}
HRESULT STDMETHODCALLTYPE DX11_Hook::MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters)
{
DX11_Hook::Inst()->resetRenderState();
return (_this->*DX11_Hook::Inst()->ResizeTarget)(pNewTargetParameters);
auto inst = DX11_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeTarget)(pNewTargetParameters);
}
HRESULT STDMETHODCALLTYPE DX11_Hook::MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags)
{
DX11_Hook::Inst()->resetRenderState();
return (_this->*DX11_Hook::Inst()->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
auto inst = DX11_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
}
HRESULT STDMETHODCALLTYPE DX11_Hook::MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters)
{
auto inst = DX11_Hook::Inst();
inst->_PrepareForOverlay(_this);
return (_this->*inst->Present1)(SyncInterval, Flags, pPresentParameters);
}
DX11_Hook::DX11_Hook():
initialized(false),
hooked(false),
_Initialized(false),
_Hooked(false),
_WindowsHooked(false),
pContext(nullptr),
mainRenderTargetView(nullptr),
Present(nullptr),
ResizeBuffers(nullptr),
ResizeTarget(nullptr)
ResizeTarget(nullptr),
Present1(nullptr)
{
_library = LoadLibrary(DX11_DLL);
}
DX11_Hook::~DX11_Hook()
{
PRINT_DEBUG("DX11 Hook removed\n");
SPDLOG_INFO("DX11 Hook removed");
if (initialized)
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
if (mainRenderTargetView) {
mainRenderTargetView->Release();
mainRenderTargetView = NULL;
}
pContext->Release();
SafeRelease(mainRenderTargetView);
SafeRelease(pContext);
ImGui_ImplDX11_InvalidateDeviceObjects();
ImGui::DestroyContext();
initialized = false;
_Initialized = false;
}
FreeLibrary(reinterpret_cast<HMODULE>(_library));
_inst = nullptr;
}
@ -202,21 +242,85 @@ DX11_Hook* DX11_Hook::Inst()
return _inst;
}
const char* DX11_Hook::get_lib_name() const
std::string DX11_Hook::GetLibraryName() const
{
return DX11_DLL;
return LibraryName;
}
void DX11_Hook::loadFunctions(IDXGISwapChain *pSwapChain)
void DX11_Hook::LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(Present1) Present1Fcn)
{
void** vTable;
vTable = *reinterpret_cast<void***>(pSwapChain);
#define LOAD_FUNC(X) (void*&)X = vTable[(int)IDXGISwapChainVTable::X]
LOAD_FUNC(Present);
LOAD_FUNC(ResizeBuffers);
LOAD_FUNC(ResizeTarget);
#undef LOAD_FUNC
Present = PresentFcn;
ResizeBuffers = ResizeBuffersFcn;
ResizeTarget = ResizeTargetFcn;
Present1 = Present1Fcn;
}
#endif//EMU_OVERLAY
std::weak_ptr<uint64_t> DX11_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
ID3D11ShaderResourceView** resource = new ID3D11ShaderResourceView*(nullptr);
// Create texture
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = static_cast<UINT>(width);
desc.Height = static_cast<UINT>(height);
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_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D* pTexture = nullptr;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = image_data;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
pDevice->CreateTexture2D(&desc, &subResource, &pTexture);
if (pTexture != nullptr)
{
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{};
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
pDevice->CreateShaderResourceView(pTexture, &srvDesc, resource);
// Release Texture, the shader resource increases the reference count.
pTexture->Release();
}
if (*resource == nullptr)
return std::shared_ptr<uint64_t>();
auto ptr = std::shared_ptr<uint64_t>((uint64_t*)resource, [](uint64_t* handle)
{
if(handle != nullptr)
{
ID3D11ShaderResourceView** resource = reinterpret_cast<ID3D11ShaderResourceView**>(handle);
(*resource)->Release();
delete resource;
}
});
_ImageResources.emplace(ptr);
return ptr;
}
void DX11_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
auto ptr = resource.lock();
if (ptr)
{
auto it = _ImageResources.find(ptr);
if (it != _ImageResources.end())
_ImageResources.erase(it);
}
}

View file

@ -1,51 +1,81 @@
#ifndef __INCLUDED_DX11_HOOK_H__
#define __INCLUDED_DX11_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#ifdef EMU_OVERLAY
#pragma once
#include "../internal_includes.h"
#include <d3d11.h>
#include "DirectX_VTables.h"
#include <dxgi1_2.h>
class DX11_Hook : public Base_Hook
class DX11_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
#define DX11_DLL "d3d11.dll"
static constexpr const char *DLL_NAME = "d3d11.dll";
private:
static DX11_Hook* _inst;
// Variables
bool hooked;
bool initialized;
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
ID3D11Device* pDevice;
ID3D11DeviceContext* pContext;
ID3D11RenderTargetView* mainRenderTargetView;
std::set<std::shared_ptr<uint64_t>> _ImageResources;
// Functions
DX11_Hook();
void resetRenderState();
void prepareForOverlay(IDXGISwapChain* pSwapChain);
void _ResetRenderState();
void _PrepareForOverlay(IDXGISwapChain* pSwapChain);
// Hook to render functions
static HRESULT STDMETHODCALLTYPE MyPresent(IDXGISwapChain* _this, UINT SyncInterval, UINT Flags);
static HRESULT STDMETHODCALLTYPE MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters);
static HRESULT STDMETHODCALLTYPE MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags);
static HRESULT STDMETHODCALLTYPE MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters);
decltype(&IDXGISwapChain::Present) Present;
decltype(&IDXGISwapChain::ResizeBuffers) ResizeBuffers;
decltype(&IDXGISwapChain::ResizeTarget) ResizeTarget;
decltype(&IDXGISwapChain1::Present1) Present1;
public:
std::string LibraryName;
virtual ~DX11_Hook();
bool start_hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static DX11_Hook* Inst();
virtual const char* get_lib_name() const;
virtual std::string GetLibraryName() const;
void loadFunctions(IDXGISwapChain *pSwapChain);
void LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(Present1) Present1Fcn);
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};
#endif//EMU_OVERLAY
#endif//__INCLUDED_DX11_HOOK_H__

View file

@ -1,74 +1,161 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "DX12_Hook.h"
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
#ifdef EMU_OVERLAY
#include <imgui.h>
#include <impls/windows/imgui_impl_dx12.h>
#include <dxgi1_4.h>
#include <backends/imgui_impl_dx12.h>
DX12_Hook* DX12_Hook::_inst = nullptr;
bool DX12_Hook::start_hook()
template<typename T>
inline void SafeRelease(T*& pUnk)
{
bool res = true;
if (!hooked)
if (pUnk != nullptr)
{
if (!Windows_Hook::Inst()->start_hook())
pUnk->Release();
pUnk = nullptr;
}
}
bool DX12_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
if (!_Hooked)
{
if (Present == nullptr || ResizeTarget == nullptr || ResizeBuffers == nullptr || ExecuteCommandLists == nullptr)
{
SPDLOG_WARN("Failed to hook DirectX 12: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
PRINT_DEBUG("Hooked DirectX 12\n");
hooked = true;
_WindowsHooked = true;
Renderer_Detector::Inst().renderer_found(this);
SPDLOG_INFO("Hooked DirectX 12");
_Hooked = true;
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)DX12_Hook::Present, &DX12_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)DX12_Hook::ResizeTarget, &DX12_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)DX12_Hook::ResizeBuffers, &DX12_Hook::MyResizeBuffers),
std::make_pair<void**, void*>(&(PVOID&)DX12_Hook::ExecuteCommandLists, &DX12_Hook::MyExecuteCommandLists)
std::make_pair<void**, void*>(&(PVOID&)Present , &DX12_Hook::MyPresent),
std::make_pair<void**, void*>(&(PVOID&)ResizeTarget , &DX12_Hook::MyResizeTarget),
std::make_pair<void**, void*>(&(PVOID&)ResizeBuffers , &DX12_Hook::MyResizeBuffers),
std::make_pair<void**, void*>(&(PVOID&)ExecuteCommandLists, &DX12_Hook::MyExecuteCommandLists)
);
if (Present1 != nullptr)
{
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)Present1, &DX12_Hook::MyPresent1)
);
}
EndHook();
get_steam_client()->steam_overlay->HookReady();
}
return res;
return true;
}
void DX12_Hook::resetRenderState()
bool DX12_Hook::IsStarted()
{
if (initialized)
return _Hooked;
}
//DX12_Hook::heap_t DX12_Hook::get_free_texture_heap()
//{
// int64_t i;
// std::vector<bool>::reference* free_heap;
// for (i = 0; i < srvDescHeapBitmap.size(); ++i)
// {
// if (!srvDescHeapBitmap[i])
// {
// srvDescHeapBitmap[i] = true;
// break;
// }
// }
//
// if (i == srvDescHeapBitmap.size())
// return heap_t{ {}, {}, -1 };
//
// UINT inc = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
//
// return heap_t{
// pSrvDescHeap->GetGPUDescriptorHandleForHeapStart().ptr + inc * i,
// pSrvDescHeap->GetCPUDescriptorHandleForHeapStart().ptr + inc * i,
// i
// };
//}
//
//bool DX12_Hook::release_texture_heap(int64_t heap_id)
//{
// srvDescHeapBitmap[heap_id] = false;
// return true;
//}
ID3D12CommandQueue* DX12_Hook::_FindCommandQueueFromSwapChain(IDXGISwapChain* pSwapChain)
{
ID3D12CommandQueue* pCommandQueue = nullptr;
if (CommandQueueOffset == 0 && pCmdQueue != nullptr)
{
pSrvDescHeap->Release();
for (UINT i = 0; i < bufferCount; ++i)
for (size_t i = 0; i < 1024; ++i)
{
pCmdAlloc[i]->Release();
pBackBuffer[i]->Release();
if (*reinterpret_cast<ID3D12CommandQueue**>(reinterpret_cast<uintptr_t>(pSwapChain) + i) == pCmdQueue)
{
SPDLOG_INFO("Found IDXGISwapChain::ppCommandQueue at offset {}.", i);
CommandQueueOffset = i;
break;
}
}
pRtvDescHeap->Release();
delete[]pCmdAlloc;
delete[]pBackBuffer;
}
if (CommandQueueOffset != 0)
pCommandQueue = *reinterpret_cast<ID3D12CommandQueue**>(reinterpret_cast<uintptr_t>(pSwapChain) + CommandQueueOffset);
return pCommandQueue;
}
void DX12_Hook::_ResetRenderState()
{
if (_Initialized)
{
OverlayHookReady(false);
ImGui_ImplDX12_Shutdown();
Windows_Hook::Inst()->resetRenderState();
Windows_Hook::Inst()->_ResetRenderState();
ImGui::DestroyContext();
initialized = false;
OverlayFrames.clear();
SafeRelease(pSrvDescHeap);
SafeRelease(pRtvDescHeap);
SafeRelease(pDevice);
_Initialized = false;
}
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void DX12_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
void DX12_Hook::_PrepareForOverlay(IDXGISwapChain* pSwapChain, ID3D12CommandQueue* pCommandQueue)
{
if (pCmdQueue == nullptr)
if (pCommandQueue == nullptr)
return;
ID3D12CommandQueue* pCmdQueue = this->pCmdQueue;
IDXGISwapChain3* pSwapChain3 = nullptr;
DXGI_SWAP_CHAIN_DESC sc_desc;
pSwapChain->QueryInterface(IID_PPV_ARGS(&pSwapChain3));
@ -77,21 +164,24 @@ void DX12_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
pSwapChain3->GetDesc(&sc_desc);
if (!initialized)
if (!_Initialized)
{
UINT bufferIndex = pSwapChain3->GetCurrentBackBufferIndex();
ID3D12Device* pDevice;
pDevice = nullptr;
if (pSwapChain3->GetDevice(IID_PPV_ARGS(&pDevice)) != S_OK)
return;
bufferCount = sc_desc.BufferCount;
UINT bufferCount = sc_desc.BufferCount;
mainRenderTargets.clear();
//srvDescHeapBitmap.clear();
//constexpr UINT descriptor_count = 1024;
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
desc.NumDescriptors = 1;
//desc.NumDescriptors = descriptor_count;
desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
if (pDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&pSrvDescHeap)) != S_OK)
{
@ -100,6 +190,9 @@ void DX12_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
return;
}
}
//srvDescHeapBitmap.resize(descriptor_count, false);
{
D3D12_DESCRIPTOR_HEAP_DESC desc = {};
desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
@ -116,88 +209,92 @@ void DX12_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
SIZE_T rtvDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = pRtvDescHeap->GetCPUDescriptorHandleForHeapStart();
pCmdAlloc = new ID3D12CommandAllocator * [bufferCount];
for (int i = 0; i < bufferCount; ++i)
ID3D12CommandAllocator* pCmdAlloc;
ID3D12Resource* pBackBuffer;
for (UINT i = 0; i < bufferCount; ++i)
{
mainRenderTargets.push_back(rtvHandle);
pCmdAlloc = nullptr;
pBackBuffer = nullptr;
if (pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&pCmdAlloc)) != S_OK || pCmdAlloc == nullptr)
{
OverlayFrames.clear();
pSrvDescHeap->Release();
pRtvDescHeap->Release();
pDevice->Release();
pSwapChain3->Release();
return;
}
if (i == 0)
{
if (pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, pCmdAlloc, NULL, IID_PPV_ARGS(&pCmdList)) != S_OK ||
pCmdList == nullptr || pCmdList->Close() != S_OK)
{
OverlayFrames.clear();
SafeRelease(pCmdList);
pCmdAlloc->Release();
pSrvDescHeap->Release();
pRtvDescHeap->Release();
pDevice->Release();
pSwapChain3->Release();
return;
}
}
if (pSwapChain3->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer)) != S_OK || pBackBuffer == nullptr)
{
OverlayFrames.clear();
pCmdList->Release();
pCmdAlloc->Release();
pSrvDescHeap->Release();
pRtvDescHeap->Release();
pDevice->Release();
pSwapChain3->Release();
return;
}
pDevice->CreateRenderTargetView(pBackBuffer, NULL, rtvHandle);
OverlayFrames.emplace_back(rtvHandle, pCmdAlloc, pBackBuffer);
rtvHandle.ptr += rtvDescriptorSize;
}
}
for (UINT i = 0; i < sc_desc.BufferCount; ++i)
{
if (pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&pCmdAlloc[i])) != S_OK)
{
pDevice->Release();
pSwapChain3->Release();
pSrvDescHeap->Release();
for (UINT j = 0; j < i; ++j)
{
pCmdAlloc[j]->Release();
}
pRtvDescHeap->Release();
delete[]pCmdAlloc;
return;
}
}
if (pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, pCmdAlloc[0], NULL, IID_PPV_ARGS(&pCmdList)) != S_OK ||
pCmdList->Close() != S_OK)
{
pDevice->Release();
pSwapChain3->Release();
pSrvDescHeap->Release();
for (UINT i = 0; i < bufferCount; ++i)
pCmdAlloc[i]->Release();
pRtvDescHeap->Release();
delete[]pCmdAlloc;
return;
}
pBackBuffer = new ID3D12Resource * [bufferCount];
for (UINT i = 0; i < bufferCount; i++)
{
pSwapChain3->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer[i]));
pDevice->CreateRenderTargetView(pBackBuffer[i], NULL, mainRenderTargets[i]);
}
//auto heaps = std::move(get_free_texture_heap());
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
ImGui_ImplDX12_Init(pDevice, bufferCount, DXGI_FORMAT_R8G8B8A8_UNORM, NULL,
ImGui_ImplDX12_Init(pDevice, bufferCount, DXGI_FORMAT_R8G8B8A8_UNORM, pSrvDescHeap,
pSrvDescHeap->GetCPUDescriptorHandleForHeapStart(),
pSrvDescHeap->GetGPUDescriptorHandleForHeapStart());
//heaps.cpu_handle,
//heaps.gpu_handle);
get_steam_client()->steam_overlay->CreateFonts();
initialized = true;
pDevice->Release();
_Initialized = true;
OverlayHookReady(true);
}
if (ImGui_ImplDX12_NewFrame())
{
Windows_Hook::Inst()->prepareForOverlay(sc_desc.OutputWindow);
if (ImGui_ImplDX12_NewFrame() && Windows_Hook::Inst()->_PrepareForOverlay(sc_desc.OutputWindow))
{
ImGui::NewFrame();
get_steam_client()->steam_overlay->OverlayProc();
OverlayProc();
UINT bufferIndex = pSwapChain3->GetCurrentBackBufferIndex();
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = pBackBuffer[bufferIndex];
barrier.Transition.pResource = OverlayFrames[bufferIndex].pBackBuffer;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
pCmdAlloc[bufferIndex]->Reset();
pCmdList->Reset(pCmdAlloc[bufferIndex], NULL);
OverlayFrames[bufferIndex].pCmdAlloc->Reset();
pCmdList->Reset(OverlayFrames[bufferIndex].pCmdAlloc, NULL);
pCmdList->ResourceBarrier(1, &barrier);
pCmdList->OMSetRenderTargets(1, &mainRenderTargets[bufferIndex], FALSE, NULL);
pCmdList->OMSetRenderTargets(1, &OverlayFrames[bufferIndex].RenderTarget, FALSE, NULL);
pCmdList->SetDescriptorHeaps(1, &pSrvDescHeap);
ImGui::Render();
@ -208,81 +305,98 @@ void DX12_Hook::prepareForOverlay(IDXGISwapChain* pSwapChain)
pCmdList->ResourceBarrier(1, &barrier);
pCmdList->Close();
pCmdQueue->ExecuteCommandLists(1, (ID3D12CommandList**)&pCmdList);
pCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&pCmdList);
}
pSwapChain3->Release();
}
HRESULT STDMETHODCALLTYPE DX12_Hook::MyPresent(IDXGISwapChain *_this, UINT SyncInterval, UINT Flags)
{
DX12_Hook::Inst()->prepareForOverlay(_this);
auto inst = DX12_Hook::Inst();
return (_this->*DX12_Hook::Inst()->Present)(SyncInterval, Flags);
ID3D12CommandQueue* pCommandQueue = inst->_FindCommandQueueFromSwapChain(_this);
if (pCommandQueue != nullptr)
{
inst->_PrepareForOverlay(_this, pCommandQueue);
}
return (_this->*inst->Present)(SyncInterval, Flags);
}
HRESULT STDMETHODCALLTYPE DX12_Hook::MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters)
{
DX12_Hook::Inst()->resetRenderState();
return (_this->*DX12_Hook::Inst()->ResizeTarget)(pNewTargetParameters);
auto inst = DX12_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeTarget)(pNewTargetParameters);
}
HRESULT STDMETHODCALLTYPE DX12_Hook::MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags)
{
DX12_Hook::Inst()->resetRenderState();
return (_this->*DX12_Hook::Inst()->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
auto inst = DX12_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->ResizeBuffers)(BufferCount, Width, Height, NewFormat, SwapChainFlags);
}
void STDMETHODCALLTYPE DX12_Hook::MyExecuteCommandLists(ID3D12CommandQueue *_this, UINT NumCommandLists, ID3D12CommandList* const* ppCommandLists)
{
DX12_Hook* me = DX12_Hook::Inst();
me->pCmdQueue = _this;
auto inst = DX12_Hook::Inst();
inst->pCmdQueue = _this;
(_this->*inst->ExecuteCommandLists)(NumCommandLists, ppCommandLists);
}
(_this->*DX12_Hook::Inst()->ExecuteCommandLists)(NumCommandLists, ppCommandLists);
HRESULT STDMETHODCALLTYPE DX12_Hook::MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters)
{
auto inst = DX12_Hook::Inst();
ID3D12CommandQueue* pCommandQueue = inst->_FindCommandQueueFromSwapChain(_this);
if (pCommandQueue != nullptr)
{
inst->_PrepareForOverlay(_this, pCommandQueue);
}
return (_this->*inst->Present1)(SyncInterval, Flags, pPresentParameters);
}
DX12_Hook::DX12_Hook():
initialized(false),
_Initialized(false),
CommandQueueOffset(0),
pDevice(nullptr),
pCmdQueue(nullptr),
bufferCount(0),
pCmdAlloc(nullptr),
pSrvDescHeap(nullptr),
pCmdList(nullptr),
pRtvDescHeap(nullptr),
hooked(false),
_Hooked(false),
_WindowsHooked(false),
Present(nullptr),
ResizeBuffers(nullptr),
ResizeTarget(nullptr),
ExecuteCommandLists(nullptr)
ExecuteCommandLists(nullptr),
Present1(nullptr)
{
_library = LoadLibrary(DX12_DLL);
PRINT_DEBUG("DX12 support is experimental, don't complain if it doesn't work as expected.\n");
SPDLOG_WARN("DX12 support is experimental, don't complain if it doesn't work as expected.");
}
DX12_Hook::~DX12_Hook()
{
PRINT_DEBUG("DX12 Hook removed\n");
SPDLOG_INFO("DX12 Hook removed");
if (initialized)
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
OverlayFrames.clear();
pSrvDescHeap->Release();
for (UINT i = 0; i < bufferCount; ++i)
{
pCmdAlloc[i]->Release();
pBackBuffer[i]->Release();
}
pRtvDescHeap->Release();
delete[]pCmdAlloc;
delete[]pBackBuffer;
ImGui_ImplDX12_InvalidateDeviceObjects();
ImGui::DestroyContext();
initialized = false;
_Initialized = false;
}
FreeLibrary(reinterpret_cast<HMODULE>(_library));
_inst = nullptr;
}
@ -294,26 +408,204 @@ DX12_Hook* DX12_Hook::Inst()
return _inst;
}
const char* DX12_Hook::get_lib_name() const
std::string DX12_Hook::GetLibraryName() const
{
return DX12_DLL;
return LibraryName;
}
void DX12_Hook::loadFunctions(ID3D12CommandQueue* pCommandQueue, IDXGISwapChain *pSwapChain)
void DX12_Hook::LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(ExecuteCommandLists) ExecuteCommandListsFcn,
decltype(Present1) Present1Fcn)
{
void** vTable;
vTable = *reinterpret_cast<void***>(pCommandQueue);
#define LOAD_FUNC(X) (void*&)X = vTable[(int)ID3D12CommandQueueVTable::X]
LOAD_FUNC(ExecuteCommandLists);
#undef LOAD_FUNC
Present = PresentFcn;
ResizeBuffers = ResizeBuffersFcn;
ResizeTarget = ResizeTargetFcn;
vTable = *reinterpret_cast<void***>(pSwapChain);
#define LOAD_FUNC(X) (void*&)X = vTable[(int)IDXGISwapChainVTable::X]
LOAD_FUNC(Present);
LOAD_FUNC(ResizeBuffers);
LOAD_FUNC(ResizeTarget);
#undef LOAD_FUNC
ExecuteCommandLists = ExecuteCommandListsFcn;
Present1 = Present1Fcn;
}
#endif//EMU_OVERLAY
std::weak_ptr<uint64_t> DX12_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
return std::shared_ptr<uint64_t>();
//heap_t heap = get_free_texture_heap();
//
//if (heap.id == -1)
// return nullptr;
//
//HRESULT hr;
//
//D3D12_HEAP_PROPERTIES props;
//memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
//props.Type = D3D12_HEAP_TYPE_DEFAULT;
//props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
//props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
//
//D3D12_RESOURCE_DESC desc;
//ZeroMemory(&desc, sizeof(desc));
//desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
//desc.Alignment = 0;
//desc.Width = source->width();
//desc.Height = source->height();
//desc.DepthOrArraySize = 1;
//desc.MipLevels = 1;
//desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
//desc.SampleDesc.Count = 1;
//desc.SampleDesc.Quality = 0;
//desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
//desc.Flags = D3D12_RESOURCE_FLAG_NONE;
//
//ID3D12Resource* pTexture = NULL;
//pDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
// D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
//
//UINT uploadPitch = (source->width() * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
//UINT uploadSize = source->height() * uploadPitch;
//desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
//desc.Alignment = 0;
//desc.Width = uploadSize;
//desc.Height = 1;
//desc.DepthOrArraySize = 1;
//desc.MipLevels = 1;
//desc.Format = DXGI_FORMAT_UNKNOWN;
//desc.SampleDesc.Count = 1;
//desc.SampleDesc.Quality = 0;
//desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
//desc.Flags = D3D12_RESOURCE_FLAG_NONE;
//
//props.Type = D3D12_HEAP_TYPE_UPLOAD;
//props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
//props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
//
//ID3D12Resource* uploadBuffer = NULL;
//hr = pDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
// D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
//IM_ASSERT(SUCCEEDED(hr));
//
//void* mapped = NULL;
//D3D12_RANGE range = { 0, uploadSize };
//hr = uploadBuffer->Map(0, &range, &mapped);
//IM_ASSERT(SUCCEEDED(hr));
//for (int y = 0; y < source->height(); y++)
// memcpy((void*)((uintptr_t)mapped + y * uploadPitch), reinterpret_cast<uint8_t*>(source->get_raw_pointer()) + y * source->width() * 4, source->width() * 4);
//uploadBuffer->Unmap(0, &range);
//
//D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
//srcLocation.pResource = uploadBuffer;
//srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
//srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
//srcLocation.PlacedFootprint.Footprint.Width = source->width();
//srcLocation.PlacedFootprint.Footprint.Height = source->height();
//srcLocation.PlacedFootprint.Footprint.Depth = 1;
//srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
//
//D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
//dstLocation.pResource = pTexture;
//dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
//dstLocation.SubresourceIndex = 0;
//
//D3D12_RESOURCE_BARRIER barrier = {};
//barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
//barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
//barrier.Transition.pResource = pTexture;
//barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
//barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
//barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
//
//ID3D12Fence* fence = NULL;
//hr = pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
//IM_ASSERT(SUCCEEDED(hr));
//
//HANDLE event = CreateEvent(0, 0, 0, 0);
//IM_ASSERT(event != NULL);
//
//D3D12_COMMAND_QUEUE_DESC queueDesc = {};
//queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
//queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
//queueDesc.NodeMask = 1;
//
//ID3D12CommandQueue* cmdQueue = NULL;
//hr = pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
//IM_ASSERT(SUCCEEDED(hr));
//
//ID3D12CommandAllocator* cmdAlloc = NULL;
//hr = pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
//IM_ASSERT(SUCCEEDED(hr));
//
//ID3D12GraphicsCommandList* cmdList = NULL;
//hr = pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
//IM_ASSERT(SUCCEEDED(hr));
//
//cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
//cmdList->ResourceBarrier(1, &barrier);
//
//hr = cmdList->Close();
//IM_ASSERT(SUCCEEDED(hr));
//
//cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
//hr = cmdQueue->Signal(fence, 1);
//IM_ASSERT(SUCCEEDED(hr));
//
//fence->SetEventOnCompletion(1, event);
//WaitForSingleObject(event, INFINITE);
//
//cmdList->Release();
//cmdAlloc->Release();
//cmdQueue->Release();
//CloseHandle(event);
//fence->Release();
//uploadBuffer->Release();
//
//// Create texture view
//D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
//ZeroMemory(&srvDesc, sizeof(srvDesc));
//srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
//srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
//srvDesc.Texture2D.MipLevels = desc.MipLevels;
//srvDesc.Texture2D.MostDetailedMip = 0;
//srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
//
//pDevice->CreateShaderResourceView(pTexture, &srvDesc, heap.cpu_handle);
//
////pSrvDescHeap->Release();
////pTexture->Release();
//
//using gpu_heap_t = decltype(D3D12_GPU_DESCRIPTOR_HANDLE::ptr);
//struct texture_t{
// gpu_heap_t gpu_handle; // This must be the first member, ImGui will use the content of the pointer as a D3D12_GPU_DESCRIPTOR_HANDLE::ptr
// ID3D12Resource* pTexture;
// int64_t heap_id;
//};
//
//texture_t* texture_data = new texture_t;
//texture_data->gpu_handle = heap.gpu_handle.ptr;
//texture_data->pTexture = pTexture;
//texture_data->heap_id = heap.id;
//
//return std::shared_ptr<uint64_t>((uint64_t*)texture_data, [this](uint64_t* handle)
//{
// if (handle != nullptr)
// {
// texture_t* pTextureData = reinterpret_cast<texture_t*>(handle);
// pTextureData->pTexture->Release();
// release_texture_heap(pTextureData->heap_id);
//
// delete pTextureData;
// }
//});
}
void DX12_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
//auto ptr = resource.lock();
//if (ptr)
//{
// auto it = _ImageResources.find(ptr);
// if (it != _ImageResources.end())
// _ImageResources.erase(it);
//}
}

View file

@ -1,60 +1,144 @@
#ifndef __INCLUDED_DX12_HOOK_H__
#define __INCLUDED_DX12_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#ifdef EMU_OVERLAY
#pragma once
#include "../internal_includes.h"
#include <d3d12.h>
#include <dxgi1_4.h>
#include "DirectX_VTables.h"
class DX12_Hook : public Base_Hook
class DX12_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
#define DX12_DLL "d3d12.dll"
static constexpr const char *DLL_NAME = "d3d12.dll";
private:
static DX12_Hook* _inst;
// Variables
bool hooked;
bool initialized;
struct DX12Frame_t
{
D3D12_CPU_DESCRIPTOR_HANDLE RenderTarget = {};
ID3D12CommandAllocator* pCmdAlloc = nullptr;
ID3D12Resource* pBackBuffer = nullptr;
inline void Reset()
{
pCmdAlloc = nullptr;
pBackBuffer = nullptr;
}
DX12Frame_t(DX12Frame_t const&) = delete;
DX12Frame_t& operator=(DX12Frame_t const&) = delete;
DX12Frame_t(D3D12_CPU_DESCRIPTOR_HANDLE RenderTarget, ID3D12CommandAllocator* pCmdAlloc, ID3D12Resource* pBackBuffer):
RenderTarget(RenderTarget), pCmdAlloc(pCmdAlloc), pBackBuffer(pBackBuffer)
{}
DX12Frame_t(DX12Frame_t&& other) noexcept:
RenderTarget(other.RenderTarget), pCmdAlloc(other.pCmdAlloc), pBackBuffer(other.pBackBuffer)
{
other.Reset();
}
DX12Frame_t& operator=(DX12Frame_t&& other) noexcept
{
DX12Frame_t tmp(std::move(other));
RenderTarget = tmp.RenderTarget;
pCmdAlloc = tmp.pCmdAlloc;
pBackBuffer = tmp.pBackBuffer;
tmp.Reset();
return *this;
}
~DX12Frame_t()
{
if (pCmdAlloc != nullptr) pCmdAlloc->Release();
if (pBackBuffer != nullptr) pBackBuffer->Release();
}
};
// Variables
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
size_t CommandQueueOffset;
ID3D12CommandQueue* pCmdQueue;
UINT bufferCount;
std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> mainRenderTargets;
ID3D12CommandAllocator** pCmdAlloc;
ID3D12Device* pDevice;
std::vector<DX12Frame_t> OverlayFrames;
//std::vector<bool> srvDescHeapBitmap;
ID3D12DescriptorHeap* pSrvDescHeap;
ID3D12GraphicsCommandList* pCmdList;
ID3D12DescriptorHeap* pRtvDescHeap;
ID3D12Resource** pBackBuffer;
// Functions
DX12_Hook();
void resetRenderState();
void prepareForOverlay(IDXGISwapChain* pSwapChain);
//struct heap_t
//{
// D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle;
// D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle;
// int64_t id;
//};
//
//heap_t get_free_texture_heap();
//bool release_texture_heap(int64_t heap_id);
ID3D12CommandQueue* _FindCommandQueueFromSwapChain(IDXGISwapChain* pSwapChain);
void _ResetRenderState();
void _PrepareForOverlay(IDXGISwapChain* pSwapChain, ID3D12CommandQueue* pCommandQueue);
// Hook to render functions
static HRESULT STDMETHODCALLTYPE MyPresent(IDXGISwapChain* _this, UINT SyncInterval, UINT Flags);
static HRESULT STDMETHODCALLTYPE MyResizeTarget(IDXGISwapChain* _this, const DXGI_MODE_DESC* pNewTargetParameters);
static HRESULT STDMETHODCALLTYPE MyResizeBuffers(IDXGISwapChain* _this, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags);
static void STDMETHODCALLTYPE MyExecuteCommandLists(ID3D12CommandQueue *_this, UINT NumCommandLists, ID3D12CommandList* const* ppCommandLists);
static HRESULT STDMETHODCALLTYPE MyPresent1(IDXGISwapChain1* _this, UINT SyncInterval, UINT Flags, const DXGI_PRESENT_PARAMETERS* pPresentParameters);
decltype(&IDXGISwapChain::Present) Present;
decltype(&IDXGISwapChain::ResizeBuffers) ResizeBuffers;
decltype(&IDXGISwapChain::ResizeTarget) ResizeTarget;
decltype(&ID3D12CommandQueue::ExecuteCommandLists) ExecuteCommandLists;
decltype(&IDXGISwapChain1::Present1) Present1;
public:
std::string LibraryName;
virtual ~DX12_Hook();
bool start_hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static DX12_Hook* Inst();
virtual const char* get_lib_name() const;
virtual std::string GetLibraryName() const;
void loadFunctions(ID3D12CommandQueue* pCommandQueue, IDXGISwapChain* pSwapChain);
void LoadFunctions(
decltype(Present) PresentFcn,
decltype(ResizeBuffers) ResizeBuffersFcn,
decltype(ResizeTarget) ResizeTargetFcn,
decltype(ExecuteCommandLists) ExecuteCommandListsFcn,
decltype(Present1) Present1Fcn1);
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};
#endif//EMU_OVERLAY
#endif//__INCLUDED_DX12_HOOK_H__

View file

@ -1,26 +1,58 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "DX9_Hook.h"
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
#ifdef EMU_OVERLAY
#include "DirectX_VTables.h"
#include <imgui.h>
#include <impls/windows/imgui_impl_dx9.h>
#include <backends/imgui_impl_dx9.h>
DX9_Hook* DX9_Hook::_inst = nullptr;
bool DX9_Hook::start_hook()
template<typename T>
inline void SafeRelease(T*& pUnk)
{
if (!hooked)
if (pUnk != nullptr)
{
if (!Windows_Hook::Inst()->start_hook())
pUnk->Release();
pUnk = nullptr;
}
}
bool DX9_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
if (!_Hooked)
{
if (Reset == nullptr || Present == nullptr)
{
SPDLOG_WARN("Failed to hook DirectX 9: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
PRINT_DEBUG("Hooked DirectX 9\n");
hooked = true;
Renderer_Detector::Inst().renderer_found(this);
_WindowsHooked = true;
SPDLOG_INFO("Hooked DirectX 9");
_Hooked = true;
BeginHook();
HookFuncs(
@ -31,57 +63,89 @@ bool DX9_Hook::start_hook()
{
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)PresentEx, &DX9_Hook::MyPresentEx)
//std::make_pair<void**, void*>(&(PVOID&)EndScene, &DX9_Hook::MyEndScene)
);
}
if (SwapChainPresent != nullptr)
{
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)SwapChainPresent, &DX9_Hook::MySwapChainPresent)
);
}
EndHook();
get_steam_client()->steam_overlay->HookReady();
}
return true;
}
void DX9_Hook::resetRenderState()
bool DX9_Hook::IsStarted()
{
if (initialized)
return _Hooked;
}
void DX9_Hook::_ResetRenderState()
{
if (_Initialized)
{
initialized = false;
OverlayHookReady(false);
ImGui_ImplDX9_Shutdown();
Windows_Hook::Inst()->resetRenderState();
Windows_Hook::Inst()->_ResetRenderState();
ImGui::DestroyContext();
SafeRelease(_pDevice);
_LastWindow = nullptr;
_Initialized = false;
}
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void DX9_Hook::prepareForOverlay(IDirect3DDevice9 *pDevice)
void DX9_Hook::_PrepareForOverlay(IDirect3DDevice9 *pDevice, HWND destWindow)
{
D3DDEVICE_CREATION_PARAMETERS param;
pDevice->GetCreationParameters(&param);
if (!destWindow)
{
IDirect3DSwapChain9 *pSwapChain = nullptr;
if (pDevice->GetSwapChain(0, &pSwapChain) == D3D_OK)
{
D3DPRESENT_PARAMETERS params;
if (pSwapChain->GetPresentParameters(&params) == D3D_OK)
{
destWindow = params.hDeviceWindow;
}
pSwapChain->Release();
}
}
//Is this necessary anymore?
if (!destWindow)
{
D3DDEVICE_CREATION_PARAMETERS param;
pDevice->GetCreationParameters(&param);
destWindow = param.hFocusWindow;
}
// Workaround to detect if we changed window.
if (param.hFocusWindow != Windows_Hook::Inst()->GetGameHwnd())
resetRenderState();
if (destWindow != _LastWindow || _pDevice != pDevice)
_ResetRenderState();
if (!initialized)
if (!_Initialized)
{
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
pDevice->AddRef();
_pDevice = pDevice;
ImGui::CreateContext();
ImGui_ImplDX9_Init(pDevice);
get_steam_client()->steam_overlay->CreateFonts();
initialized = true;
_LastWindow = destWindow;
_Initialized = true;
OverlayHookReady(true);
}
if (ImGui_ImplDX9_NewFrame())
{
Windows_Hook::Inst()->prepareForOverlay(param.hFocusWindow);
if (ImGui_ImplDX9_NewFrame() && Windows_Hook::Inst()->_PrepareForOverlay(destWindow))
{
ImGui::NewFrame();
get_steam_client()->steam_overlay->OverlayProc();
OverlayProc();
ImGui::Render();
@ -91,55 +155,72 @@ void DX9_Hook::prepareForOverlay(IDirect3DDevice9 *pDevice)
HRESULT STDMETHODCALLTYPE DX9_Hook::MyReset(IDirect3DDevice9* _this, D3DPRESENT_PARAMETERS* pPresentationParameters)
{
DX9_Hook::Inst()->resetRenderState();
return (_this->*DX9_Hook::Inst()->Reset)(pPresentationParameters);
}
HRESULT STDMETHODCALLTYPE DX9_Hook::MyEndScene(IDirect3DDevice9* _this)
{
if( !DX9_Hook::Inst()->uses_present )
DX9_Hook::Inst()->prepareForOverlay(_this);
return (_this->*DX9_Hook::Inst()->EndScene)();
auto inst = DX9_Hook::Inst();
inst->_ResetRenderState();
return (_this->*inst->Reset)(pPresentationParameters);
}
HRESULT STDMETHODCALLTYPE DX9_Hook::MyPresent(IDirect3DDevice9* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion)
{
DX9_Hook::Inst()->uses_present = true;
DX9_Hook::Inst()->prepareForOverlay(_this);
return (_this->*DX9_Hook::Inst()->Present)(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
auto inst = DX9_Hook::Inst();
inst->_PrepareForOverlay(_this, hDestWindowOverride);
return (_this->*inst->Present)(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
}
HRESULT STDMETHODCALLTYPE DX9_Hook::MyPresentEx(IDirect3DDevice9Ex* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion, DWORD dwFlags)
{
DX9_Hook::Inst()->uses_present = true;
DX9_Hook::Inst()->prepareForOverlay(_this);
return (_this->*DX9_Hook::Inst()->PresentEx)(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
auto inst = DX9_Hook::Inst();
inst->_PrepareForOverlay(_this, hDestWindowOverride);
return (_this->*inst->PresentEx)(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
}
HRESULT STDMETHODCALLTYPE DX9_Hook::MySwapChainPresent(IDirect3DSwapChain9* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion, DWORD dwFlags)
{
IDirect3DDevice9* pDevice;
auto inst = DX9_Hook::Inst();
if (SUCCEEDED(_this->GetDevice(&pDevice)))
{
HWND destWindow = hDestWindowOverride;
if (!destWindow)
{
D3DPRESENT_PARAMETERS param;
if (_this->GetPresentParameters(&param) == D3D_OK)
{
destWindow = param.hDeviceWindow;
}
}
inst->_PrepareForOverlay(pDevice, destWindow);
pDevice->Release();
}
return (_this->*inst->SwapChainPresent)(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags);
}
DX9_Hook::DX9_Hook():
initialized(false),
hooked(false),
uses_present(false),
EndScene(nullptr),
_Initialized(false),
_Hooked(false),
_WindowsHooked(false),
_LastWindow(nullptr),
Present(nullptr),
PresentEx(nullptr),
Reset(nullptr)
{
_library = LoadLibrary(DX9_DLL);
}
DX9_Hook::~DX9_Hook()
{
PRINT_DEBUG("DX9 Hook removed\n");
SPDLOG_INFO("DX9 Hook removed");
if (initialized)
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
ImGui_ImplDX9_InvalidateDeviceObjects();
ImGui::DestroyContext();
}
FreeLibrary(reinterpret_cast<HMODULE>(_library));
_inst = nullptr;
}
@ -151,22 +232,94 @@ DX9_Hook* DX9_Hook::Inst()
return _inst;
}
const char* DX9_Hook::get_lib_name() const
std::string DX9_Hook::GetLibraryName() const
{
return DX9_DLL;
return LibraryName;
}
void DX9_Hook::loadFunctions(IDirect3DDevice9* pDevice, bool ex)
void DX9_Hook::LoadFunctions(decltype(Present) PresentFcn, decltype(Reset) ResetFcn, decltype(PresentEx) PresentExFcn, decltype(&IDirect3DSwapChain9::Present) SwapChainPresentFcn)
{
void** vTable = *reinterpret_cast<void***>(pDevice);
Present = PresentFcn;
Reset = ResetFcn;
#define LOAD_FUNC(X) (void*&)X = vTable[(int)IDirect3DDevice9VTable::X]
LOAD_FUNC(Reset);
LOAD_FUNC(EndScene);
LOAD_FUNC(Present);
if (ex)
LOAD_FUNC(PresentEx);
#undef LOAD_FUNC
PresentEx = PresentExFcn;
SwapChainPresent = SwapChainPresentFcn;
}
#endif//EMU_OVERLAY
std::weak_ptr<uint64_t> DX9_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
IDirect3DTexture9** pTexture = new IDirect3DTexture9*(nullptr);
_pDevice->CreateTexture(
width,
height,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT,
pTexture,
nullptr
);
if (*pTexture != nullptr)
{
D3DLOCKED_RECT rect;
if (SUCCEEDED((*pTexture)->LockRect(0, &rect, nullptr, D3DLOCK_DISCARD)))
{
const uint32_t* pixels = reinterpret_cast<const uint32_t*>(image_data);
uint8_t* texture_bits = reinterpret_cast<uint8_t*>(rect.pBits);
for (int32_t i = 0; i < height; ++i)
{
for (int32_t j = 0; j < width; ++j)
{
// RGBA to ARGB Conversion, DX9 doesn't have a RGBA loader
uint32_t color = *pixels++;
reinterpret_cast<uint32_t*>(texture_bits)[j] = ((color & 0xff) << 16) | (color & 0xff00) | ((color & 0xff0000) >> 16) | (color & 0xff000000);
}
texture_bits += rect.Pitch;
}
if (FAILED((*pTexture)->UnlockRect(0)))
{
(*pTexture)->Release();
delete pTexture;
pTexture = nullptr;
}
}
else
{
(*pTexture)->Release();
delete pTexture;
pTexture = nullptr;
}
}
if (pTexture == nullptr)
return std::shared_ptr<uint64_t>();
auto ptr = std::shared_ptr<uint64_t>((uint64_t*)pTexture, [](uint64_t* handle)
{
if (handle != nullptr)
{
IDirect3DTexture9** resource = reinterpret_cast<IDirect3DTexture9**>(handle);
(*resource)->Release();
delete resource;
}
});
_ImageResources.emplace(ptr);
return ptr;
}
void DX9_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
auto ptr = resource.lock();
if (ptr)
{
auto it = _ImageResources.find(ptr);
if (it != _ImageResources.end())
_ImageResources.erase(it);
}
}

View file

@ -1,52 +1,75 @@
#ifndef __INCLUDED_DX9_HOOK_H__
#define __INCLUDED_DX9_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#ifdef EMU_OVERLAY
#pragma once
#include "../internal_includes.h"
#include <d3d9.h>
#include "DirectX_VTables.h"
class DX9_Hook : public Base_Hook
class DX9_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
#define DX9_DLL "d3d9.dll"
static constexpr const char *DLL_NAME = "d3d9.dll";
private:
static DX9_Hook* _inst;
// Variables
bool hooked;
bool initialized;
bool uses_present;
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
HWND _LastWindow;
IDirect3DDevice9* _pDevice;
std::set<std::shared_ptr<uint64_t>> _ImageResources;
// Functions
DX9_Hook();
void resetRenderState();
void prepareForOverlay(IDirect3DDevice9* pDevice);
void _ResetRenderState();
void _PrepareForOverlay(IDirect3DDevice9* pDevice, HWND destWindow);
// Hook to render functions
decltype(&IDirect3DDevice9::Reset) Reset;
decltype(&IDirect3DDevice9::EndScene) EndScene;
decltype(&IDirect3DDevice9::Present) Present;
decltype(&IDirect3DDevice9Ex::PresentEx) PresentEx;
decltype(&IDirect3DSwapChain9::Present) SwapChainPresent;
static HRESULT STDMETHODCALLTYPE MyReset(IDirect3DDevice9* _this, D3DPRESENT_PARAMETERS* pPresentationParameters);
static HRESULT STDMETHODCALLTYPE MyEndScene(IDirect3DDevice9 *_this);
static HRESULT STDMETHODCALLTYPE MyPresent(IDirect3DDevice9* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion);
static HRESULT STDMETHODCALLTYPE MyPresentEx(IDirect3DDevice9Ex* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion, DWORD dwFlags);
static HRESULT STDMETHODCALLTYPE MySwapChainPresent(IDirect3DSwapChain9* _this, CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion, DWORD dwFlags);
public:
std::string LibraryName;
virtual ~DX9_Hook();
bool start_hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static DX9_Hook* Inst();
virtual const char* get_lib_name() const;
virtual std::string GetLibraryName() const;
void loadFunctions(IDirect3DDevice9 *pDevice, bool ex);
void LoadFunctions(decltype(Present) PresentFcn, decltype(Reset) ResetFcn, decltype(PresentEx) PresentExFcn, decltype(&IDirect3DSwapChain9::Present) SwapChainPresentFcn);
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};
#endif//EMU_OVERLAY
#endif//__INCLUDED_DX9_HOOK_H__

View file

@ -1,6 +1,23 @@
#pragma once
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include <DXGI.h>
#pragma once
enum class IDXGISwapChainVTable
{
@ -446,3 +463,44 @@ enum class IDirect3DDevice9VTable
ResetEx,
GetDisplayModeEx,
};
struct IDirect3DSwapChain9VTable
{
enum class Index
{
// IUnknown
QueryInterface,
AddRef,
Release,
// IDirect3DSwapChain9
Present,
GetFrontBufferData,
GetBackBuffer,
GetRasterStatus,
GetDisplayMode,
GetDevice,
GetPresentParameters,
// IDirect3DSwapChain9Ex
GetLastPresentCount,
GetPresentStats,
GetDisplayModeEx,
};
decltype(&IDirect3DSwapChain9::QueryInterface) pQueryInterface;
decltype(&IDirect3DSwapChain9::AddRef) pAddRef;
decltype(&IDirect3DSwapChain9::Release) pRelease;
decltype(&IDirect3DSwapChain9::Present) pPresent;
decltype(&IDirect3DSwapChain9::GetFrontBufferData) pGetFrontBufferData;
decltype(&IDirect3DSwapChain9::GetBackBuffer) pGetBackBuffer;
decltype(&IDirect3DSwapChain9::GetRasterStatus) pGetRasterStatus;
decltype(&IDirect3DSwapChain9::GetDisplayMode) pGetDisplayMode;
decltype(&IDirect3DSwapChain9::GetDevice) pGetDevice;
decltype(&IDirect3DSwapChain9::GetPresentParameters) pGetPresentParameters;
decltype(&IDirect3DSwapChain9Ex::GetLastPresentCount) pGetLastPresentCount;
decltype(&IDirect3DSwapChain9Ex::GetPresentStats) pGetPresentStats;
decltype(&IDirect3DSwapChain9Ex::GetDisplayModeEx) pGetDisplayModeEx;
};

View file

@ -1,96 +1,104 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "OpenGL_Hook.h"
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
#ifdef EMU_OVERLAY
#include <imgui.h>
#include <impls/imgui_impl_opengl3.h>
#include <backends/imgui_impl_opengl3.h>
#include <GL/glew.h>
#include "../steam_overlay.h"
#include <glad/gl.h>
OpenGL_Hook* OpenGL_Hook::_inst = nullptr;
bool OpenGL_Hook::start_hook()
bool OpenGL_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
bool res = true;
if (!hooked)
if (!_Hooked)
{
if (!Windows_Hook::Inst()->start_hook())
if (wglSwapBuffers == nullptr)
{
SPDLOG_WARN("Failed to hook OpenGL: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
GLenum err = glewInit();
_WindowsHooked = true;
if (err == GLEW_OK)
{
PRINT_DEBUG("Hooked OpenGL\n");
SPDLOG_INFO("Hooked OpenGL");
hooked = true;
Renderer_Detector::Inst().renderer_found(this);
_Hooked = true;
UnhookAll();
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)wglSwapBuffers, &OpenGL_Hook::MywglSwapBuffers)
);
EndHook();
get_steam_client()->steam_overlay->HookReady();
}
else
{
PRINT_DEBUG("Failed to hook OpenGL\n");
/* Problem: glewInit failed, something is seriously wrong. */
PRINT_DEBUG("Error: %s\n", glewGetErrorString(err));
res = false;
}
UnhookAll();
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)wglSwapBuffers, &OpenGL_Hook::MywglSwapBuffers)
);
EndHook();
}
return true;
}
void OpenGL_Hook::resetRenderState()
bool OpenGL_Hook::IsStarted()
{
if (initialized)
return _Hooked;
}
void OpenGL_Hook::_ResetRenderState()
{
if (_Initialized)
{
OverlayHookReady(false);
ImGui_ImplOpenGL3_Shutdown();
Windows_Hook::Inst()->resetRenderState();
Windows_Hook::Inst()->_ResetRenderState();
ImGui::DestroyContext();
initialized = false;
last_window = nullptr;
_Initialized = false;
}
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void OpenGL_Hook::prepareForOverlay(HDC hDC)
void OpenGL_Hook::_PrepareForOverlay(HDC hDC)
{
HWND hWnd = WindowFromDC(hDC);
if (hWnd != Windows_Hook::Inst()->GetGameHwnd())
resetRenderState();
if (hWnd != last_window)
_ResetRenderState();
if (!initialized)
if (!_Initialized)
{
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
ImGui_ImplOpenGL3_Init();
get_steam_client()->steam_overlay->CreateFonts();
initialized = true;
last_window = hWnd;
_Initialized = true;
OverlayHookReady(true);
}
if (ImGui_ImplOpenGL3_NewFrame())
if (ImGui_ImplOpenGL3_NewFrame() && Windows_Hook::Inst()->_PrepareForOverlay(hWnd))
{
Windows_Hook::Inst()->prepareForOverlay(hWnd);
ImGui::NewFrame();
get_steam_client()->steam_overlay->OverlayProc();
OverlayProc();
ImGui::Render();
@ -100,30 +108,33 @@ void OpenGL_Hook::prepareForOverlay(HDC hDC)
BOOL WINAPI OpenGL_Hook::MywglSwapBuffers(HDC hDC)
{
OpenGL_Hook::Inst()->prepareForOverlay(hDC);
return OpenGL_Hook::Inst()->wglSwapBuffers(hDC);
auto inst = OpenGL_Hook::Inst();
inst->_PrepareForOverlay(hDC);
return inst->wglSwapBuffers(hDC);
}
OpenGL_Hook::OpenGL_Hook():
initialized(false),
hooked(false),
_Hooked(false),
_WindowsHooked(false),
_Initialized(false),
last_window(nullptr),
wglSwapBuffers(nullptr)
{
_library = LoadLibrary(OPENGL_DLL);
}
OpenGL_Hook::~OpenGL_Hook()
{
PRINT_DEBUG("OpenGL Hook removed\n");
SPDLOG_INFO("OpenGL Hook removed");
if (initialized)
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
ImGui_ImplOpenGL3_Shutdown();
ImGui::DestroyContext();
}
FreeLibrary(reinterpret_cast<HMODULE>(_library));
_inst = nullptr;
}
@ -135,14 +146,62 @@ OpenGL_Hook* OpenGL_Hook::Inst()
return _inst;
}
const char* OpenGL_Hook::get_lib_name() const
std::string OpenGL_Hook::GetLibraryName() const
{
return OPENGL_DLL;
return LibraryName;
}
void OpenGL_Hook::loadFunctions(wglSwapBuffers_t pfnwglSwapBuffers)
void OpenGL_Hook::LoadFunctions(wglSwapBuffers_t pfnwglSwapBuffers)
{
wglSwapBuffers = pfnwglSwapBuffers;
}
#endif//EMU_OVERLAY
std::weak_ptr<uint64_t> OpenGL_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
GLuint* texture = new GLuint(0);
glGenTextures(1, texture);
if (glGetError() != GL_NO_ERROR)
{
delete texture;
return std::shared_ptr<uint64_t>(nullptr);
}
// Save old texture id
GLint oldTex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTex);
glBindTexture(GL_TEXTURE_2D, *texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Upload pixels into texture
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
glBindTexture(GL_TEXTURE_2D, oldTex);
auto ptr = std::shared_ptr<uint64_t>((uint64_t*)texture, [](uint64_t* handle)
{
if (handle != nullptr)
{
GLuint* texture = (GLuint*)handle;
glDeleteTextures(1, texture);
delete texture;
}
});
_ImageResources.emplace(ptr);
return ptr;
}
void OpenGL_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
auto ptr = resource.lock();
if (ptr)
{
auto it = _ImageResources.find(ptr);
if (it != _ImageResources.end())
_ImageResources.erase(it);
}
}

View file

@ -1,13 +1,32 @@
#ifndef __INCLUDED_OPENGL_HOOK_H__
#define __INCLUDED_OPENGL_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#ifdef EMU_OVERLAY
#pragma once
class OpenGL_Hook : public Base_Hook
#include "../internal_includes.h"
class OpenGL_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
#define OPENGL_DLL "opengl32.dll"
static constexpr const char *DLL_NAME = "opengl32.dll";
using wglSwapBuffers_t = BOOL(WINAPI*)(HDC);
@ -15,14 +34,17 @@ private:
static OpenGL_Hook* _inst;
// Variables
bool hooked;
bool initialized;
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
HWND last_window;
std::set<std::shared_ptr<uint64_t>> _ImageResources;
// Functions
OpenGL_Hook();
void resetRenderState();
void prepareForOverlay(HDC hDC);
void _ResetRenderState();
void _PrepareForOverlay(HDC hDC);
// Hook to render functions
static BOOL WINAPI MywglSwapBuffers(HDC hDC);
@ -30,13 +52,16 @@ private:
wglSwapBuffers_t wglSwapBuffers;
public:
std::string LibraryName;
virtual ~OpenGL_Hook();
bool start_hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static OpenGL_Hook* Inst();
virtual const char* get_lib_name() const;
void loadFunctions(wglSwapBuffers_t pfnwglSwapBuffers);
};
virtual std::string GetLibraryName() const;
void LoadFunctions(wglSwapBuffers_t pfnwglSwapBuffers);
#endif//EMU_OVERLAY
#endif//__INCLUDED_OPENGL_HOOK_H__
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};

View file

@ -0,0 +1,128 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "Vulkan_Hook.h"
#include "Windows_Hook.h"
#include <imgui.h>
#include <backends/imgui_impl_vulkan.h>
Vulkan_Hook* Vulkan_Hook::_inst = nullptr;
bool Vulkan_Hook::StartHook(std::function<bool(bool)> key_combination_callback)
{
SPDLOG_WARN("Vulkan overlay is not yet supported.");
return false;
if (!_Hooked)
{
if (vkQueuePresentKHR == nullptr)
{
SPDLOG_WARN("Failed to hook Vulkan: Rendering functions missing.");
return false;
}
if (!Windows_Hook::Inst()->StartHook(key_combination_callback))
return false;
_WindowsHooked = true;
SPDLOG_INFO("Hooked Vulkan");
_Hooked = true;
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)vkQueuePresentKHR, &Vulkan_Hook::MyvkQueuePresentKHR)
);
EndHook();
}
return true;
}
bool Vulkan_Hook::IsStarted()
{
return _Hooked;
}
void Vulkan_Hook::_ResetRenderState()
{
}
// Try to make this function and overlay's proc as short as possible or it might affect game's fps.
void Vulkan_Hook::_PrepareForOverlay()
{
}
VKAPI_ATTR VkResult VKAPI_CALL Vulkan_Hook::MyvkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo)
{
auto inst = Vulkan_Hook::Inst();
inst->_PrepareForOverlay();
return inst->vkQueuePresentKHR(queue, pPresentInfo);
}
Vulkan_Hook::Vulkan_Hook():
_Hooked(false),
_WindowsHooked(false),
_Initialized(false),
vkQueuePresentKHR(nullptr)
{
}
Vulkan_Hook::~Vulkan_Hook()
{
SPDLOG_INFO("Vulkan_Hook Hook removed");
if (_WindowsHooked)
delete Windows_Hook::Inst();
if (_Initialized)
{
}
_inst = nullptr;
}
Vulkan_Hook* Vulkan_Hook::Inst()
{
if (_inst == nullptr)
_inst = new Vulkan_Hook;
return _inst;
}
std::string Vulkan_Hook::GetLibraryName() const
{
return LibraryName;
}
void Vulkan_Hook::LoadFunctions(decltype(::vkQueuePresentKHR)* _vkQueuePresentKHR)
{
vkQueuePresentKHR = _vkQueuePresentKHR;
}
std::weak_ptr<uint64_t> Vulkan_Hook::CreateImageResource(const void* image_data, uint32_t width, uint32_t height)
{
return std::shared_ptr<uint64_t>(nullptr);
}
void Vulkan_Hook::ReleaseImageResource(std::weak_ptr<uint64_t> resource)
{
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "../internal_includes.h"
#include <vulkan/vulkan.h>
class Vulkan_Hook :
public Renderer_Hook,
public Base_Hook
{
public:
static constexpr const char *DLL_NAME = "vulkan-1.dll";
private:
static Vulkan_Hook* _inst;
// Variables
bool _Hooked;
bool _WindowsHooked;
bool _Initialized;
// Functions
Vulkan_Hook();
void _ResetRenderState();
void _PrepareForOverlay();
// Hook to render functions
static VKAPI_ATTR VkResult VKAPI_CALL MyvkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo);
decltype(::vkQueuePresentKHR)* vkQueuePresentKHR;
public:
std::string LibraryName;
virtual ~Vulkan_Hook();
virtual bool StartHook(std::function<bool(bool)> key_combination_callback);
virtual bool IsStarted();
static Vulkan_Hook* Inst();
virtual std::string GetLibraryName() const;
void LoadFunctions(decltype(::vkQueuePresentKHR)* _vkQueuePresentKHR);
virtual std::weak_ptr<uint64_t> CreateImageResource(const void* image_data, uint32_t width, uint32_t height);
virtual void ReleaseImageResource(std::weak_ptr<uint64_t> resource);
};

View file

@ -1,75 +1,152 @@
#include "Windows_Hook.h"
#include "../Renderer_Detector.h"
#include "../../dll/dll.h"
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef EMU_OVERLAY
#include "Windows_Hook.h"
#include <imgui.h>
#include <impls/windows/imgui_impl_win32.h>
#include <backends/imgui_impl_win32.h>
#include <System/Library.h>
extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
constexpr decltype(Windows_Hook::DLL_NAME) Windows_Hook::DLL_NAME;
Windows_Hook* Windows_Hook::_inst = nullptr;
bool Windows_Hook::start_hook()
bool Windows_Hook::StartHook(std::function<bool(bool)>& _key_combination_callback)
{
bool res = true;
if (!hooked)
if (!_Hooked)
{
GetRawInputBuffer = ::GetRawInputBuffer;
GetRawInputData = ::GetRawInputData;
SetCursorPos = ::SetCursorPos;
void* hUser32 = System::Library::GetLibraryHandle(DLL_NAME);
if (hUser32 == nullptr)
{
SPDLOG_WARN("Failed to hook Windows: Cannot find {}", DLL_NAME);
return false;
}
PRINT_DEBUG("Hooked Windows\n");
System::Library::Library libUser32;
LibraryName = System::Library::GetLibraryPath(hUser32);
if (!libUser32.OpenLibrary(LibraryName, false))
{
SPDLOG_WARN("Failed to hook Windows: Cannot load {}", LibraryName);
return false;
}
GetRawInputBuffer = libUser32.GetSymbol<decltype(::GetRawInputBuffer)>("GetRawInputBuffer");
GetRawInputData = libUser32.GetSymbol<decltype(::GetRawInputData)>("GetRawInputData");
GetKeyState = libUser32.GetSymbol<decltype(::GetKeyState)>("GetKeyState");
GetAsyncKeyState = libUser32.GetSymbol<decltype(::GetAsyncKeyState)>("GetAsyncKeyState");
GetKeyboardState = libUser32.GetSymbol<decltype(::GetKeyboardState)>("GetKeyboardState");
GetCursorPos = libUser32.GetSymbol<decltype(::GetCursorPos)>("GetCursorPos");
SetCursorPos = libUser32.GetSymbol<decltype(::SetCursorPos)>("SetCursorPos");
if(GetRawInputBuffer == nullptr ||
GetRawInputData == nullptr ||
GetKeyState == nullptr ||
GetAsyncKeyState == nullptr ||
GetKeyboardState == nullptr ||
GetCursorPos == nullptr ||
SetCursorPos == nullptr)
{
SPDLOG_ERROR("Failed to hook Windows: Events functions missing.");
return false;
}
SPDLOG_INFO("Hooked Windows");
_KeyCombinationCallback = std::move(_key_combination_callback);
BeginHook();
HookFuncs(
std::make_pair<void**, void*>(&(PVOID&)GetRawInputBuffer, &Windows_Hook::MyGetRawInputBuffer),
std::make_pair<void**, void*>(&(PVOID&)GetRawInputData , &Windows_Hook::MyGetRawInputData),
std::make_pair<void**, void*>(&(PVOID&)SetCursorPos , &Windows_Hook::MySetCursorPos)
std::make_pair<void**, void*>(&(PVOID&)GetKeyState , &Windows_Hook::MyGetKeyState),
std::make_pair<void**, void*>(&(PVOID&)GetAsyncKeyState , &Windows_Hook::MyGetAsyncKeyState),
std::make_pair<void**, void*>(&(PVOID&)GetKeyboardState , &Windows_Hook::MyGetKeyboardState),
std::make_pair<void**, void*>(&(PVOID&)GetCursorPos , &Windows_Hook::MyGetCursorPos),
std::make_pair<void**, void*>(&(PVOID&)SetCursorPos , &Windows_Hook::MySetCursorPos)
);
EndHook();
hooked = true;
_Hooked = true;
}
return res;
return true;
}
void Windows_Hook::resetRenderState()
void Windows_Hook::_ResetRenderState()
{
if (initialized)
if (_Initialized)
{
initialized = false;
SetWindowLongPtr(_game_hwnd, GWLP_WNDPROC, (LONG_PTR)_game_wndproc);
_game_hwnd = nullptr;
_game_wndproc = nullptr;
_Initialized = false;
SetWindowLongPtr(_GameHwnd, GWLP_WNDPROC, (LONG_PTR)_GameWndProc);
_GameHwnd = nullptr;
_GameWndProc = nullptr;
ImGui_ImplWin32_Shutdown();
}
}
void Windows_Hook::prepareForOverlay(HWND hWnd)
bool Windows_Hook::_PrepareForOverlay(HWND hWnd)
{
if (!initialized)
if (_GameHwnd != hWnd)
_ResetRenderState();
if (!_Initialized)
{
ImGui_ImplWin32_Init(hWnd);
_GameHwnd = hWnd;
ImGui_ImplWin32_Init(_GameHwnd);
_game_hwnd = hWnd;
_game_wndproc = (WNDPROC)SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)&Windows_Hook::HookWndProc);
initialized = true;
_GameWndProc = (WNDPROC)SetWindowLongPtr(_GameHwnd, GWLP_WNDPROC, (LONG_PTR)&Windows_Hook::HookWndProc);
_Initialized = true;
}
ImGui_ImplWin32_NewFrame();
if (_Initialized)
{
void* current_proc = (void*)GetWindowLongPtr(_GameHwnd, GWLP_WNDPROC);
if (current_proc == nullptr)
return false;
ImGui_ImplWin32_NewFrame();
// Read keyboard modifiers inputs
auto& io = ImGui::GetIO();
POINT pos;
if (this->GetCursorPos(&pos) && ScreenToClient(hWnd, &pos))
{
io.MousePos = ImVec2((float)pos.x, (float)pos.y);
}
io.KeyCtrl = (this->GetKeyState(VK_CONTROL) & 0x8000) != 0;
io.KeyShift = (this->GetKeyState(VK_SHIFT) & 0x8000) != 0;
io.KeyAlt = (this->GetKeyState(VK_MENU) & 0x8000) != 0;
return true;
}
return false;
}
HWND Windows_Hook::GetGameHwnd() const
{
return _game_hwnd;
return _GameHwnd;
}
WNDPROC Windows_Hook::GetGameWndProc() const
{
return _game_wndproc;
return _GameWndProc;
}
/////////////////////////////////////////////////////////////////////////////////////
@ -97,112 +174,207 @@ bool IgnoreMsg(UINT uMsg)
return false;
}
void RawMouseEvent(RAWINPUT& raw)
void RawEvent(RAWINPUT& raw)
{
if (raw.header.dwType == RIM_TYPEMOUSE)
HWND hWnd = Windows_Hook::Inst()->GetGameHwnd();
switch(raw.header.dwType)
{
if (raw.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_LBUTTONDOWN, 0, 0);
else if (raw.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_LBUTTONUP, 0, 0);
else if (raw.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_MBUTTONDOWN, 0, 0);
else if (raw.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_MBUTTONUP, 0, 0);
else if (raw.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_RBUTTONDOWN, 0, 0);
else if (raw.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(Windows_Hook::Inst()->GetGameHwnd(), WM_RBUTTONUP, 0, 0);
case RIM_TYPEMOUSE:
if (raw.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_LBUTTONDOWN, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_LBUTTONUP, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_RBUTTONDOWN, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_RBUTTONUP, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_MBUTTONDOWN, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_UP)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_MBUTTONUP, 0, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_WHEEL)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_MOUSEWHEEL, ((WPARAM)raw.data.mouse.usButtonData) << 16, 0);
if (raw.data.mouse.usButtonFlags & RI_MOUSE_HWHEEL)
ImGui_ImplWin32_WndProcHandler(hWnd, WM_MOUSEHWHEEL, ((WPARAM)raw.data.mouse.usButtonData) << 16, 0);
break;
//case RIM_TYPEKEYBOARD:
//ImGui_ImplWin32_WndProcHandler(hWnd, raw.data.keyboard.Message, raw.data.keyboard.VKey, 0);
//break;
}
}
LRESULT CALLBACK Windows_Hook::HookWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
Steam_Overlay* overlay = get_steam_client()->steam_overlay;
bool show = overlay->ShowOverlay();
// Is the event is a key press
if (uMsg == WM_KEYDOWN)
Windows_Hook* inst = Windows_Hook::Inst();
bool skip_input = inst->_KeyCombinationCallback(false);
bool clean_keys = false;
if (inst->_Initialized)
{
// Tab is pressed and was not pressed before
if (wParam == VK_TAB && !(lParam & (1 << 30)))
// Is the event is a key press
if (uMsg == WM_KEYDOWN)
{
// If Left Shift is pressed
if (GetAsyncKeyState(VK_LSHIFT) & (1 << 15))
// Tab is pressed and was not pressed before
if (wParam == VK_TAB && !(lParam & (1 << 30)))
{
show = !overlay->ShowOverlay();
overlay->ShowOverlay(show);
// If Left Shift is pressed
if (inst->GetAsyncKeyState(VK_LSHIFT) & (1 << 15))
{
if (inst->_KeyCombinationCallback(true))
{
skip_input = true;
// Save the last known cursor pos when opening the overlay
// so we can spoof the GetCursorPos return value.
inst->GetCursorPos(&inst->_SavedCursorPos);
}
else
{
clean_keys = true;
}
}
}
}
if (skip_input && IgnoreMsg(uMsg))
{
ImGui_ImplWin32_WndProcHandler(hWnd, uMsg, wParam, lParam);
if (clean_keys)
{
auto& io = ImGui::GetIO();
memset(io.KeysDown, 0, sizeof(io.KeysDown));
}
return 0;
}
}
ImGui_ImplWin32_WndProcHandler(hWnd, uMsg, wParam, lParam);
if (show)
{
if (IgnoreMsg(uMsg))
return 0;
}
// Protect against recursive call of the WindowProc...
if (inst->_RecurseCallCount > 16)
return 0;
++inst->_RecurseCallCount;
// Call the overlay window procedure
return CallWindowProc(Windows_Hook::Inst()->_game_wndproc, hWnd, uMsg, wParam, lParam);
auto res = CallWindowProc(Windows_Hook::Inst()->_GameWndProc, hWnd, uMsg, wParam, lParam);
--inst->_RecurseCallCount;
return res;
}
UINT WINAPI Windows_Hook::MyGetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader)
{
if (pData == nullptr || !get_steam_client()->steam_overlay->ShowOverlay())
return Windows_Hook::Inst()->GetRawInputBuffer(pData, pcbSize, cbSizeHeader);
Windows_Hook* inst = Windows_Hook::Inst();
int res = inst->GetRawInputBuffer(pData, pcbSize, cbSizeHeader);
if (!inst->_Initialized)
return res;
int num = Windows_Hook::Inst()->GetRawInputBuffer(pData, pcbSize, cbSizeHeader);
for (int i = 0; i < num; ++i)
RawMouseEvent(pData[i]);
if (pData != nullptr)
{
for (int i = 0; i < res; ++i)
RawEvent(pData[i]);
}
if (!inst->_KeyCombinationCallback(false))
return res;
return 0;
}
UINT WINAPI Windows_Hook::MyGetRawInputData(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader)
{
if (pData == nullptr || !get_steam_client()->steam_overlay->ShowOverlay())
return Windows_Hook::Inst()->GetRawInputData(hRawInput, uiCommand, pData, pcbSize, cbSizeHeader);
Windows_Hook* inst = Windows_Hook::Inst();
auto res = inst->GetRawInputData(hRawInput, uiCommand, pData, pcbSize, cbSizeHeader);
if (!inst->_Initialized || pData == nullptr)
return res;
Windows_Hook::Inst()->GetRawInputData(hRawInput, uiCommand, pData, pcbSize, cbSizeHeader);
if (uiCommand == RID_INPUT && res == sizeof(RAWINPUT))
RawEvent(*reinterpret_cast<RAWINPUT*>(pData));
RawMouseEvent(*reinterpret_cast<RAWINPUT*>(pData));
if (!inst->_KeyCombinationCallback(false))
return res;
memset(pData, 0, *pcbSize);
*pcbSize = 0;
return 0;
}
BOOL WINAPI Windows_Hook::MySetCursorPos(int x, int y)
SHORT WINAPI Windows_Hook::MyGetKeyState(int nVirtKey)
{
if (get_steam_client()->steam_overlay->ShowOverlay()) {
POINT p;
GetCursorPos(&p);
x = p.x;
y = p.y;
Windows_Hook* inst = Windows_Hook::Inst();
if (inst->_Initialized && inst->_KeyCombinationCallback(false))
return 0;
return inst->GetKeyState(nVirtKey);
}
SHORT WINAPI Windows_Hook::MyGetAsyncKeyState(int vKey)
{
Windows_Hook* inst = Windows_Hook::Inst();
if (inst->_Initialized && inst->_KeyCombinationCallback(false))
return 0;
return inst->GetAsyncKeyState(vKey);
}
BOOL WINAPI Windows_Hook::MyGetKeyboardState(PBYTE lpKeyState)
{
Windows_Hook* inst = Windows_Hook::Inst();
if (inst->_Initialized && inst->_KeyCombinationCallback(false))
return FALSE;
return inst->GetKeyboardState(lpKeyState);
}
BOOL WINAPI Windows_Hook::MyGetCursorPos(LPPOINT lpPoint)
{
Windows_Hook* inst = Windows_Hook::Inst();
BOOL res = inst->GetCursorPos(lpPoint);
if (inst->_Initialized && inst->_KeyCombinationCallback(false) && lpPoint != nullptr)
{
*lpPoint = inst->_SavedCursorPos;
}
return Windows_Hook::Inst()->SetCursorPos(x, y);
return res;
}
BOOL WINAPI Windows_Hook::MySetCursorPos(int X, int Y)
{
Windows_Hook* inst = Windows_Hook::Inst();
if (inst->_Initialized && inst->_KeyCombinationCallback(false))
{// That way, it will fail only if the real API fails.
// Hides error messages on some Unity debug builds.
POINT pos;
inst->GetCursorPos(&pos);
X = pos.x;
Y = pos.y;
}
return inst->SetCursorPos(X, Y);
}
/////////////////////////////////////////////////////////////////////////////////////
Windows_Hook::Windows_Hook() :
initialized(false),
hooked(false),
_game_hwnd(nullptr),
_game_wndproc(nullptr),
_Initialized(false),
_Hooked(false),
_RecurseCallCount(0),
_GameHwnd(nullptr),
_GameWndProc(nullptr),
GetRawInputBuffer(nullptr),
GetRawInputData(nullptr)
GetRawInputData(nullptr),
GetKeyState(nullptr),
GetAsyncKeyState(nullptr),
GetKeyboardState(nullptr)
{
//_library = LoadLibrary(DLL_NAME);
}
Windows_Hook::~Windows_Hook()
{
PRINT_DEBUG("Windows Hook removed\n");
SPDLOG_INFO("Windows Hook removed");
resetRenderState();
//FreeLibrary(reinterpret_cast<HMODULE>(_library));
_ResetRenderState();
_inst = nullptr;
}
@ -215,9 +387,7 @@ Windows_Hook* Windows_Hook::Inst()
return _inst;
}
const char* Windows_Hook::get_lib_name() const
std::string Windows_Hook::GetLibraryName() const
{
return WINDOWS_DLL;
}
#endif//EMU_OVERLAY
return LibraryName;
}

View file

@ -1,52 +1,80 @@
#ifndef __INCLUDED_WINDOWS_HOOK_H__
#define __INCLUDED_WINDOWS_HOOK_H__
/*
* Copyright (C) Nemirtingas
* This file is part of the ingame overlay project
*
* The ingame overlay project is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* The ingame overlay project is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the ingame overlay project; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include "../Base_Hook.h"
#pragma once
#ifdef __WINDOWS__
#ifdef EMU_OVERLAY
#include "../internal_includes.h"
class Windows_Hook : public Base_Hook
class Windows_Hook :
public Base_Hook
{
public:
#define WINDOWS_DLL "user32.dll"
static constexpr const char* DLL_NAME = "user32.dll";
private:
static Windows_Hook* _inst;
// Variables
bool hooked;
bool initialized;
HWND _game_hwnd;
WNDPROC _game_wndproc;
bool _Hooked;
bool _Initialized;
int _RecurseCallCount;
HWND _GameHwnd;
WNDPROC _GameWndProc;
POINT _SavedCursorPos;
// Functions
Windows_Hook();
// Hook to Windows window messages
decltype(GetRawInputBuffer)* GetRawInputBuffer;
decltype(GetRawInputData)* GetRawInputData;
decltype(SetCursorPos)* SetCursorPos;
decltype(::GetRawInputBuffer) *GetRawInputBuffer;
decltype(::GetRawInputData) *GetRawInputData;
decltype(::GetKeyState) *GetKeyState;
decltype(::GetAsyncKeyState) *GetAsyncKeyState;
decltype(::GetKeyboardState) *GetKeyboardState;
decltype(::GetCursorPos) *GetCursorPos;
decltype(::SetCursorPos) *SetCursorPos;
static LRESULT CALLBACK HookWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static UINT WINAPI MyGetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader);
static UINT WINAPI MyGetRawInputData(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader);
static UINT WINAPI MyGetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader);
static UINT WINAPI MyGetRawInputData(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader);
static SHORT WINAPI MyGetKeyState(int nVirtKey);
static SHORT WINAPI MyGetAsyncKeyState(int vKey);
static BOOL WINAPI MyGetKeyboardState(PBYTE lpKeyState);
static BOOL WINAPI MyGetCursorPos(LPPOINT lpPoint);
static BOOL WINAPI MySetCursorPos(int X, int Y);
// In (bool): Is toggle wanted
// Out(bool): Is the overlay visible, if true, inputs will be disabled
std::function<bool(bool)> _KeyCombinationCallback;
static BOOL WINAPI MySetCursorPos(int x, int y);
public:
std::string LibraryName;
virtual ~Windows_Hook();
void resetRenderState();
void prepareForOverlay(HWND);
void _ResetRenderState();
bool _PrepareForOverlay(HWND hWnd);
HWND GetGameHwnd() const;
WNDPROC GetGameWndProc() const;
bool start_hook();
bool StartHook(std::function<bool(bool)>& key_combination_callback);
static Windows_Hook* Inst();
virtual const char* get_lib_name() const;
virtual std::string GetLibraryName() const;
};
#endif//EMU_OVERLAY
#endif//__WINDOWS__
#endif//__INCLUDED_WINDOWS_HOOK_H__

File diff suppressed because it is too large Load diff