Skip to content

Instantly share code, notes, and snippets.

@mminer
Created December 8, 2018 00:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mminer/7ee581c31893d719a7c516ca15a6334a to your computer and use it in GitHub Desktop.
Save mminer/7ee581c31893d719a7c516ca15a6334a to your computer and use it in GitHub Desktop.
Gets a shared texture handle from an Unreal texture.
#include "SharedTexture.h"
FSharedTexture FSharedTexture::FromRenderTarget(const UTextureRenderTarget2D& RenderTarget)
{
const FTextureRHIRef TextureRHI = RenderTarget.Resource->TextureRHI;
if (TextureRHI == nullptr)
{
return {};
}
void* NativeResource = TextureRHI->GetNativeResource();
// GetNativeResource returns a different type depending on the platform.
// For Windows, a DirectX 11 texture should be a safe bet.
ID3D11Texture2D* D3D11Texture2D = static_cast<ID3D11Texture2D*>(NativeResource);
const unsigned long Handle = GetHandle(*D3D11Texture2D);
if (Handle == 0)
{
return {};
}
FSharedTexture SharedTexture;
SharedTexture.Handle = Handle;
SharedTexture.Format = GetFormat(*D3D11Texture2D);
SharedTexture.Width = RenderTarget.SizeX;
SharedTexture.Height = RenderTarget.SizeY;
return SharedTexture;
}
unsigned long FSharedTexture::GetHandle(ID3D11Texture2D& D3D11Texture2D)
{
IDXGIResource* DXGIResource;
const HRESULT DXGIResourceResult = D3D11Texture2D.QueryInterface(
__uuidof(IDXGIResource),
reinterpret_cast<void**>(&DXGIResource)
);
if (FAILED(DXGIResourceResult))
{
return 0;
}
HANDLE SharedHandle;
const HRESULT SharedHandleResult = DXGIResource->GetSharedHandle(&SharedHandle);
DXGIResource->Release();
if (FAILED(SharedHandleResult))
{
return 0;
}
return HandleToULong(SharedHandle);
}
int FSharedTexture::GetFormat(ID3D11Texture2D& D3D11Texture2D)
{
D3D11_TEXTURE2D_DESC TextureDescription;
D3D11Texture2D.GetDesc(&TextureDescription);
return static_cast<int>(TextureDescription.Format);
}
#pragma once
#include "Engine/TextureRenderTarget2D.h"
#include "Windows/AllowWindowsPlatformTypes.h"
#include <d3d11.h>
#include "Windows/HideWindowsPlatformTypes.h"
struct FSharedTexture
{
unsigned long Handle = 0;
int Format = 0;
int Width = 0;
int Height = 0;
static FSharedTexture FromRenderTarget(const UTextureRenderTarget2D& RenderTarget);
private:
static unsigned long GetHandle(ID3D11Texture2D& D3D11Texture2D);
static int GetFormat(ID3D11Texture2D& D3D11Texture2D);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment