DirectX中不同的Device或者Context使用共享资源

在游戏中,经常都提供我们可以切换DirectX版本的,而且在编写一些渲染插件的时候,也会遇到不同的Device或者Context使用相同的资源,这种情况下,如果不将资源设为共享而直接调用,就会因为抢占资源而导致Crash。

使用资源的方法

//创建共享资源并设置MiscFlags=D3D11_RESOURCE_MISC_SHARED,然后获取SharedHandle.
D3D11_TEXTURE2D_DESC desc;
desc.Width = SZVRCompositorComponent::g_renderWidth;
desc.Height = SZVRCompositorComponent::g_renderHeight;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.CPUAccessFlags = 0;
desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;

LLGFL_D3D11_CreateTexture(m_device.Get(), &desc, nullptr, sharedTexture_hmd.GetAddressOf());
IDXGIResource* pResource = nullptr;
auto hr = sharedTexture_hmd->QueryInterface(__uuidof(IDXGIResource), reinterpret_cast<void**>(&pResource));
if (!FAILED(hr))
{
	pResource->GetSharedHandle(&sharedTextureHandle_hmd);
}
//初始化资源共享对象,通过SharedHandle来打开共享资源,然后调用QueryInterface强制转换为想要的类型

Microsoft::WRL::ComPtr<ID3D11Texture2D> g_pD3D11LeftSharedTexture;//声明共享资源的指针

left_handle=sharedTextureHandle_hmd;
Microsoft::WRL::ComPtr<ID3D11Resource> resourceTexture_Left = nullptr;
device->OpenSharedResource(left_handle, __uuidof(ID3D11Resource), reinterpret_cast<void**>(resourceTexture_Left.GetAddressOf()));

if (resourceTexture_Left == nullptr)
{
	SDKCompositorShowDebugMessageBox(L"Resource Open Failed");
	return;
}

resourceTexture_Left->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(g_pD3D11LeftSharedTexture.GetAddressOf()));

然后就可以对g_pD3D11LeftSharedTexture进行各种操作了

ID3D11DeviceContext* ctx = nullptr;
	device->GetImmediateContext(&ctx);
	ctx->CopySubresourceRegion(g_pD3D11LeftSharedTexture.Get(), 0, 0, 0, 0, pLeftTexture, 0, nullptr);

猜你喜欢

转载自blog.csdn.net/shujianlove0/article/details/84936882