/** Preprocesses a shader without performing compilation, and dump it out for debugging*/ void D3D9PreProcessShader( const TCHAR* strFilename, const FString& strShaderFile, vector<D3DXMACRO>& Defines, const FD3DIncludeEnvironment& Environment, const TCHAR* strShaderPath ) { TRefCountPtr<ID3DXBuffer> ShaderCode; TRefCountPtr<ID3DXBuffer> ErrorText; FTCHARToANSI AnsiShaderFile(strShaderFile.c_str()); FD3DIncludeEnvironment IncludeEnvironment(Environment); HRESULT ret = D3DXPreprocessShader( (ANSICHAR*)AnsiShaderFile, strShaderFile.size(), &Defines.at(0), &IncludeEnvironment, ShaderCode.GetInitReference(), ErrorText.GetInitReference() ); if( FAILED(ret) ) { debugf(NAME_Warning, TEXT("Preprocess failed for shader %s: %s"), strFilename, ANSI_TO_TCHAR(ErrorText->GetBufferPointer())); } else { TCHAR Tmp[MAX_SPRINTF]; appSprintf(Tmp, TEXT("%s%s.pre"), strShaderPath, strFilename); appSaveStringToFile(ANSI_TO_TCHAR(ShaderCode->GetBufferPointer()), Tmp); } }
void FDeferredShadingSceneRenderer::RenderVisualizeTexturePool() { TRefCountPtr<IPooledRenderTarget> VisualizeTexturePool; /** Resolution for the texture pool visualizer texture. */ enum { TexturePoolVisualizerSizeX = 280, TexturePoolVisualizerSizeY = 140, }; FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(FIntPoint(TexturePoolVisualizerSizeX, TexturePoolVisualizerSizeY), PF_B8G8R8A8, TexCreate_None, TexCreate_None, false)); GRenderTargetPool.FindFreeElement(Desc, VisualizeTexturePool, TEXT("VisualizeTexturePool")); uint32 Pitch; FColor* TextureData = (FColor*)RHILockTexture2D((FTexture2DRHIRef&)VisualizeTexturePool->GetRenderTargetItem().ShaderResourceTexture, 0, RLM_WriteOnly, Pitch, false ); if(TextureData) { // clear with grey to get reliable background color FMemory::Memset(TextureData, 0x88, TexturePoolVisualizerSizeX * TexturePoolVisualizerSizeY * 4); RHIGetTextureMemoryVisualizeData(TextureData, TexturePoolVisualizerSizeX, TexturePoolVisualizerSizeY, Pitch, 4096); } RHIUnlockTexture2D((FTexture2DRHIRef&)VisualizeTexturePool->GetRenderTargetItem().ShaderResourceTexture, 0, false); FIntPoint RTExtent = GSceneRenderTargets.GetBufferSizeXY(); FVector2D Tex00 = FVector2D(0, 0); FVector2D Tex11 = FVector2D(1, 1); //todo VisualizeTexture(*VisualizeTexturePool, ViewFamily.RenderTarget, FIntRect(0, 0, RTExtent.X, RTExtent.Y), RTExtent, 1.0f, 0.0f, 0.0f, Tex00, Tex11, 1.0f, false); }
FDynamicRHI* FD3D12DynamicRHIModule::CreateRHI() { TRefCountPtr<IDXGIFactory4> DXGIFactory; SafeCreateDXGIFactory(DXGIFactory.GetInitReference()); check(DXGIFactory); return new FD3D12DynamicRHI(DXGIFactory, ChosenAdapter); }
void FRCPassPostProcessVisualizeLPV::Process(FRenderingCompositePassContext& Context) { SCOPED_DRAW_EVENT(Context.RHICmdList, VisualizeLPV); const FSceneView& View = Context.View; const FSceneViewFamily& ViewFamily = *(View.Family); // const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context); const TRefCountPtr<IPooledRenderTarget> RenderTarget = GetInput(ePId_Input0)->GetOutput()->PooledRenderTarget; const FSceneRenderTargetItem& DestRenderTarget = RenderTarget->GetRenderTargetItem(); // Set the view family's render target/viewport. SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef()); { FRenderTargetTemp TempRenderTarget(View, (const FTexture2DRHIRef&)DestRenderTarget.TargetableTexture); FCanvas Canvas(&TempRenderTarget, NULL, ViewFamily.CurrentRealTime, ViewFamily.CurrentWorldTime, ViewFamily.DeltaWorldTime, View.GetFeatureLevel()); float X = 30; float Y = 28; const float YStep = 14; const float ColumnWidth = 250; Canvas.DrawShadowedString( X, Y += YStep, TEXT("VisualizeLightPropagationVolume"), GetStatsFont(), FLinearColor(0.2f, 0.2f, 1)); Y += YStep; const FLightPropagationVolumeSettings& Dest = View.FinalPostProcessSettings.BlendableManager.GetSingleFinalDataConst<FLightPropagationVolumeSettings>(); #define ENTRY(name)\ Canvas.DrawShadowedString( X, Y += YStep, TEXT(#name) TEXT(":"), GetStatsFont(), FLinearColor(1, 1, 1));\ Canvas.DrawShadowedString( X + ColumnWidth, Y, *FString::Printf(TEXT("%g"), Dest.name), GetStatsFont(), FLinearColor(1, 1, 1)); ENTRY(LPVIntensity) ENTRY(LPVVplInjectionBias) ENTRY(LPVSize) ENTRY(LPVSecondaryOcclusionIntensity) ENTRY(LPVSecondaryBounceIntensity) ENTRY(LPVGeometryVolumeBias) ENTRY(LPVEmissiveInjectionIntensity) ENTRY(LPVDirectionalOcclusionIntensity) ENTRY(LPVDirectionalOcclusionRadius) ENTRY(LPVDiffuseOcclusionExponent) ENTRY(LPVSpecularOcclusionExponent) ENTRY(LPVDiffuseOcclusionIntensity) ENTRY(LPVSpecularOcclusionIntensity) #undef ENTRY Canvas.Flush_RenderThread(Context.RHICmdList); } Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams()); // to satify following passws FRenderingCompositeOutput* Output = GetOutput(ePId_Output0); Output->PooledRenderTarget = RenderTarget; }
void FSlateD3DRenderer::DrawWindows( FSlateDrawBuffer& InWindowDrawBuffer ) { // Update the font cache with new text before elements are batched FontCache->UpdateCache(); // Iterate through each element list and set up an RHI window for it if needed TArray<FSlateWindowElementList>& WindowElementLists = InWindowDrawBuffer.GetWindowElementLists(); for( int32 ListIndex = 0; ListIndex < WindowElementLists.Num(); ++ListIndex ) { FSlateWindowElementList& ElementList = WindowElementLists[ListIndex]; if ( ElementList.GetWindow().IsValid() ) { TSharedRef<SWindow> WindowToDraw = ElementList.GetWindow().ToSharedRef(); // Add all elements for this window to the element batcher ElementBatcher->AddElements( ElementList.GetDrawElements() ); bool bUnused = false; ElementBatcher->FillBatchBuffers( ElementList, bUnused ); // All elements for this window have been batched and rendering data updated ElementBatcher->ResetBatches(); FVector2D WindowSize = WindowToDraw->GetSizeInScreen(); FSlateD3DViewport* Viewport = WindowToViewportMap.Find( &WindowToDraw.Get() ); check(Viewport); RenderingPolicy->UpdateBuffers( ElementList ); check(Viewport); GD3DDeviceContext->RSSetViewports(1, &Viewport->ViewportInfo ); ID3D11RenderTargetView* RTV = Viewport->RenderTargetView; ID3D11DepthStencilView* DSV = Viewport->DepthStencilView; GD3DDeviceContext->OMSetRenderTargets( 1, &RTV, NULL ); RenderingPolicy->DrawElements( ViewMatrix*Viewport->ProjectionMatrix, ElementList.GetRenderBatches() ); GD3DDeviceContext->OMSetRenderTargets(0, NULL, NULL); const bool bUseVSync = false; Viewport->D3DSwapChain->Present( bUseVSync ? 1 : 0, 0); // All elements have been drawn. Reset all cached data ElementBatcher->ResetBatches(); } } // flush the cache if needed FontCache->ConditionalFlushCache(); }
void FSlateD3DRenderer::Destroy() { FSlateShaderParameterMap::Get().Shutdown(); ElementBatcher.Reset(); RenderingPolicy.Reset(); TextureManager.Reset(); GD3DDevice.SafeRelease(); GD3DDeviceContext.SafeRelease(); }
FD3D11Viewport::FD3D11Viewport(FD3D11DynamicRHI* InD3DRHI,HWND InWindowHandle,uint32 InSizeX,uint32 InSizeY,bool bInIsFullscreen, EPixelFormat InPreferredPixelFormat): D3DRHI(InD3DRHI), LastFlipTime(0), LastFrameComplete(0), LastCompleteTime(0), SyncCounter(0), bSyncedLastFrame(false), WindowHandle(InWindowHandle), MaximumFrameLatency(3), SizeX(InSizeX), SizeY(InSizeY), bIsFullscreen(bInIsFullscreen), PixelFormat(InPreferredPixelFormat), bIsValid(true), FrameSyncEvent(InD3DRHI) { check(IsInGameThread()); D3DRHI->Viewports.Add(this); // Ensure that the D3D device has been created. D3DRHI->InitD3DDevice(); // Create a backbuffer/swapchain for each viewport TRefCountPtr<IDXGIDevice> DXGIDevice; VERIFYD3D11RESULT(D3DRHI->GetDevice()->QueryInterface( IID_IDXGIDevice, (void**)DXGIDevice.GetInitReference() )); // Create the swapchain. DXGI_SWAP_CHAIN_DESC SwapChainDesc; FMemory::Memzero( &SwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC) ); SwapChainDesc.BufferDesc = SetupDXGI_MODE_DESC(); // MSAA Sample count SwapChainDesc.SampleDesc.Count = 1; SwapChainDesc.SampleDesc.Quality = 0; SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; // 1:single buffering, 2:double buffering, 3:triple buffering SwapChainDesc.BufferCount = 1; SwapChainDesc.OutputWindow = WindowHandle; SwapChainDesc.Windowed = !bIsFullscreen; // DXGI_SWAP_EFFECT_DISCARD / DXGI_SWAP_EFFECT_SEQUENTIAL SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; SwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; VERIFYD3D11RESULT(D3DRHI->GetFactory()->CreateSwapChain(DXGIDevice,&SwapChainDesc,SwapChain.GetInitReference())); // Set the DXGI message hook to not change the window behind our back. D3DRHI->GetFactory()->MakeWindowAssociation(WindowHandle,DXGI_MWA_NO_WINDOW_CHANGES); // Create a RHI surface to represent the viewport's back buffer. BackBuffer = GetSwapChainSurface(D3DRHI, PixelFormat, SwapChain); // Tell the window to redraw when they can. // @todo: For Slate viewports, it doesn't make sense to post WM_PAINT messages (we swallow those.) ::PostMessage( WindowHandle, WM_PAINT, 0, 0 ); BeginInitResource(&FrameSyncEvent); }
/** Applies screen space radial blur passes. */ void ApplyRadialBlurPasses( FRHICommandListImmediate& RHICmdList, const FViewInfo& View, const FLightSceneInfo* const LightSceneInfo, /** First pass source - this will not be overwritten. */ TRefCountPtr<IPooledRenderTarget>& FirstPassSource, /** Subsequent pass source, will also contain the final result. */ TRefCountPtr<IPooledRenderTarget>& LightShaftsSource, /** First pass dest. */ TRefCountPtr<IPooledRenderTarget>& LightShaftsDest) { TShaderMapRef<FScreenVS> ScreenVertexShader(View.ShaderMap); const FIntPoint BufferSize = FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(); const uint32 DownsampleFactor = GetLightShaftDownsampleFactor(); const FIntPoint FilterBufferSize = BufferSize / DownsampleFactor; const FIntPoint DownSampledXY = View.ViewRect.Min / DownsampleFactor; const uint32 DownsampledSizeX = View.ViewRect.Width() / DownsampleFactor; const uint32 DownsampledSizeY = View.ViewRect.Height() / DownsampleFactor; const uint32 NumPasses = FMath::Max(GLightShaftBlurPasses, 0); for (uint32 PassIndex = 0; PassIndex < NumPasses; PassIndex++) { SetRenderTarget(RHICmdList, LightShaftsDest->GetRenderTargetItem().TargetableTexture, FTextureRHIRef()); RHICmdList.SetViewport(0, 0, 0.0f, FilterBufferSize.X, FilterBufferSize.Y, 1.0f); RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); TShaderMapRef<FBlurLightShaftsPixelShader> BlurLightShaftsPixelShader(View.ShaderMap); SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BlurLightShaftsBoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *ScreenVertexShader, *BlurLightShaftsPixelShader); TRefCountPtr<IPooledRenderTarget>& EffectiveSource = PassIndex == 0 ? FirstPassSource : LightShaftsSource; /// ? BlurLightShaftsPixelShader->SetParameters(RHICmdList, LightSceneInfo, View, PassIndex, EffectiveSource); { // Apply a radial blur to the bloom and occlusion mask DrawRectangle( RHICmdList, DownSampledXY.X, DownSampledXY.Y, DownsampledSizeX, DownsampledSizeY, DownSampledXY.X, DownSampledXY.Y, DownsampledSizeX, DownsampledSizeY, FilterBufferSize, FilterBufferSize, *ScreenVertexShader, EDRF_UseTriangleOptimization); } RHICmdList.CopyToResolveTarget(LightShaftsDest->GetRenderTargetItem().TargetableTexture, LightShaftsDest->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); // Swap input and output for the next pass Swap(LightShaftsSource, LightShaftsDest); } }
/** * Creates a FD3D11Surface to represent a swap chain's back buffer. */ FD3D11Texture2D* GetSwapChainSurface(FD3D11DynamicRHI* D3DRHI,IDXGISwapChain* SwapChain) { // Grab the back buffer TRefCountPtr<ID3D11Texture2D> BackBufferResource; VERIFYD3D11RESULT_EX(SwapChain->GetBuffer(0,IID_ID3D11Texture2D,(void**)BackBufferResource.GetInitReference()), D3DRHI->GetDevice()); // create the render target view TRefCountPtr<ID3D11RenderTargetView> BackBufferRenderTargetView; D3D11_RENDER_TARGET_VIEW_DESC RTVDesc; RTVDesc.Format = DXGI_FORMAT_UNKNOWN; RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; RTVDesc.Texture2D.MipSlice = 0; VERIFYD3D11RESULT(D3DRHI->GetDevice()->CreateRenderTargetView(BackBufferResource,&RTVDesc,BackBufferRenderTargetView.GetInitReference())); D3D11_TEXTURE2D_DESC TextureDesc; BackBufferResource->GetDesc(&TextureDesc); TArray<TRefCountPtr<ID3D11RenderTargetView> > RenderTargetViews; RenderTargetViews.Add(BackBufferRenderTargetView); // create a shader resource view to allow using the backbuffer as a texture TRefCountPtr<ID3D11ShaderResourceView> BackBufferShaderResourceView; D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; SRVDesc.Format = DXGI_FORMAT_UNKNOWN; SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MostDetailedMip = 0; SRVDesc.Texture2D.MipLevels = 1; VERIFYD3D11RESULT(D3DRHI->GetDevice()->CreateShaderResourceView(BackBufferResource,&SRVDesc,BackBufferShaderResourceView.GetInitReference())); FD3D11Texture2D* NewTexture = new FD3D11Texture2D( D3DRHI, BackBufferResource, BackBufferShaderResourceView, false, 1, RenderTargetViews, NULL, TextureDesc.Width, TextureDesc.Height, 1, 1, 1, PF_A2B10G10R10, false, false, false ); D3D11TextureAllocated2D(*NewTexture); NewTexture->DoNoDeferDelete(); return NewTexture; }
FIndexBufferRHIRef FD3D11DynamicRHI::RHICreateIndexBuffer(uint32 Stride,uint32 Size,uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { // Explicitly check that the size is nonzero before allowing CreateIndexBuffer to opaquely fail. check(Size > 0); // Describe the index buffer. D3D11_BUFFER_DESC Desc; ZeroMemory( &Desc, sizeof( D3D11_BUFFER_DESC ) ); Desc.ByteWidth = Size; Desc.Usage = (InUsage & BUF_AnyDynamic) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; Desc.BindFlags = D3D11_BIND_INDEX_BUFFER; Desc.CPUAccessFlags = (InUsage & BUF_AnyDynamic) ? D3D11_CPU_ACCESS_WRITE : 0; Desc.MiscFlags = 0; if (InUsage & BUF_UnorderedAccess) { Desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS; } if(InUsage & BUF_DrawIndirect) { Desc.MiscFlags |= D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS; } if (InUsage & BUF_ShaderResource) { Desc.BindFlags |= D3D11_BIND_SHADER_RESOURCE; } // If a resource array was provided for the resource, create the resource pre-populated D3D11_SUBRESOURCE_DATA InitData; D3D11_SUBRESOURCE_DATA* pInitData = NULL; if(CreateInfo.ResourceArray) { check(Size == CreateInfo.ResourceArray->GetResourceDataSize()); InitData.pSysMem = CreateInfo.ResourceArray->GetResourceData(); InitData.SysMemPitch = Size; InitData.SysMemSlicePitch = 0; pInitData = &InitData; } TRefCountPtr<ID3D11Buffer> IndexBufferResource; VERIFYD3D11RESULT(Direct3DDevice->CreateBuffer(&Desc,pInitData,IndexBufferResource.GetInitReference())); UpdateBufferStats(IndexBufferResource, true); if(CreateInfo.ResourceArray) { // Discard the resource array's contents. CreateInfo.ResourceArray->Discard(); } return new FD3D11IndexBuffer(IndexBufferResource, Stride, Size, InUsage); }
void FSlateD3DRenderer::CreateBackBufferResources( TRefCountPtr<IDXGISwapChain>& InSwapChain, TRefCountPtr<ID3D11Texture2D>& OutBackBuffer, TRefCountPtr<ID3D11RenderTargetView>& OutRTV ) { InSwapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), (void**)OutBackBuffer.GetInitReference() ); D3D11_RENDER_TARGET_VIEW_DESC RTVDesc; RTVDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; RTVDesc.Texture2D.MipSlice = 0; HRESULT Hr = GD3DDevice->CreateRenderTargetView( OutBackBuffer, &RTVDesc, OutRTV.GetInitReference() ); check( SUCCEEDED(Hr) ); }
void PrefilterPlanarReflection(FRHICommandListImmediate& RHICmdList, FViewInfo& View, const FPlanarReflectionSceneProxy* ReflectionSceneProxy, const FRenderTarget* Target) { FTextureRHIParamRef SceneColorInput = FSceneRenderTargets::Get(RHICmdList).GetSceneColorTexture(); if(View.FeatureLevel >= ERHIFeatureLevel::SM4) { // Note: null velocity buffer, so dynamic object temporal AA will not be correct TRefCountPtr<IPooledRenderTarget> VelocityRT; TRefCountPtr<IPooledRenderTarget> FilteredSceneColor; GPostProcessing.ProcessPlanarReflection(RHICmdList, View, VelocityRT, FilteredSceneColor); if (FilteredSceneColor) { SceneColorInput = FilteredSceneColor->GetRenderTargetItem().ShaderResourceTexture; } } { SCOPED_DRAW_EVENT(RHICmdList, PrefilterPlanarReflection); FRHIRenderTargetView ColorView(Target->GetRenderTargetTexture(), 0, -1, ERenderTargetLoadAction::ENoAction, ERenderTargetStoreAction::EStore); FRHISetRenderTargetsInfo Info(1, &ColorView, FRHIDepthRenderTargetView()); RHICmdList.SetRenderTargetsAndClear(Info); RHICmdList.SetViewport(View.ViewRect.Min.X, View.ViewRect.Min.Y, 0.0f, View.ViewRect.Max.X, View.ViewRect.Max.Y, 1.0f); RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); RHICmdList.SetRasterizerState(TStaticRasterizerState<FM_Solid, CM_None>::GetRHI()); RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI()); TShaderMapRef<TDeferredLightVS<false> > VertexShader(View.ShaderMap); TShaderMapRef<FPrefilterPlanarReflectionPS<bEnablePlanarReflectionPrefilter> > PixelShader(View.ShaderMap); static FGlobalBoundShaderState BoundShaderState; SetGlobalBoundShaderState(RHICmdList, View.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader); PixelShader->SetParameters(RHICmdList, View, ReflectionSceneProxy, SceneColorInput); VertexShader->SetSimpleLightParameters(RHICmdList, View, FSphere(0)); DrawRectangle( RHICmdList, 0, 0, View.ViewRect.Width(), View.ViewRect.Height(), View.ViewRect.Min.X, View.ViewRect.Min.Y, View.ViewRect.Width(), View.ViewRect.Height(), View.ViewRect.Size(), FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(), *VertexShader, EDRF_UseTriangleOptimization); } }
FUnorderedAccessViewRHIRef FD3D12DynamicRHI::RHICreateUnorderedAccessView(FStructuredBufferRHIParamRef StructuredBufferRHI, bool bUseUAVCounter, bool bAppendBuffer) { FD3D12StructuredBuffer* StructuredBuffer = FD3D12DynamicRHI::ResourceCast(StructuredBufferRHI); const D3D12_RESOURCE_DESC& BufferDesc = StructuredBuffer->Resource->GetDesc(); const uint32 BufferUsage = StructuredBuffer->GetUsage(); const bool bByteAccessBuffer = (BufferUsage & BUF_ByteAddressBuffer) != 0; const bool bStructuredBuffer = !bByteAccessBuffer; check(bByteAccessBuffer != bStructuredBuffer); // You can't have a structured buffer that allows raw views D3D12_UNORDERED_ACCESS_VIEW_DESC UAVDesc ={}; UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; UAVDesc.Format = DXGI_FORMAT_UNKNOWN; uint32 EffectiveStride = StructuredBuffer->GetStride(); if (bByteAccessBuffer) { UAVDesc.Format = DXGI_FORMAT_R32_TYPELESS; EffectiveStride = 4; } else if (BufferUsage & BUF_DrawIndirect) { UAVDesc.Format = DXGI_FORMAT_R32_UINT; EffectiveStride = 4; } UAVDesc.Buffer.FirstElement = StructuredBuffer->ResourceLocation->GetOffset() / EffectiveStride; UAVDesc.Buffer.NumElements = StructuredBuffer->ResourceLocation->GetEffectiveBufferSize() / EffectiveStride; UAVDesc.Buffer.StructureByteStride = bStructuredBuffer ? EffectiveStride : 0; UAVDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; UAVDesc.Buffer.CounterOffsetInBytes = 0; const bool bNeedsCounterResource = bAppendBuffer | bUseUAVCounter; TRefCountPtr<FD3D12Resource> CounterResource; if (bNeedsCounterResource) { GetRHIDevice()->GetResourceHelper().CreateBuffer(D3D12_HEAP_TYPE_DEFAULT, 4, CounterResource.GetInitReference(), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); } if (bByteAccessBuffer) { UAVDesc.Buffer.Flags |= D3D12_BUFFER_UAV_FLAG_RAW; } return new FD3D12UnorderedAccessView(GetRHIDevice(), &UAVDesc, StructuredBuffer->ResourceLocation, CounterResource); }
int32 FD3DGPUProfiler::RecordEventTimestamp(ID3D11Device* Direct3DDevice, ID3D11DeviceContext* Direct3DDeviceIMContext) { check(CurrentGPUProfile); D3D11_QUERY_DESC TimestampQueryDesc; TimestampQueryDesc.Query = D3D11_QUERY_TIMESTAMP; TimestampQueryDesc.MiscFlags = 0; TRefCountPtr<ID3D11Query> TimestampQuery; VERIFYD3D11RESULT(Direct3DDevice->CreateQuery(&TimestampQueryDesc,TimestampQuery.GetInitReference())); Direct3DDeviceIMContext->End(TimestampQuery); return CurrentGPUProfile->EventTimestampQueries.Add(TimestampQuery); }
FShaderResourceViewRHIRef FD3D11DynamicRHI::RHICreateShaderResourceView(FStructuredBufferRHIParamRef StructuredBufferRHI) { DYNAMIC_CAST_D3D11RESOURCE(StructuredBuffer,StructuredBuffer); D3D11_BUFFER_DESC BufferDesc; StructuredBuffer->Resource->GetDesc(&BufferDesc); const bool bByteAccessBuffer = (BufferDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS) != 0; // Create a Shader Resource View D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; if ( bByteAccessBuffer ) { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX; SRVDesc.BufferEx.NumElements = BufferDesc.ByteWidth / 4; SRVDesc.BufferEx.FirstElement = 0; SRVDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW; SRVDesc.Format = DXGI_FORMAT_R32_TYPELESS; } else { SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; SRVDesc.Buffer.FirstElement = 0; SRVDesc.Buffer.NumElements = BufferDesc.ByteWidth / BufferDesc.StructureByteStride; SRVDesc.Format = DXGI_FORMAT_UNKNOWN; } TRefCountPtr<ID3D11ShaderResourceView> ShaderResourceView; VERIFYD3D11RESULT(Direct3DDevice->CreateShaderResourceView(StructuredBuffer->Resource, &SRVDesc, (ID3D11ShaderResourceView**)ShaderResourceView.GetInitReference())); return new FD3D11ShaderResourceView(ShaderResourceView,StructuredBuffer); }
void FSlateD3DRenderer::Private_ResizeViewport( const TSharedRef<SWindow> InWindow, uint32 Width, uint32 Height, bool bFullscreen ) { FSlateD3DViewport* Viewport = WindowToViewportMap.Find( &InWindow.Get() ); if( Viewport && ( Width != Viewport->ViewportInfo.Width || Height != Viewport->ViewportInfo.Height || bFullscreen != Viewport->bFullscreen ) ) { GD3DDeviceContext->OMSetRenderTargets(0,NULL,NULL); Viewport->BackBufferTexture.SafeRelease(); Viewport->RenderTargetView.SafeRelease(); Viewport->DepthStencilView.SafeRelease(); Viewport->ViewportInfo.Width = Width; Viewport->ViewportInfo.Height = Height; Viewport->bFullscreen = bFullscreen; Viewport->ProjectionMatrix = CreateProjectionMatrixD3D( Width, Height ); DXGI_SWAP_CHAIN_DESC Desc; Viewport->D3DSwapChain->GetDesc( &Desc ); HRESULT Hr = Viewport->D3DSwapChain->ResizeBuffers( Desc.BufferCount, Viewport->ViewportInfo.Width, Viewport->ViewportInfo.Height, Desc.BufferDesc.Format, Desc.Flags ); check( SUCCEEDED(Hr) ); CreateBackBufferResources( Viewport->D3DSwapChain, Viewport->BackBufferTexture,Viewport->RenderTargetView ); } }
FUnorderedAccessViewRHIRef FD3D11DynamicRHI::RHICreateUnorderedAccessView(FTextureRHIParamRef TextureRHI) { FD3D11TextureBase* Texture = GetD3D11TextureFromRHITexture(TextureRHI); D3D11_UNORDERED_ACCESS_VIEW_DESC UAVDesc; if (TextureRHI->GetTexture3D() != NULL) { FD3D11Texture3D* Texture3D = (FD3D11Texture3D*)Texture; UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D; UAVDesc.Texture3D.MipSlice = 0; UAVDesc.Texture3D.FirstWSlice = 0; UAVDesc.Texture3D.WSize = Texture3D->GetSizeZ(); } else { UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; UAVDesc.Texture2D.MipSlice = 0; } UAVDesc.Format = FindShaderResourceDXGIFormat((DXGI_FORMAT)GPixelFormats[TextureRHI->GetFormat()].PlatformFormat, false); TRefCountPtr<ID3D11UnorderedAccessView> UnorderedAccessView; VERIFYD3D11RESULT(Direct3DDevice->CreateUnorderedAccessView(Texture->GetResource(),&UAVDesc,(ID3D11UnorderedAccessView**)UnorderedAccessView.GetInitReference())); return new FD3D11UnorderedAccessView(UnorderedAccessView,Texture); }
FUnorderedAccessViewRHIRef FD3D11DynamicRHI::RHICreateUnorderedAccessView(FVertexBufferRHIParamRef VertexBufferRHI, uint8 Format) { DYNAMIC_CAST_D3D11RESOURCE(VertexBuffer,VertexBuffer); D3D11_BUFFER_DESC BufferDesc; VertexBuffer->Resource->GetDesc(&BufferDesc); const bool bByteAccessBuffer = (BufferDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS) != 0; D3D11_UNORDERED_ACCESS_VIEW_DESC UAVDesc; UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; UAVDesc.Format = FindUnorderedAccessDXGIFormat((DXGI_FORMAT)GPixelFormats[Format].PlatformFormat); UAVDesc.Buffer.FirstElement = 0; UAVDesc.Buffer.NumElements = BufferDesc.ByteWidth / GPixelFormats[Format].BlockBytes; UAVDesc.Buffer.Flags = 0; if (bByteAccessBuffer) { UAVDesc.Buffer.Flags |= D3D11_BUFFER_UAV_FLAG_RAW; UAVDesc.Format = DXGI_FORMAT_R32_TYPELESS; } TRefCountPtr<ID3D11UnorderedAccessView> UnorderedAccessView; VERIFYD3D11RESULT(Direct3DDevice->CreateUnorderedAccessView(VertexBuffer->Resource,&UAVDesc,(ID3D11UnorderedAccessView**)UnorderedAccessView.GetInitReference())); return new FD3D11UnorderedAccessView(UnorderedAccessView,VertexBuffer); }
FIndexBufferRHIRef FOpenGLDynamicRHI::RHICreateIndexBuffer(uint32 Stride,uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { VERIFY_GL_SCOPE(); const void *Data = NULL; // If a resource array was provided for the resource, create the resource pre-populated if(CreateInfo.ResourceArray) { check(Size == CreateInfo.ResourceArray->GetResourceDataSize()); Data = CreateInfo.ResourceArray->GetResourceData(); } TRefCountPtr<FOpenGLIndexBuffer> IndexBuffer = new FOpenGLIndexBuffer(Stride, Size, InUsage, Data); return IndexBuffer.GetReference(); }
static uint32 CountAdapterOutputs(TRefCountPtr<IDXGIAdapter>& Adapter) { uint32 OutputCount = 0; for(;;) { TRefCountPtr<IDXGIOutput> Output; HRESULT hr = Adapter->EnumOutputs(OutputCount, Output.GetInitReference()); if(FAILED(hr)) { break; } ++OutputCount; } return OutputCount; }
static void BeginVelocityRendering(FRHICommandList& RHICmdList, TRefCountPtr<IPooledRenderTarget>& VelocityRT, bool bPerformClear) { FTextureRHIRef VelocityTexture = VelocityRT->GetRenderTargetItem().TargetableTexture; FTexture2DRHIRef DepthTexture = GSceneRenderTargets.GetSceneDepthTexture(); FLinearColor VelocityClearColor = FLinearColor::Black; if (bPerformClear) { // now make the FRHISetRenderTargetsInfo that encapsulates all of the info FRHIRenderTargetView ColorView(VelocityTexture, 0, -1, ERenderTargetLoadAction::EClear, ERenderTargetStoreAction::EStore); FRHIDepthRenderTargetView DepthView(DepthTexture, ERenderTargetLoadAction::ELoad, ERenderTargetStoreAction::ENoAction, true); FRHISetRenderTargetsInfo Info(1, &ColorView, DepthView); Info.ClearColors[0] = VelocityClearColor; // Clear the velocity buffer (0.0f means "use static background velocity"). RHICmdList.SetRenderTargetsAndClear(Info); } else { SetRenderTarget(RHICmdList, VelocityTexture, DepthTexture, ESimpleRenderTargetMode::EExistingColorAndReadOnlyDepth); // some platforms need the clear color when rendertargets transition to SRVs. We propagate here to allow parallel rendering to always // have the proper mapping when the RT is transitioned. RHICmdList.BindClearMRTValues(true, 1, &VelocityClearColor, false, 1.0f, false, 0); } }
/** * Creates a FStaticMeshRenderData from a D3DXMesh * @param DestMesh Destination mesh to extract to * @param NumUVs Number of UVs * @param Elements Elements array * @return Boolean representing success or failure */ bool ConvertD3DXMeshToRawMesh( TRefCountPtr<ID3DXMesh>& D3DMesh, FRawMesh& DestMesh, int32 NumUVs ) { // Extract simplified data to LOD FUtilVertex* D3DVertices; uint16* D3DIndices; ::DWORD * D3DAttributes; D3DMesh->LockVertexBuffer(D3DLOCK_READONLY,(LPVOID*)&D3DVertices); D3DMesh->LockIndexBuffer(D3DLOCK_READONLY,(LPVOID*)&D3DIndices); D3DMesh->LockAttributeBuffer(D3DLOCK_READONLY,&D3DAttributes); int32 NumFaces = D3DMesh->GetNumFaces(); int32 NumWedges = NumFaces * 3; DestMesh.FaceMaterialIndices.Init(NumFaces); DestMesh.FaceSmoothingMasks.Init(NumFaces); DestMesh.VertexPositions.Init(NumWedges); DestMesh.WedgeIndices.Init(NumWedges); DestMesh.WedgeColors.Init(NumWedges); DestMesh.WedgeTangentX.Init(NumWedges); DestMesh.WedgeTangentY.Init(NumWedges); DestMesh.WedgeTangentZ.Init(NumWedges); for (int32 UVIndex = 0; UVIndex < NumUVs; ++UVIndex) { DestMesh.WedgeTexCoords[UVIndex].Init(NumWedges); } for(int32 I=0;I<NumFaces;I++) { // Copy smoothing mask and index from any vertex into this triangle DestMesh.FaceSmoothingMasks[I] = D3DVertices[D3DIndices[I*3+0]].SmoothingMask; DestMesh.FaceMaterialIndices[I] = D3DAttributes[I]; for(int UVs=0;UVs<NumUVs;UVs++) { DestMesh.WedgeTexCoords[UVs][I*3+0] = D3DVertices[D3DIndices[I*3+0]].UVs[UVs]; DestMesh.WedgeTexCoords[UVs][I*3+1] = D3DVertices[D3DIndices[I*3+1]].UVs[UVs]; DestMesh.WedgeTexCoords[UVs][I*3+2] = D3DVertices[D3DIndices[I*3+2]].UVs[UVs]; } for(int32 K=0;K<3;K++) { DestMesh.WedgeIndices[I*3+K] = I*3+K; DestMesh.VertexPositions[I*3+K] = D3DVertices[D3DIndices[I*3+K]].Position; DestMesh.WedgeColors[I*3+K] = D3DVertices[D3DIndices[I*3+K]].Color; DestMesh.WedgeTangentX[I*3+K] = D3DVertices[D3DIndices[I*3+K]].TangentX; DestMesh.WedgeTangentY[I*3+K] = D3DVertices[D3DIndices[I*3+K]].TangentY; DestMesh.WedgeTangentZ[I*3+K] = D3DVertices[D3DIndices[I*3+K]].TangentZ; } } D3DMesh->UnlockIndexBuffer(); D3DMesh->UnlockVertexBuffer(); D3DMesh->UnlockAttributeBuffer(); return true; }
TRefCountPtr<FReflectionCaptureEncodedHDRDerivedData> FReflectionCaptureEncodedHDRDerivedData::GenerateEncodedHDRData(const FReflectionCaptureFullHDRDerivedData& FullHDRData, const FGuid& StateId, float Brightness) { TRefCountPtr<FReflectionCaptureEncodedHDRDerivedData> EncodedHDRData = new FReflectionCaptureEncodedHDRDerivedData(); const FString KeyString = GetDDCKeyString(StateId); if (!GetDerivedDataCacheRef().GetSynchronous(*KeyString, EncodedHDRData->CapturedData)) { EncodedHDRData->GenerateFromDerivedDataSource(FullHDRData, Brightness); if (EncodedHDRData->CapturedData.Num() > 0) { GetDerivedDataCacheRef().Put(*KeyString, EncodedHDRData->CapturedData); } } check(EncodedHDRData->CapturedData.Num() > 0); INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory,EncodedHDRData->CapturedData.GetAllocatedSize()); return EncodedHDRData; }
static void CompileShader( const FString& Filename, const FString& EntryPoint, const FString& ShaderModel, TRefCountPtr<ID3DBlob>& OutBlob ) { uint32 ShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if UE_BUILD_DEBUG ShaderFlags |= D3D10_SHADER_DEBUG; #else ShaderFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; #endif TRefCountPtr<ID3DBlob> ErrorBlob; HRESULT Hr = D3DX11CompileFromFile( *Filename, NULL, NULL, TCHAR_TO_ANSI(*EntryPoint), TCHAR_TO_ANSI(*ShaderModel), ShaderFlags, 0, NULL, OutBlob.GetInitReference(), ErrorBlob.GetInitReference(), NULL ); if( FAILED(Hr) ) { if( ErrorBlob.GetReference() ) { checkf(0, ANSI_TO_TCHAR(ErrorBlob->GetBufferPointer())); } } }
void FDeferredShadingSceneRenderer::RenderVelocities(FRHICommandListImmediate& RHICmdList, TRefCountPtr<IPooledRenderTarget>& VelocityRT) { check(FeatureLevel >= ERHIFeatureLevel::SM4); SCOPE_CYCLE_COUNTER(STAT_RenderVelocities); if (!ShouldRenderVelocities()) { return; } // this is not supported check(!Views[0].bIsSceneCapture); SCOPED_DRAW_EVENT(RHICmdList, RenderVelocities); FPooledRenderTargetDesc Desc = FVelocityRendering::GetRenderTargetDesc(); GRenderTargetPool.FindFreeElement(Desc, VelocityRT, TEXT("Velocity")); GPrevPerBoneMotionBlur.LockData(); BeginVelocityRendering(RHICmdList, VelocityRT, true); if (GRHICommandList.UseParallelAlgorithms() && CVarParallelVelocity.GetValueOnRenderThread()) { RenderVelocitiesInnerParallel(RHICmdList, VelocityRT); } else { RenderVelocitiesInner(RHICmdList, VelocityRT); } RHICmdList.CopyToResolveTarget(VelocityRT->GetRenderTargetItem().TargetableTexture, VelocityRT->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams()); // restore any color write state changes RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI()); RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI()); GPrevPerBoneMotionBlur.UnlockData(); // to be able to observe results with VisualizeTexture GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, VelocityRT); }
/** * Initializes the static variables, if necessary. */ void FD3D11BufferedGPUTiming::PlatformStaticInitialize(void* UserData) { // Are the static variables initialized? check( !GAreGlobalsInitialized ); // Get the GPU timestamp frequency. GTimingFrequency = 0; TRefCountPtr<ID3D11Query> FreqQuery; FD3D11DynamicRHI* D3DRHI = (FD3D11DynamicRHI*)UserData; ID3D11DeviceContext *D3D11DeviceContext = D3DRHI->GetDeviceContext(); HRESULT D3DResult; D3D11_QUERY_DESC QueryDesc; QueryDesc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT; QueryDesc.MiscFlags = 0; D3DResult = D3DRHI->GetDevice()->CreateQuery(&QueryDesc, FreqQuery.GetInitReference() ); if ( D3DResult == S_OK ) { D3D11DeviceContext->Begin(FreqQuery); D3D11DeviceContext->End(FreqQuery); D3D11_QUERY_DATA_TIMESTAMP_DISJOINT FreqQueryData; D3DResult = D3D11DeviceContext->GetData(FreqQuery,&FreqQueryData,sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT),0); double StartTime = FPlatformTime::Seconds(); while ( D3DResult == S_FALSE && (FPlatformTime::Seconds() - StartTime) < 0.1 ) { FPlatformProcess::Sleep( 0.005f ); D3DResult = D3D11DeviceContext->GetData(FreqQuery,&FreqQueryData,sizeof(D3D11_QUERY_DATA_TIMESTAMP_DISJOINT),0); } if(D3DResult == S_OK) { GTimingFrequency = FreqQueryData.Frequency; checkSlow(!FreqQueryData.Disjoint); } } FreqQuery = NULL; }
/** Sets shader parameter values */ void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View, TRefCountPtr<IPooledRenderTarget>& LightShaftOcclusion) { FGlobalShader::SetParameters(RHICmdList, GetPixelShader(), View); SetTextureParameter( RHICmdList, GetPixelShader(), SourceTextureParameter, SourceTextureSamplerParameter, TStaticSamplerState<SF_Bilinear,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), LightShaftOcclusion->GetRenderTargetItem().ShaderResourceTexture ); }
bool FD3D11Viewport::Present(bool bLockToVsync) { bool bNativelyPresented = true; #if D3D11_WITH_DWMAPI // We can't call Present if !bIsValid, as it waits a window message to be processed, but the main thread may not be pumping the message handler. if(bIsValid) { // Check if the viewport's swap chain has been invalidated by DXGI. BOOL bSwapChainFullscreenState; TRefCountPtr<IDXGIOutput> SwapChainOutput; VERIFYD3D11RESULT(SwapChain->GetFullscreenState(&bSwapChainFullscreenState,SwapChainOutput.GetInitReference())); // Can't compare BOOL with bool... if ( (!!bSwapChainFullscreenState) != bIsFullscreen ) { bIsValid = false; // Minimize the window. // use SW_FORCEMINIMIZE if the messaging thread is likely to be blocked for a sizeable period. // SW_FORCEMINIMIZE also prevents the minimize animation from playing. ::ShowWindow(WindowHandle,SW_MINIMIZE); } } // When desktop composition is enabled, locking to vsync via the Present // call is unreliable. Instead, communicate with the desktop window manager // directly to enable vsync. const bool bSyncWithDWM = bLockToVsync && !bIsFullscreen && RHIConsoleVariables::bSyncWithDWM && IsCompositionEnabled(); if (bSyncWithDWM) { PresentWithVsyncDWM(); } else #endif //D3D11_WITH_DWMAPI { // Present the back buffer to the viewport window. bNativelyPresented = PresentChecked(bLockToVsync ? RHIConsoleVariables::SyncInterval : 0); } return bNativelyPresented; }
void FOculusRiftPlugin::SetGraphicsAdapter(const ovrGraphicsLuid& luid) { TRefCountPtr<IDXGIFactory> DXGIFactory; if(SUCCEEDED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**) DXGIFactory.GetInitReference()))) { for(int32 adapterIndex = 0;; adapterIndex++) { TRefCountPtr<IDXGIAdapter> DXGIAdapter; DXGI_ADAPTER_DESC DXGIAdapterDesc; if( FAILED(DXGIFactory->EnumAdapters(adapterIndex, DXGIAdapter.GetInitReference())) || FAILED(DXGIAdapter->GetDesc(&DXGIAdapterDesc)) ) { break; } if(!FMemory::Memcmp(&luid, &DXGIAdapterDesc.AdapterLuid, sizeof(LUID))) { // Remember this adapterIndex so we use the right adapter, even when we startup without HMD connected GConfig->SetInt(TEXT("Oculus.Settings"), TEXT("GraphicsAdapter"), adapterIndex, GEngineIni); break; } } } }
static void GetShaderBindings( TRefCountPtr<ID3D11ShaderReflection> Reflector, FSlateD3DShaderBindings& OutBindings ) { D3D11_SHADER_DESC ShaderDesc; Reflector->GetDesc( &ShaderDesc ); for( uint32 I = 0; I < ShaderDesc.BoundResources; ++I ) { D3D11_SHADER_INPUT_BIND_DESC Desc; Reflector->GetResourceBindingDesc( I, &Desc ); FSlateD3DShaderParameter* Param = FSlateShaderParameterMap::Get().Find( Desc.Name ); if( Param ) { if( Desc.Type == D3D_SIT_TEXTURE ) { OutBindings.ResourceViews.Add( (TSlateD3DTypedShaderParameter<ID3D11ShaderResourceView>*)Param ); } else if( Desc.Type == D3D_SIT_CBUFFER ) { OutBindings.ConstantBuffers.Add( (TSlateD3DTypedShaderParameter<ID3D11Buffer>*)Param ); } else if( Desc.Type == D3D_SIT_SAMPLER ) { OutBindings.SamplerStates.Add( (TSlateD3DTypedShaderParameter<ID3D11SamplerState>*)Param ); } else { // unhandled param type check(0); } } else { // not registered check(0); } } }