| 15 | extern thread_local bool g_in_dxgi_runtime; |
| 16 | |
| 17 | extern "C" HRESULT WINAPI D3D12CreateDevice(IUnknown *pAdapter, D3D_FEATURE_LEVEL MinimumFeatureLevel, REFIID riid, void **ppDevice) |
| 18 | { |
| 19 | const auto trampoline = reshade::hooks::call(D3D12CreateDevice); |
| 20 | |
| 21 | // Pass on unmodified in case this called from within 'Direct3DCreate9', which indicates that the D3D9 runtime is trying to create an internal device for D3D9on12, which should not be hooked |
| 22 | if (g_in_dxgi_runtime) |
| 23 | return trampoline(pAdapter, MinimumFeatureLevel, riid, ppDevice); |
| 24 | |
| 25 | // Need to lock during device creation to ensure an existing device proxy cannot be destroyed in while it is queried below |
| 26 | const std::unique_lock<std::shared_mutex> lock(g_d3d12_adapter_mutex); |
| 27 | |
| 28 | reshade::log::message( |
| 29 | reshade::log::level::info, |
| 30 | "Redirecting D3D12CreateDevice(pAdapter = %p, MinimumFeatureLevel = %x, riid = %s, ppDevice = %p) ...", |
| 31 | pAdapter, MinimumFeatureLevel, reshade::log::iid_to_string(riid).c_str(), ppDevice); |
| 32 | |
| 33 | com_ptr<DXGIAdapter> adapter_proxy; |
| 34 | if (pAdapter && SUCCEEDED(pAdapter->QueryInterface(&adapter_proxy))) |
| 35 | pAdapter = adapter_proxy->_orig; |
| 36 | |
| 37 | #if RESHADE_ADDON >= 2 |
| 38 | if (ppDevice != nullptr) |
| 39 | { |
| 40 | reshade::load_addons(); |
| 41 | |
| 42 | uint32_t api_version = static_cast<uint32_t>(MinimumFeatureLevel); |
| 43 | if (reshade::invoke_addon_event<reshade::addon_event::create_device>(reshade::api::device_api::d3d12, api_version)) |
| 44 | { |
| 45 | MinimumFeatureLevel = static_cast<D3D_FEATURE_LEVEL>(api_version); |
| 46 | } |
| 47 | } |
| 48 | #endif |
| 49 | |
| 50 | // NVIDIA Ansel creates a D3D11 device internally, so to avoid hooking that, set the flag that forces 'D3D11CreateDevice' to return early |
| 51 | g_in_dxgi_runtime = true; |
| 52 | const HRESULT hr = trampoline(pAdapter, MinimumFeatureLevel, riid, ppDevice); |
| 53 | g_in_dxgi_runtime = false; |
| 54 | |
| 55 | // Skip calls that only check feature level support |
| 56 | if (ppDevice == nullptr) |
| 57 | return hr; |
| 58 | |
| 59 | if (FAILED(hr)) |
| 60 | { |
| 61 | #if RESHADE_ADDON >= 2 |
| 62 | reshade::unload_addons(); |
| 63 | #endif |
| 64 | |
| 65 | reshade::log::message(reshade::log::level::warning, "D3D12CreateDevice failed with error code %s.", reshade::log::hr_to_string(hr).c_str()); |
| 66 | return hr; |
| 67 | } |
| 68 | |
| 69 | // The returned device should alway implement the 'ID3D12Device' base interface |
| 70 | const auto device = static_cast<ID3D12Device *>(*ppDevice); |
| 71 | |
| 72 | // Direct3D 12 devices are singletons per adapter, so first check if one was already created previously |
| 73 | D3D12Device *device_proxy = nullptr; |
| 74 | D3D12Device *const device_proxy_existing = get_private_pointer_d3dx<D3D12Device>(device); |