From 2b64f003622ee7871fd7aec041622427dd2fc88f Mon Sep 17 00:00:00 2001 From: Egor Yusov Date: Fri, 19 Aug 2016 23:35:47 -0700 Subject: Updated to Diligent Engine 2.0 --- .../build/UWP/GraphicsEngineD3D11.vcxproj | 200 +++ .../build/UWP/GraphicsEngineD3D11.vcxproj.filters | 2 + .../build/Win32/GraphicsEngineD3D11.vcxproj | 346 +++++ .../Win32/GraphicsEngineD3D11.vcxproj.filters | 9 + .../GraphicsEngineD3D11.Shared.vcxitems | 89 ++ .../GraphicsEngineD3D11.Shared.vcxitems.filters | 198 +++ .../build/Windows.Shared/GraphicsEngineD3D11.props | 24 + .../build/Windows/EngineRoot.props | 22 - .../build/Windows/GraphicsEngineD3D11.props | 10 - .../build/Windows/GraphicsEngineD3D11.vcxproj | 336 ---- .../Windows/GraphicsEngineD3D11.vcxproj.filters | 2 - .../build/WindowsStore/EngineRoot.props | 18 - .../GraphicsEngineD3D11.Shared.vcxitems | 89 -- .../GraphicsEngineD3D11.Shared.vcxitems.filters | 196 --- .../GraphicsEngineD3D11.Windows.vcxproj | 205 --- .../GraphicsEngineD3D11.Windows.vcxproj.filters | 2 - .../GraphicsEngineD3D11.WindowsPhone.vcxproj | 144 -- ...raphicsEngineD3D11.WindowsPhone.vcxproj.filters | 2 - .../include/BlendStateD3D11Impl.h | 55 - .../GraphicsEngineD3D11/include/BufferD3D11Impl.h | 46 +- .../include/BufferViewD3D11Impl.h | 27 +- .../include/CommandListD3D11Impl.h | 53 + .../include/D3D11DebugUtilities.h | 26 +- .../include/D3D11TypeConversions.h | 69 +- .../include/D3D11TypeDefinitions.h | 181 +++ Graphics/GraphicsEngineD3D11/include/D3DErrors.h | 89 -- .../GraphicsEngineD3D11/include/DSStateD3D11Impl.h | 54 - .../include/DeviceContextD3D11Impl.h | 305 ++-- .../include/EngineD3D11Defines.h | 28 + .../include/HLSLDefinitions.fxh | 61 - .../include/HLSLDefinitions_inc.fxh | 61 - .../include/PipelineStateD3D11Impl.h | 100 ++ .../include/RasterizerStateD3D11Impl.h | 54 - .../include/RenderDeviceD3D11Impl.h | 36 +- .../GraphicsEngineD3D11/include/SamplerD3D11Impl.h | 16 +- .../GraphicsEngineD3D11/include/ShaderD3D11Impl.h | 206 +-- .../include/ShaderResourceBindingD3D11Impl.h | 81 + .../include/ShaderResourceCacheD3D11.h | 316 ++++ .../include/ShaderResourceLayoutD3D11.h | 300 ++++ .../include/ShaderResourcesD3D11.h | 139 ++ .../include/SwapChainD3D11Impl.h | 28 +- .../GraphicsEngineD3D11/include/Texture1D_D3D11.h | 17 +- .../GraphicsEngineD3D11/include/Texture2D_D3D11.h | 17 +- .../GraphicsEngineD3D11/include/Texture3D_D3D11.h | 17 +- .../GraphicsEngineD3D11/include/TextureBaseD3D11.h | 48 +- .../include/TextureViewD3D11Impl.h | 22 +- .../include/VertexDescD3D11Impl.h | 55 - Graphics/GraphicsEngineD3D11/include/pch.h | 10 +- Graphics/GraphicsEngineD3D11/include/targetver.h | 2 +- .../interface/BlendStateD3D11.h | 50 - .../GraphicsEngineD3D11/interface/BufferD3D11.h | 2 +- .../interface/BufferViewD3D11.h | 2 +- .../interface/DepthStencilStateD3D11.h | 50 - .../interface/DeviceContextD3D11.h | 2 +- .../interface/EngineD3D11Attribs.h | 65 + .../interface/PipelineStateD3D11.h | 107 ++ .../interface/RasterizerStateD3D11.h | 50 - .../interface/RenderDeviceD3D11.h | 4 +- .../interface/RenderDeviceFactoryD3D11.h | 34 +- .../GraphicsEngineD3D11/interface/SamplerD3D11.h | 2 +- .../GraphicsEngineD3D11/interface/ShaderD3D11.h | 2 +- .../interface/ShaderResourceBindingD3D11.h | 45 + .../GraphicsEngineD3D11/interface/SwapChainD3D11.h | 2 +- .../GraphicsEngineD3D11/interface/TextureD3D11.h | 2 +- .../interface/TextureViewD3D11.h | 2 +- .../interface/VertexDescriptionD3D11.h | 50 - .../src/BlendStateD3D11Impl.cpp | 144 -- .../GraphicsEngineD3D11/src/BufferD3D11Impl.cpp | 66 +- .../src/BufferViewD3D11Impl.cpp | 20 +- .../src/CommandListD3D11Impl.cpp | 45 + .../src/D3D11DebugUtilities.cpp | 171 +-- .../src/D3D11TypeConversions.cpp | 499 +----- Graphics/GraphicsEngineD3D11/src/DLLMain.cpp | 2 +- .../GraphicsEngineD3D11/src/DSStateD3D11Impl.cpp | 66 - .../src/DeviceContextD3D11Impl.cpp | 1608 ++++++++++++-------- .../src/GraphicsEngineD3D11.def | 2 +- .../src/PipelineStateD3D11Impl.cpp | 222 +++ .../src/RasterizerStateD3D11Impl.cpp | 110 -- .../src/RenderDeviceD3D11Impl.cpp | 215 +-- .../src/RenderDeviceFactoryD3D11.cpp | 139 +- .../GraphicsEngineD3D11/src/SamplerD3D11Impl.cpp | 6 +- .../GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp | 788 +--------- .../src/ShaderResourceBindingD3D11Impl.cpp | 168 ++ .../src/ShaderResourceCacheD3D11.cpp | 265 ++++ .../src/ShaderResourceLayoutD3D11.cpp | 783 ++++++++++ .../src/ShaderResourcesD3D11.cpp | 435 ++++++ .../GraphicsEngineD3D11/src/SwapChainD3D11Impl.cpp | 109 +- .../GraphicsEngineD3D11/src/Texture1D_D3D11.cpp | 111 +- .../GraphicsEngineD3D11/src/Texture2D_D3D11.cpp | 166 +- .../GraphicsEngineD3D11/src/Texture3D_D3D11.cpp | 47 +- .../GraphicsEngineD3D11/src/TextureBaseD3D11.cpp | 23 +- .../src/TextureViewD3D11Impl.cpp | 20 +- .../src/VertexDescD3D11Impl.cpp | 72 - Graphics/GraphicsEngineD3D11/src/pch.cpp | 2 +- 94 files changed, 5983 insertions(+), 5205 deletions(-) create mode 100644 Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj create mode 100644 Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj.filters create mode 100644 Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj create mode 100644 Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj.filters create mode 100644 Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems create mode 100644 Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters create mode 100644 Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.props delete mode 100644 Graphics/GraphicsEngineD3D11/build/Windows/EngineRoot.props delete mode 100644 Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.props delete mode 100644 Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj delete mode 100644 Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj.filters delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/EngineRoot.props delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj.filters delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj delete mode 100644 Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj.filters delete mode 100644 Graphics/GraphicsEngineD3D11/include/BlendStateD3D11Impl.h create mode 100644 Graphics/GraphicsEngineD3D11/include/CommandListD3D11Impl.h create mode 100644 Graphics/GraphicsEngineD3D11/include/D3D11TypeDefinitions.h delete mode 100644 Graphics/GraphicsEngineD3D11/include/D3DErrors.h delete mode 100644 Graphics/GraphicsEngineD3D11/include/DSStateD3D11Impl.h create mode 100644 Graphics/GraphicsEngineD3D11/include/EngineD3D11Defines.h delete mode 100644 Graphics/GraphicsEngineD3D11/include/HLSLDefinitions.fxh delete mode 100644 Graphics/GraphicsEngineD3D11/include/HLSLDefinitions_inc.fxh create mode 100644 Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h delete mode 100644 Graphics/GraphicsEngineD3D11/include/RasterizerStateD3D11Impl.h create mode 100644 Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h create mode 100644 Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h create mode 100644 Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h create mode 100644 Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/include/VertexDescD3D11Impl.h delete mode 100644 Graphics/GraphicsEngineD3D11/interface/BlendStateD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/interface/DepthStencilStateD3D11.h create mode 100644 Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h create mode 100644 Graphics/GraphicsEngineD3D11/interface/PipelineStateD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/interface/RasterizerStateD3D11.h create mode 100644 Graphics/GraphicsEngineD3D11/interface/ShaderResourceBindingD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/interface/VertexDescriptionD3D11.h delete mode 100644 Graphics/GraphicsEngineD3D11/src/BlendStateD3D11Impl.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/CommandListD3D11Impl.cpp delete mode 100644 Graphics/GraphicsEngineD3D11/src/DSStateD3D11Impl.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp delete mode 100644 Graphics/GraphicsEngineD3D11/src/RasterizerStateD3D11Impl.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/ShaderResourceCacheD3D11.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp create mode 100644 Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp delete mode 100644 Graphics/GraphicsEngineD3D11/src/VertexDescD3D11Impl.cpp (limited to 'Graphics/GraphicsEngineD3D11') diff --git a/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj b/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj new file mode 100644 index 00000000..d31d9a69 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj @@ -0,0 +1,200 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + + {29acd2a7-4c49-4973-9673-8f57ef37070f} + StaticLibrary + GraphicsEngineD3D11 + en-US + 14.0 + true + Windows Store + 10.0.10586.0 + 10.0.10240.0 + 10.0 + + + + StaticLibrary + true + v140 + + + StaticLibrary + true + v140 + + + StaticLibrary + true + v140 + + + StaticLibrary + false + true + v140 + + + StaticLibrary + false + true + v140 + + + StaticLibrary + false + true + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + false + + + false + + + false + + + false + + + false + + + + false + true + + + Console + false + false + + + + + false + true + + + Console + false + false + + + + + false + true + + + Console + false + false + + + + + false + true + + + Console + false + false + + + + + false + true + + + Console + false + false + + + + + false + true + + + Console + false + false + + + + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj.filters b/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj.filters new file mode 100644 index 00000000..c31757ec --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/UWP/GraphicsEngineD3D11.vcxproj.filters @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj b/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj new file mode 100644 index 00000000..571c5660 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj @@ -0,0 +1,346 @@ + + + + + DbgDLL + Win32 + + + DbgDLL + x64 + + + Debug + Win32 + + + Debug + x64 + + + RelDLL + Win32 + + + RelDLL + x64 + + + Release + Win32 + + + Release + x64 + + + + + {7380f7e6-315f-4b4e-92eb-e6aeee865298} + + + {8ada5f93-7a38-4ad8-b8f5-1ffd4d4f630c} + + + {58f32677-436b-412a-bbf8-2b1310d82cd8} + + + {40fd58ed-aabc-4cbd-bee4-33116995a626} + + + {052dd700-477c-4512-a7f4-b05ebef5c80e} + + + {c6014499-0cf2-43ec-a773-a4e354fb2d74} + + + + + true + true + true + true + + + + + + + {FE289CC7-15D6-4A76-B9CB-F61CAB3192C9} + Win32Proj + GraphicsEngineD3D11 + + + + StaticLibrary + true + Unicode + v140 + + + DynamicLibrary + true + Unicode + v140 + + + StaticLibrary + true + Unicode + v140 + + + DynamicLibrary + true + Unicode + v140 + + + StaticLibrary + false + true + Unicode + v140 + + + DynamicLibrary + false + true + Unicode + v140 + + + StaticLibrary + false + true + Unicode + v140 + + + DynamicLibrary + false + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib + + + + $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib + + + + $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib + + + + $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib + + + + + Disabled + WIN32;_LIB;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + + + Disabled + WIN32;_LIB;%(PreprocessorDefinitions) + + + Windows + true + d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) + ..\..\src\GraphicsEngineD3D11.def + + + + + + + + + Disabled + WIN32;_LIB;%(PreprocessorDefinitions) + + + Windows + true + + + + + MachineX64 + + + + + Disabled + WIN32;_LIB;%(PreprocessorDefinitions) + + + Windows + true + d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) + ..\..\src\GraphicsEngineD3D11.def + + + + + MachineX64 + + + + + MaxSpeed + true + true + WIN32;_LIB;%(PreprocessorDefinitions) + StreamingSIMDExtensions2 + Speed + /Qvec-report:1 %(AdditionalOptions) + + + Windows + true + true + true + + + + + + + + + MaxSpeed + true + true + WIN32;_LIB;%(PreprocessorDefinitions) + StreamingSIMDExtensions2 + Speed + /Qvec-report:1 %(AdditionalOptions) + + + Windows + true + true + true + d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) + ..\..\src\GraphicsEngineD3D11.def + + + + + + + + + MaxSpeed + true + true + WIN32;_LIB;%(PreprocessorDefinitions) + AdvancedVectorExtensions2 + Speed + /Qvec-report:1 %(AdditionalOptions) + + + Windows + true + true + true + + + + + MachineX64 + + + + + MaxSpeed + true + true + WIN32;_LIB;%(PreprocessorDefinitions) + Speed + AdvancedVectorExtensions2 + /Qvec-report:1 %(AdditionalOptions) + + + Windows + true + true + true + d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) + ..\..\src\GraphicsEngineD3D11.def + + + + + MachineX64 + + + + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj.filters b/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj.filters new file mode 100644 index 00000000..afa04bc6 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/Win32/GraphicsEngineD3D11.vcxproj.filters @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems new file mode 100644 index 00000000..9e8c8b8f --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems @@ -0,0 +1,89 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + {3c22010c-99f3-4321-8f55-36da8f97a980} + GraphicsEngineD3D11 + GraphicsEngineD3D11.Shared + 248F659F-DAC5-46E8-AC09-60EC9FC95053 + + + + %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + + + + + + + + + + + + + + + false + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters new file mode 100644 index 00000000..e23371f0 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters @@ -0,0 +1,198 @@ + + + + + {326ec87b-f6ab-4291-a28f-631b2b240d3a} + + + {a12cf1d4-8cb0-4360-898a-d69d16e288c5} + + + {e3e50068-d75b-4663-bee9-5ca137971e89} + + + + + interface + + + interface + + + interface + + + interface + + + interface + + + interface + + + interface + + + interface + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + include + + + interface + + + include + + + include + + + include + + + include + + + interface + + + interface + + + include + + + include + + + interface + + + include + + + include + + + interface + + + include + + + include + + + include + + + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.props b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.props new file mode 100644 index 00000000..c72d8cf0 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/build/Windows.Shared/GraphicsEngineD3D11.props @@ -0,0 +1,24 @@ + + + + + ..\..\..\.. + ..\..\.. + ..\.. + + + $(GraphicsRoot)\GraphicsEngineD3D11\include;$(GraphicsRoot)\GraphicsEngineD3D11\interface;$(GraphicsRoot)\GraphicsEngine\include;$(GraphicsRoot)\GraphicsEngine\interface;$(GraphicsRoot)\GraphicsEngineD3DBase\include;$(GraphicsRoot)\GraphicsTools\include;$(EngineRoot)\Common\include;$(EngineRoot)\Common\interface;$(EngineRoot)\Platforms\interface;$(VC_IncludePath);$(WindowsSDK_IncludePath) + + + + + $(EngineRoot) + + + $(GraphicsRoot) + + + $(ProjectRoot) + + + \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows/EngineRoot.props b/Graphics/GraphicsEngineD3D11/build/Windows/EngineRoot.props deleted file mode 100644 index 02287e9c..00000000 --- a/Graphics/GraphicsEngineD3D11/build/Windows/EngineRoot.props +++ /dev/null @@ -1,22 +0,0 @@ - - - - - ..\..\..\.. - ..\..\.. - ..\.. - - - - - - $(EngineRoot) - - - $(GraphicsRoot) - - - $(ProjectRoot) - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.props b/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.props deleted file mode 100644 index db23faae..00000000 --- a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.props +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - $(GraphicsRoot)\GraphicsEngineD3D11\include;$(GraphicsRoot)\GraphicsEngineD3D11\interface;$(GraphicsRoot)\GraphicsEngine\include;$(GraphicsRoot)\GraphicsEngine\interface;$(GraphicsRoot)\GraphicsTools\include;$(EngineRoot)\Common\include;$(EngineRoot)\Common\interface;$(EngineRoot)\Platforms\interface;$(VC_IncludePath);$(WindowsSDK_IncludePath) - - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj b/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj deleted file mode 100644 index 7a6e1ebd..00000000 --- a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj +++ /dev/null @@ -1,336 +0,0 @@ - - - - - DbgDLL - Win32 - - - DbgDLL - x64 - - - Debug - Win32 - - - Debug - x64 - - - RelDLL - Win32 - - - RelDLL - x64 - - - Release - Win32 - - - Release - x64 - - - - - {7380f7e6-315f-4b4e-92eb-e6aeee865298} - - - {8ada5f93-7a38-4ad8-b8f5-1ffd4d4f630c} - - - {58f32677-436b-412a-bbf8-2b1310d82cd8} - - - {052dd700-477c-4512-a7f4-b05ebef5c80e} - - - {c6014499-0cf2-43ec-a773-a4e354fb2d74} - - - - {FE289CC7-15D6-4A76-B9CB-F61CAB3192C9} - Win32Proj - GraphicsEngineD3D11 - - - - StaticLibrary - true - Unicode - v140 - - - DynamicLibrary - true - Unicode - v140 - - - StaticLibrary - true - Unicode - v140 - - - DynamicLibrary - true - Unicode - v140 - - - StaticLibrary - false - true - Unicode - v140 - - - DynamicLibrary - false - true - Unicode - v140 - - - StaticLibrary - false - true - Unicode - v140 - - - DynamicLibrary - false - true - Unicode - v140 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib - - - - $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib - - - - $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib - - - - $(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib - - - - - Level3 - Disabled - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - - - - - - - - - Level3 - Disabled - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) - ..\..\src\GraphicsEngineD3D11.def - - - - - - - - - Level3 - Disabled - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - - - - - MachineX64 - - - - - Level3 - Disabled - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) - ..\..\src\GraphicsEngineD3D11.def - - - - - MachineX64 - - - - - Level3 - MaxSpeed - true - true - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - true - true - - - - - - - - - Level3 - MaxSpeed - true - true - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - true - true - d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) - ..\..\src\GraphicsEngineD3D11.def - - - - - - - - - Level3 - MaxSpeed - true - true - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - true - true - - - - - MachineX64 - - - - - Level3 - MaxSpeed - true - true - WIN32;_LIB;%(PreprocessorDefinitions) - - - Windows - true - true - true - d3d11.lib;d3dcompiler.lib;%(AdditionalDependencies) - ..\..\src\GraphicsEngineD3D11.def - - - - - MachineX64 - - - - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj.filters b/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj.filters deleted file mode 100644 index 9cd85105..00000000 --- a/Graphics/GraphicsEngineD3D11/build/Windows/GraphicsEngineD3D11.vcxproj.filters +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/EngineRoot.props b/Graphics/GraphicsEngineD3D11/build/WindowsStore/EngineRoot.props deleted file mode 100644 index fcb891c0..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/EngineRoot.props +++ /dev/null @@ -1,18 +0,0 @@ - - - - - ..\..\..\..\.. - ..\..\..\.. - - - - - - $(EngineRoot) - - - $(GraphicsRoot) - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems deleted file mode 100644 index 0850b1e0..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems +++ /dev/null @@ -1,89 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - true - {3c22010c-99f3-4321-8f55-36da8f97a980} - GraphicsEngineD3D11 - GraphicsEngineD3D11.Shared - 248F659F-DAC5-46E8-AC09-60EC9FC95053 - - - - %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) - - - - - - - - - - - - - - - - CppHeader - $(EngineRoot)\Utilities\File2Include\File2String.exe %(FullPath) $(ProjectRoot)\include\%(Filename)_inc.fxh - $(ProjectRoot)\include\%(Filename)_inc.h - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create - - - - - - - - - - - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters deleted file mode 100644 index dd1617f1..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Shared/GraphicsEngineD3D11.Shared.vcxitems.filters +++ /dev/null @@ -1,196 +0,0 @@ - - - - - {326ec87b-f6ab-4291-a28f-631b2b240d3a} - - - {a12cf1d4-8cb0-4360-898a-d69d16e288c5} - - - {e3e50068-d75b-4663-bee9-5ca137971e89} - - - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - interface - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - include - - - interface - - - include - - - include - - - include - - - include - - - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - src - - - - - src - - - - - include - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj deleted file mode 100644 index 095b7883..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj +++ /dev/null @@ -1,205 +0,0 @@ - - - - - Debug - ARM - - - Debug - Win32 - - - Debug - x64 - - - Release - ARM - - - Release - Win32 - - - Release - x64 - - - - {3838fd2b-3c87-4caf-95de-95e7c3947c26} - GraphicsEngineD3D11 - en-US - 12.0 - true - Windows Store - 8.1 - CodeSharingStaticLibrary - - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - true - v120 - - - StaticLibrary - false - true - v120 - - - StaticLibrary - false - true - v120 - - - StaticLibrary - false - true - v120 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - false - - - false - - - false - - - false - - - false - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj.filters b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj.filters deleted file mode 100644 index 4228787f..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.Windows/GraphicsEngineD3D11.Windows.vcxproj.filters +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj deleted file mode 100644 index 37889180..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj +++ /dev/null @@ -1,144 +0,0 @@ - - - - - Debug - ARM - - - Debug - Win32 - - - Release - ARM - - - Release - Win32 - - - - {581c72cf-7f31-4eba-8f6e-743ca5774742} - GraphicsEngineD3D11 - en-US - 12.0 - true - Windows Phone - 8.1 - CodeSharingStaticLibrary - - - - StaticLibrary - true - v120_wp81 - - - StaticLibrary - true - v120_wp81 - - - StaticLibrary - false - true - v120_wp81 - - - StaticLibrary - false - true - v120_wp81 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - false - - - false - - - false - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - Use - false - true - - - Console - false - false - - - - - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj.filters b/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj.filters deleted file mode 100644 index 4228787f..00000000 --- a/Graphics/GraphicsEngineD3D11/build/WindowsStore/GraphicsEngineD3D11.WindowsPhone/GraphicsEngineD3D11.WindowsPhone.vcxproj.filters +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/include/BlendStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/BlendStateD3D11Impl.h deleted file mode 100644 index 9bfc8af2..00000000 --- a/Graphics/GraphicsEngineD3D11/include/BlendStateD3D11Impl.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of Diligent::BlendStateD3D11Impl class - -#include "BlendStateD3D11.h" -#include "RenderDeviceD3D11.h" -#include "BlendStateBase.h" - -namespace Diligent -{ - -/// Implementation of the Diligent::IBlendStateD3D11 interface -class BlendStateD3D11Impl : public BlendStateBase -{ -public: - typedef BlendStateBase TBlendStateBase; - - BlendStateD3D11Impl(class RenderDeviceD3D11Impl *pDeviceD3D11, const BlendStateDesc& BuffDesc); - ~BlendStateD3D11Impl(); - - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); - - /// Implementation of the IBlendStateD3D11::GetD3D11BlendState() method. - ID3D11BlendState *GetD3D11BlendState(){ return m_pd3d11BlendState; } - -private: - /// D3D11 Blend state object - Diligent::CComPtr m_pd3d11BlendState; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h index 190599cd..290b633f 100644 --- a/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/BufferD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,21 +34,43 @@ namespace Diligent { +class FixedBlockMemoryAllocator; + +enum class D3D11BufferState +{ + Undefined = 0x00, + ShaderResource = 0x01, + ConstantBuffer = 0x02, + VertexBuffer = 0x04, + IndexBuffer = 0x08, + UnorderedAccess = 0x10, + AnyInput = ShaderResource | ConstantBuffer | VertexBuffer | IndexBuffer +}; + /// Implementation of the Diligent::IBufferD3D11 interface -class BufferD3D11Impl : public BufferBase +class BufferD3D11Impl : public BufferBase { public: - typedef BufferBase TBufferBase; - BufferD3D11Impl(class RenderDeviceD3D11Impl *pDeviceD3D11, const BufferDesc& BuffDesc, const BufferData &BuffData = BufferData()); + typedef BufferBase TBufferBase; + BufferD3D11Impl(FixedBlockMemoryAllocator &BufferObjMemAllocator, + FixedBlockMemoryAllocator &BuffViewObjMemAllocator, + class RenderDeviceD3D11Impl *pDeviceD3D11, + const BufferDesc& BuffDesc, + const BufferData &BuffData = BufferData()); ~BufferD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + + virtual void UpdateData( IDeviceContext *pContext, Uint32 Offset, Uint32 Size, const PVoid pData )override final; + virtual void CopyData( IDeviceContext *pContext, IBuffer *pSrcBuffer, Uint32 SrcOffset, Uint32 DstOffset, Uint32 Size )override final; + virtual void Map( IDeviceContext *pContext, MAP_TYPE MapType, Uint32 MapFlags, PVoid &pMappedData )override final; + virtual void Unmap( IDeviceContext *pContext, MAP_TYPE MapType )override final; + virtual ID3D11Buffer *GetD3D11Buffer()override final{ return m_pd3d11Buffer; } - virtual void UpdateData( IDeviceContext *pContext, Uint32 Offset, Uint32 Size, const PVoid pData )override; - virtual void CopyData( IDeviceContext *pContext, IBuffer *pSrcBuffer, Uint32 SrcOffset, Uint32 DstOffset, Uint32 Size )override; - virtual void Map( IDeviceContext *pContext, MAP_TYPE MapType, Uint32 MapFlags, PVoid &pMappedData )override; - virtual void Unmap( IDeviceContext *pContext )override; - virtual ID3D11Buffer *GetD3D11Buffer()override{ return m_pd3d11Buffer; } + void ResetState(D3D11BufferState State){m_State = static_cast(State);} + void AddState(D3D11BufferState State){m_State |= static_cast(State);} + void ClearState(D3D11BufferState State){m_State &= ~static_cast(State);} + bool CheckState(D3D11BufferState State){return (m_State & static_cast(State)) ? true : false;} private: virtual void CreateViewInternal( const struct BufferViewDesc &ViewDesc, IBufferView **ppView, bool bIsDefaultView )override; @@ -57,7 +79,9 @@ private: void CreateSRV( struct BufferViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ); friend class DeviceContextD3D11Impl; - Diligent::CComPtr m_pd3d11Buffer; ///< D3D11 buffer object + CComPtr m_pd3d11Buffer; ///< D3D11 buffer object + + Uint32 m_State = static_cast(D3D11BufferState::Undefined); }; } diff --git a/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h index 37308ae9..07321a16 100644 --- a/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/BufferViewD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,24 +33,29 @@ namespace Diligent { +class FixedBlockMemoryAllocator; /// Implementation of the Diligent::IBufferViewD3D11 interface -class BufferViewD3D11Impl : public BufferViewBase +class BufferViewD3D11Impl : public BufferViewBase { public: - typedef BufferViewBase TBufferViewBase; + typedef BufferViewBase TBufferViewBase; - BufferViewD3D11Impl( IRenderDevice *pDevice, - const BufferViewDesc& ViewDesc, - class IBuffer *pBuffer, - ID3D11View* pD3D11View, - bool bIsDefaultView); + BufferViewD3D11Impl( FixedBlockMemoryAllocator &BuffViewObjAllocator, + IRenderDevice *pDevice, + const BufferViewDesc& ViewDesc, + class IBuffer *pBuffer, + ID3D11View* pD3D11View, + bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) final; - virtual ID3D11View* GetD3D11View(); + virtual ID3D11View* GetD3D11View()override final + { + return m_pD3D11View; + } protected: - Diligent::CComPtr m_pD3D11View; /// m_pD3D11View; /// +{ +public: + typedef CommandListBase TCommandListBase; + CommandListD3D11Impl(FixedBlockMemoryAllocator &CommandListObjMemAllocator, + IRenderDevice *pDevice, + ID3D11CommandList *pd3d11CommandList); + ~CommandListD3D11Impl(); + + ID3D11CommandList *GetD3D11CommandList(){ return m_pd3d11CommandList; } + +private: + CComPtr m_pd3d11CommandList; ///< D3D11 CommandList object +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/D3D11DebugUtilities.h b/Graphics/GraphicsEngineD3D11/include/D3D11DebugUtilities.h index 1becfb17..cddc4249 100644 --- a/Graphics/GraphicsEngineD3D11/include/D3D11DebugUtilities.h +++ b/Graphics/GraphicsEngineD3D11/include/D3D11DebugUtilities.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,32 +26,8 @@ /// \file /// Debug utilities -#include "DeviceObject.h" -#include "ShaderD3D11Impl.h" - -#ifdef _DEBUG -# define VERIFY_RESOURCE_ARRAYS -#endif namespace Diligent { -#ifdef VERIFY_RESOURCE_ARRAYS - - /// Debug function that verifies that cached engine objects and d3d11 shader resource views in two provided arrays are consistent - void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundSRV > &SRVs, const std::vector d3d11SRVs, IShader *pShader ); - - /// Debug function that verifies that cached engine objects and d3d11 unordered access views in two provided arrays are consistent - void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundUAV > &UAVs, const std::vector d3d11UAVs, IShader *pShader ); - - /// Debug function that verifies that cached engine objects and d3d11 constant buffers in two provided arrays are consistent - void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundCB > &CBs, const std::vector d3d11CBs, IShader *pShader ); - - /// Debug function that verifies that cached engine objects and d3d11 samplers in two provided arrays are consistent - void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundSampler >&Samplers, const std::vector d3d11Samplers, IShader *pShader ); - -#else - - #define dbgVerifyResourceArrays(...) -#endif } diff --git a/Graphics/GraphicsEngineD3D11/include/D3D11TypeConversions.h b/Graphics/GraphicsEngineD3D11/include/D3D11TypeConversions.h index ddc76591..21031ea8 100644 --- a/Graphics/GraphicsEngineD3D11/include/D3D11TypeConversions.h +++ b/Graphics/GraphicsEngineD3D11/include/D3D11TypeConversions.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ /// Type conversion routines #include "GraphicsTypes.h" +#include "DXGITypeConversions.h" namespace Diligent { @@ -45,22 +46,7 @@ inline UINT BindFlagsToD3D11BindFlags(Uint32 BindFlags) return D3D11BindFlags; } -inline D3D11_PRIMITIVE_TOPOLOGY TopologyToDX11Topology(PRIMITIVE_TOPOLOGY Topology) -{ - switch( Topology ) - { - case PRIMITIVE_TOPOLOGY_UNDEFINED: return D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; - case PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - case PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; - case PRIMITIVE_TOPOLOGY_POINT_LIST: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; - case PRIMITIVE_TOPOLOGY_LINE_LIST: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST; - default: UNEXPECTED("Unsupported primitive topology" ); return D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; - } -} - -DXGI_FORMAT TypeToDXGI_Format(VALUE_TYPE ValType, Uint32 NumComponents, Bool bIsNormalized); - -DXGI_FORMAT TexFormatToDXGI_Format(TEXTURE_FORMAT TexFormat, Uint32 BindFlags = 0); +D3D11_PRIMITIVE_TOPOLOGY TopologyToD3D11Topology(PRIMITIVE_TOPOLOGY Topology); inline D3D11_USAGE UsageToD3D11Usage(USAGE Usage) { @@ -110,38 +96,21 @@ inline UINT MiscTextureFlagsToD3D11Flags(Uint32 Flags) } D3D11_FILTER FilterTypeToD3D11Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter); - -inline D3D11_TEXTURE_ADDRESS_MODE TexAddressModeToD3D11AddressMode(TEXTURE_ADDRESS_MODE Mode) -{ - switch(Mode) - { - case TEXTURE_ADDRESS_UNKNOWN: UNEXPECTED("Texture address mode is not specified" ); return D3D11_TEXTURE_ADDRESS_CLAMP; - case TEXTURE_ADDRESS_WRAP: return D3D11_TEXTURE_ADDRESS_WRAP; - case TEXTURE_ADDRESS_MIRROR: return D3D11_TEXTURE_ADDRESS_MIRROR; - case TEXTURE_ADDRESS_CLAMP: return D3D11_TEXTURE_ADDRESS_CLAMP; - case TEXTURE_ADDRESS_BORDER: return D3D11_TEXTURE_ADDRESS_BORDER; - case TEXTURE_ADDRESS_MIRROR_ONCE: return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE; - default: UNEXPECTED("Unknown texture address mode" ); return D3D11_TEXTURE_ADDRESS_CLAMP; - } -} - -inline D3D11_COMPARISON_FUNC ComparisonFuncToD3D11ComparisonFunc(COMPARISON_FUNCTION Func) -{ - switch(Func) - { - case COMPARISON_FUNC_UNKNOW: UNEXPECTED("Comparison function is not specified" ); return D3D11_COMPARISON_ALWAYS; - case COMPARISON_FUNC_NEVER: return D3D11_COMPARISON_NEVER; - case COMPARISON_FUNC_LESS: return D3D11_COMPARISON_LESS; - case COMPARISON_FUNC_EQUAL: return D3D11_COMPARISON_EQUAL; - case COMPARISON_FUNC_LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL; - case COMPARISON_FUNC_GREATER: return D3D11_COMPARISON_GREATER; - case COMPARISON_FUNC_NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL; - case COMPARISON_FUNC_GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL; - case COMPARISON_FUNC_ALWAYS: return D3D11_COMPARISON_ALWAYS; - default: UNEXPECTED("Unknown comparison function" ); return D3D11_COMPARISON_ALWAYS; - } -} - -D3D11_STENCIL_OP StencilOpToD3D11StencilOp( STENCIL_OP ); +D3D11_TEXTURE_ADDRESS_MODE TexAddressModeToD3D11AddressMode(TEXTURE_ADDRESS_MODE Mode); + +D3D11_COMPARISON_FUNC ComparisonFuncToD3D11ComparisonFunc(COMPARISON_FUNCTION Func); +void DepthStencilStateDesc_To_D3D11_DEPTH_STENCIL_DESC(const DepthStencilStateDesc &DepthStencilDesc, D3D11_DEPTH_STENCIL_DESC &d3d11DSSDesc); +void RasterizerStateDesc_To_D3D11_RASTERIZER_DESC(const RasterizerStateDesc &RasterizerDesc, D3D11_RASTERIZER_DESC &d3d11RSDesc); +void BlendStateDesc_To_D3D11_BLEND_DESC(const BlendStateDesc &BSDesc, D3D11_BLEND_DESC &D3D11BSDesc); +void LayoutElements_To_D3D11_INPUT_ELEMENT_DESCs(const std::vector > &LayoutElements, + std::vector > &D3D11InputElements); + +void TextureViewDesc_to_D3D11_SRV_DESC(const TextureViewDesc& TexViewDesc, D3D11_SHADER_RESOURCE_VIEW_DESC &D3D11SRVDesc, Uint32 SampleCount); +void TextureViewDesc_to_D3D11_RTV_DESC(const TextureViewDesc& TexViewDesc, D3D11_RENDER_TARGET_VIEW_DESC &D3D11RTVDesc, Uint32 SampleCount); +void TextureViewDesc_to_D3D11_DSV_DESC(const TextureViewDesc& TexViewDesc, D3D11_DEPTH_STENCIL_VIEW_DESC &D3D11DSVDesc, Uint32 SampleCount); +void TextureViewDesc_to_D3D11_UAV_DESC(const TextureViewDesc& TexViewDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC &D3D11UAVDesc); + +void BufferViewDesc_to_D3D11_SRV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& SRVDesc, D3D11_SHADER_RESOURCE_VIEW_DESC &D3D11SRVDesc); +void BufferViewDesc_to_D3D11_UAV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& UAVDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC &D3D11UAVDesc); } diff --git a/Graphics/GraphicsEngineD3D11/include/D3D11TypeDefinitions.h b/Graphics/GraphicsEngineD3D11/include/D3D11TypeDefinitions.h new file mode 100644 index 00000000..bd35a89e --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/D3D11TypeDefinitions.h @@ -0,0 +1,181 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Definitions of D3D11 types + +// Filters +#define D3D_FILTER_MIN_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_MIN_MAG_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_ANISOTROPIC D3D11_FILTER_ANISOTROPIC + +#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_POINT D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR +#define D3D_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT +#define D3D_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR +#define D3D_FILTER_COMPARISON_ANISOTROPIC D3D11_FILTER_COMPARISON_ANISOTROPIC + +// Minimum/maximum filtering is not supported in d3d11 +#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MINIMUM_ANISOTROPIC D3D11_FILTER_MIN_MAG_MIP_POINT + +#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR D3D11_FILTER_MIN_MAG_MIP_POINT +#define D3D_FILTER_MAXIMUM_ANISOTROPIC D3D11_FILTER_MIN_MAG_MIP_POINT + + +// Comparison functions +#define D3D_COMPARISON_FUNC_NEVER D3D11_COMPARISON_NEVER +#define D3D_COMPARISON_FUNC_LESS D3D11_COMPARISON_LESS +#define D3D_COMPARISON_FUNC_EQUAL D3D11_COMPARISON_EQUAL +#define D3D_COMPARISON_FUNC_LESS_EQUAL D3D11_COMPARISON_LESS_EQUAL +#define D3D_COMPARISON_FUNC_GREATER D3D11_COMPARISON_GREATER +#define D3D_COMPARISON_FUNC_NOT_EQUAL D3D11_COMPARISON_NOT_EQUAL +#define D3D_COMPARISON_FUNC_GREATER_EQUAL D3D11_COMPARISON_GREATER_EQUAL +#define D3D_COMPARISON_FUNC_ALWAYS D3D11_COMPARISON_ALWAYS + +// Stencil operations +#define D3D_STENCIL_OP_KEEP D3D11_STENCIL_OP_KEEP +#define D3D_STENCIL_OP_ZERO D3D11_STENCIL_OP_ZERO +#define D3D_STENCIL_OP_REPLACE D3D11_STENCIL_OP_REPLACE +#define D3D_STENCIL_OP_INCR_SAT D3D11_STENCIL_OP_INCR_SAT +#define D3D_STENCIL_OP_DECR_SAT D3D11_STENCIL_OP_DECR_SAT +#define D3D_STENCIL_OP_INVERT D3D11_STENCIL_OP_INVERT +#define D3D_STENCIL_OP_INCR D3D11_STENCIL_OP_INCR +#define D3D_STENCIL_OP_DECR D3D11_STENCIL_OP_DECR + +// Depth write masks +#define D3D_DEPTH_WRITE_MASK_ALL D3D11_DEPTH_WRITE_MASK_ALL +#define D3D_DEPTH_WRITE_MASK_ZERO D3D11_DEPTH_WRITE_MASK_ZERO + +// Cull modes +#define D3D_CULL_MODE_NONE D3D11_CULL_NONE +#define D3D_CULL_MODE_FRONT D3D11_CULL_FRONT +#define D3D_CULL_MODE_BACK D3D11_CULL_BACK + +// Fill modes +#define D3D_FILL_MODE_WIREFRAME D3D11_FILL_WIREFRAME +#define D3D_FILL_MODE_SOLID D3D11_FILL_SOLID + +// Blend sources +#define D3D_BLEND_ZERO D3D11_BLEND_ZERO +#define D3D_BLEND_ONE D3D11_BLEND_ONE +#define D3D_BLEND_SRC_COLOR D3D11_BLEND_SRC_COLOR +#define D3D_BLEND_INV_SRC_COLOR D3D11_BLEND_INV_SRC_COLOR +#define D3D_BLEND_SRC_ALPHA D3D11_BLEND_SRC_ALPHA +#define D3D_BLEND_INV_SRC_ALPHA D3D11_BLEND_INV_SRC_ALPHA +#define D3D_BLEND_DEST_ALPHA D3D11_BLEND_DEST_ALPHA +#define D3D_BLEND_INV_DEST_ALPHA D3D11_BLEND_INV_DEST_ALPHA +#define D3D_BLEND_DEST_COLOR D3D11_BLEND_DEST_COLOR +#define D3D_BLEND_INV_DEST_COLOR D3D11_BLEND_INV_DEST_COLOR +#define D3D_BLEND_SRC_ALPHA_SAT D3D11_BLEND_SRC_ALPHA_SAT +#define D3D_BLEND_BLEND_FACTOR D3D11_BLEND_BLEND_FACTOR +#define D3D_BLEND_INV_BLEND_FACTOR D3D11_BLEND_INV_BLEND_FACTOR +#define D3D_BLEND_SRC1_COLOR D3D11_BLEND_SRC1_COLOR +#define D3D_BLEND_INV_SRC1_COLOR D3D11_BLEND_INV_SRC1_COLOR +#define D3D_BLEND_SRC1_ALPHA D3D11_BLEND_SRC1_ALPHA +#define D3D_BLEND_INV_SRC1_ALPHA D3D11_BLEND_INV_SRC1_ALPHA + +// Blend operations +#define D3D_BLEND_OP_ADD D3D11_BLEND_OP_ADD +#define D3D_BLEND_OP_SUBTRACT D3D11_BLEND_OP_SUBTRACT +#define D3D_BLEND_OP_REV_SUBTRACT D3D11_BLEND_OP_REV_SUBTRACT +#define D3D_BLEND_OP_MIN D3D11_BLEND_OP_MIN +#define D3D_BLEND_OP_MAX D3D11_BLEND_OP_MAX + +// Color masks +#define D3D_COLOR_WRITE_ENABLE_RED D3D11_COLOR_WRITE_ENABLE_RED +#define D3D_COLOR_WRITE_ENABLE_GREEN D3D11_COLOR_WRITE_ENABLE_GREEN +#define D3D_COLOR_WRITE_ENABLE_BLUE D3D11_COLOR_WRITE_ENABLE_BLUE +#define D3D_COLOR_WRITE_ENABLE_ALPHA D3D11_COLOR_WRITE_ENABLE_ALPHA + +// Input classification +#define D3D_INPUT_CLASSIFICATION_PER_VERTEX_DATA D3D11_INPUT_PER_VERTEX_DATA +#define D3D_INPUT_CLASSIFICATION_PER_INSTANCE_DATA D3D11_INPUT_PER_INSTANCE_DATA + +// Texture address modes +#define D3D_TEXTURE_ADDRESS_WRAP D3D11_TEXTURE_ADDRESS_WRAP +#define D3D_TEXTURE_ADDRESS_MIRROR D3D11_TEXTURE_ADDRESS_MIRROR +#define D3D_TEXTURE_ADDRESS_CLAMP D3D11_TEXTURE_ADDRESS_CLAMP +#define D3D_TEXTURE_ADDRESS_BORDER D3D11_TEXTURE_ADDRESS_BORDER +#define D3D_TEXTURE_ADDRESS_MIRROR_ONCE D3D11_TEXTURE_ADDRESS_MIRROR_ONCE + + +// SRV Dimensions +// d3d11.h aliases D3D11_SRV_DIMENSION as D3D_SRV_DIMENSION, so there is no +// need to redefine this enum + +// RTV Dimensions +#define D3D_RTV_DIMENSION_UNKNOWN D3D11_RTV_DIMENSION_UNKNOWN +#define D3D_RTV_DIMENSION_BUFFER D3D11_RTV_DIMENSION_BUFFER +#define D3D_RTV_DIMENSION_TEXTURE1D D3D11_RTV_DIMENSION_TEXTURE1D +#define D3D_RTV_DIMENSION_TEXTURE1DARRAY D3D11_RTV_DIMENSION_TEXTURE1DARRAY +#define D3D_RTV_DIMENSION_TEXTURE2D D3D11_RTV_DIMENSION_TEXTURE2D +#define D3D_RTV_DIMENSION_TEXTURE2DARRAY D3D11_RTV_DIMENSION_TEXTURE2DARRAY +#define D3D_RTV_DIMENSION_TEXTURE2DMS D3D11_RTV_DIMENSION_TEXTURE2DMS +#define D3D_RTV_DIMENSION_TEXTURE2DMSARRAY D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY +#define D3D_RTV_DIMENSION_TEXTURE3D D3D11_RTV_DIMENSION_TEXTURE3D + + +// DSV Dimensions +#define D3D_DSV_DIMENSION_UNKNOWN D3D11_DSV_DIMENSION_UNKNOWN +#define D3D_DSV_DIMENSION_TEXTURE1D D3D11_DSV_DIMENSION_TEXTURE1D +#define D3D_DSV_DIMENSION_TEXTURE1DARRAY D3D11_DSV_DIMENSION_TEXTURE1DARRAY +#define D3D_DSV_DIMENSION_TEXTURE2D D3D11_DSV_DIMENSION_TEXTURE2D +#define D3D_DSV_DIMENSION_TEXTURE2DARRAY D3D11_DSV_DIMENSION_TEXTURE2DARRAY +#define D3D_DSV_DIMENSION_TEXTURE2DMS D3D11_DSV_DIMENSION_TEXTURE2DMS +#define D3D_DSV_DIMENSION_TEXTURE2DMSARRAY D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY + +// UAV Dimensions +#define D3D_UAV_DIMENSION_UNKNOWN D3D11_UAV_DIMENSION_UNKNOWN +#define D3D_UAV_DIMENSION_BUFFER D3D11_UAV_DIMENSION_BUFFER +#define D3D_UAV_DIMENSION_TEXTURE1D D3D11_UAV_DIMENSION_TEXTURE1D +#define D3D_UAV_DIMENSION_TEXTURE1DARRAY D3D11_UAV_DIMENSION_TEXTURE1DARRAY +#define D3D_UAV_DIMENSION_TEXTURE2D D3D11_UAV_DIMENSION_TEXTURE2D +#define D3D_UAV_DIMENSION_TEXTURE2DARRAY D3D11_UAV_DIMENSION_TEXTURE2DARRAY +#define D3D_UAV_DIMENSION_TEXTURE3D D3D11_UAV_DIMENSION_TEXTURE3D diff --git a/Graphics/GraphicsEngineD3D11/include/D3DErrors.h b/Graphics/GraphicsEngineD3D11/include/D3DErrors.h deleted file mode 100644 index 00029230..00000000 --- a/Graphics/GraphicsEngineD3D11/include/D3DErrors.h +++ /dev/null @@ -1,89 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -#include "Errors.h" - -/// \file -/// Declaration of Diligent::ComErrorDesc class - -namespace Diligent -{ - -/// Helper class that provides description of a COM error -class ComErrorDesc -{ -public: - ComErrorDesc( HRESULT hr ) - { - FormatMessageA( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - hr, - MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), - m_Msg, - _countof(m_Msg), - NULL ); - auto nLen = strlen( m_Msg ); - if( nLen > 1 && m_Msg[nLen - 1] == '\n' ) - { - m_Msg[nLen - 1] = 0; - if( m_Msg[nLen - 2] == '\r' ) - { - m_Msg[nLen - 2] = 0; - } - } - } - - const char* Get(){ return m_Msg; } - -private: - char m_Msg[4096]; -}; - -} - - -#define CHECK_D3D_RESULT_THROW(Expr, Message)\ -{ \ - HRESULT _hr_ = Expr; \ - if(FAILED(_hr_)) \ - { \ - ComErrorDesc ErrDesc( _hr_ ); \ - LOG_ERROR_AND_THROW( Message, "\nHRESULT Desc: ", ErrDesc.Get());\ - } \ -} - -#define CHECK_D3D_RESULT_THROW_EX(Expr, ...)\ -{ \ - HRESULT _hr_ = Expr; \ - if(FAILED(_hr_)) \ - { \ - Diligent::MsgStream ms; \ - Diligent::FormatMsg(ms, __VA_ARGS__); \ - ComErrorDesc ErrDesc( _hr_ ); \ - LOG_ERROR_AND_THROW( ms.str(), "\nHRESULT Desc: ", ErrDesc.Get());\ - } \ -} diff --git a/Graphics/GraphicsEngineD3D11/include/DSStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/DSStateD3D11Impl.h deleted file mode 100644 index 55aaa2ce..00000000 --- a/Graphics/GraphicsEngineD3D11/include/DSStateD3D11Impl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of Diligent::DSStateD3D11Impl class - -#include "DepthStencilStateD3D11.h" -#include "RenderDeviceD3D11.h" -#include "DepthStencilStateBase.h" - -namespace Diligent -{ - -/// Implementation of the Diligent::IDepthStencilStateD3D11 interface -class DSStateD3D11Impl : public DepthStencilStateBase -{ -public: - typedef DepthStencilStateBase TDepthStencilStateBase; - - DSStateD3D11Impl(class RenderDeviceD3D11Impl *pDeviceD3D11, const DepthStencilStateDesc& BuffDesc); - ~DSStateD3D11Impl(); - - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); - - ID3D11DepthStencilState *GetD3D11DepthStencilState(){ return m_pd3d11DepthStencilState; } - -private: - /// D3D11 depth-stencil state - Diligent::CComPtr m_pd3d11DepthStencilState; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h index a4102db6..e3b2c498 100644 --- a/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/DeviceContextD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,42 +43,44 @@ class DeviceContextD3D11Impl : public DeviceContextBase public: typedef DeviceContextBase TDeviceContextBase; - DeviceContextD3D11Impl(IRenderDevice *pDevice, ID3D11DeviceContext *pd3d11DeviceContext); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + DeviceContextD3D11Impl(IMemoryAllocator &Allocator, IRenderDevice *pDevice, ID3D11DeviceContext *pd3d11DeviceContext, const struct EngineD3D11Attribs &EngineAttribs, bool bIsDeferred); + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual void SetShaders( IShader **ppShaders, Uint32 NumShadersToSet )override; + virtual void SetPipelineState(IPipelineState *pPipelineState)override final; - virtual void BindShaderResources( IResourceMapping *pResourceMapping, Uint32 Flags )override; + virtual void TransitionShaderResources(IPipelineState *pPipelineState, IShaderResourceBinding *pShaderResourceBinding)override final; - virtual void SetVertexBuffers( Uint32 StartSlot, Uint32 NumBuffersSet, IBuffer **ppBuffers, Uint32 *pStrides, Uint32 *pOffsets, Uint32 Flags )override; - virtual void ClearState()override; + virtual void CommitShaderResources(IShaderResourceBinding *pShaderResourceBinding, Uint32 Flags)override final; - virtual void SetVertexDescription( IVertexDescription *pVertexDesc )override; + virtual void SetStencilRef(Uint32 StencilRef)override final; - virtual void SetIndexBuffer( IBuffer *pIndexBuffer, Uint32 ByteOffset )override; + virtual void SetBlendFactors(const float* pBlendFactors = nullptr)override final; - virtual void SetDepthStencilState( IDepthStencilState *pDepthStencilState, Uint32 StencilRef = 0 )override; + virtual void SetVertexBuffers( Uint32 StartSlot, Uint32 NumBuffersSet, IBuffer **ppBuffers, Uint32 *pStrides, Uint32 *pOffsets, Uint32 Flags )override final; + virtual void ClearState()override final; - virtual void SetRasterizerState( IRasterizerState *pRS )override; + virtual void SetIndexBuffer( IBuffer *pIndexBuffer, Uint32 ByteOffset )override final; - virtual void SetBlendState( IBlendState *pBS, const float* pBlendFactors, Uint32 SampleMask )override; + virtual void SetViewports( Uint32 NumViewports, const Viewport *pViewports, Uint32 RTWidth, Uint32 RTHeight )override final; - virtual void SetViewports( Uint32 NumViewports, const Viewport *pViewports, Uint32 RTWidth, Uint32 RTHeight )override; + virtual void SetScissorRects( Uint32 NumRects, const Rect *pRects, Uint32 RTWidth, Uint32 RTHeight )override final; - virtual void SetScissorRects( Uint32 NumRects, const Rect *pRects, Uint32 RTWidth, Uint32 RTHeight )override; + virtual void SetRenderTargets( Uint32 NumRenderTargets, ITextureView *ppRenderTargets[], ITextureView *pDepthStencil )override final; - virtual void SetRenderTargets( Uint32 NumRenderTargets, ITextureView *ppRenderTargets[], ITextureView *pDepthStencil )override; + virtual void Draw( DrawAttribs &DrawAttribs )override final; - virtual void Draw( DrawAttribs &DrawAttribs )override; + virtual void DispatchCompute( const DispatchComputeAttribs &DispatchAttrs )override final; - virtual void DispatchCompute( const DispatchComputeAttribs &DispatchAttrs )override; + virtual void ClearDepthStencil( ITextureView *pView, Uint32 ClearFlags, float fDepth, Uint8 Stencil)override final; - virtual void ClearDepthStencil( ITextureView *pView, Uint32 ClearFlags, float fDepth, Uint8 Stencil)override; + virtual void ClearRenderTarget( ITextureView *pView, const float *RGBA )override final; - virtual void ClearRenderTarget( ITextureView *pView, const float *RGBA )override; - - virtual void Flush()override; + virtual void Flush()override final; + void FinishCommandList(class ICommandList **ppCommandList)override final; + + virtual void ExecuteCommandList(class ICommandList *pCommandList)override final; + ID3D11DeviceContext* GetD3D11DeviceContext(){ return m_pd3d11DeviceContext; } void RebindRenderTargets(); @@ -93,166 +95,187 @@ public: private: - /// Goes through the list of bound shaders and binds all required - /// d3d11 resource to the d3d11 device context, for each shader. - void SetD3DShadersAndResources(); - - /// Binds d3d11 index buffer to the d3d11 device context. - void SetD3DIndexBuffer(VALUE_TYPE IndexType); - - /// Binds d3d11 vertex buffers to the d3d11 device context. - void SetD3DVertexBuffers(); + /// Commits d3d11 index buffer to the d3d11 device context. + void CommitD3D11IndexBuffer(VALUE_TYPE IndexType); - /// Binds d3d11 constant buffers to the d3d11 device context - void SetD3DConstantBuffers ( class ShaderD3D11Impl *pShader ); - /// Binds d3d11 shader resource views to the d3d11 device context - void SetD3DSRVs ( class ShaderD3D11Impl *pShader ); - /// Binds d3d11 unordered access views to the d3d11 device context - void SetD3DUAVs ( class ShaderD3D11Impl *pShader ); - /// Binds d3d11 samplers to the d3d11 device context - void SetD3DSamplers ( class ShaderD3D11Impl *pShader ); + /// Commits d3d11 vertex buffers to the d3d11 device context. + void CommitD3D11VertexBuffers(class PipelineStateD3D11Impl *pPipelineStateD3D11); /// Helper template function used to facilitate resource unbinding - template - void UnbindResourceView(std::vector BoundResourcesArr[], - std::vector BoundD3D11ResourcesArr[], + template + void UnbindResourceView(TD3D11ResourceViewType CommittedD3D11ViewsArr[][NumSlots], + ID3D11Resource* CommittedD3D11ResourcesArr[][NumSlots], + Uint8 NumCommittedResourcesArr[], IDeviceObject *pResToUnbind, + ID3D11Resource *pd3d11ResToUndind, TSetD3D11View SetD3D11ViewMethods[]); /// Unbinds a texture from the shader resource view slots. /// \note The function only unbinds the texture from d3d11 device /// context. All shader bindings are retained. - void UnbindTextureFromInput(ITexture *pTexture); + void UnbindTextureFromInput(TextureBaseD3D11 *pTexture, ID3D11Resource *pd3d11Resource); /// Unbinds a buffer from the input (shader resource views slots, index /// and vertex buffer slots). /// \note The function only unbinds the buffer from d3d11 device /// context. All shader bindings are retained. - void UnbindBufferFromInput(IBuffer *pBuffer); + void UnbindBufferFromInput(BufferD3D11Impl *pBuffer, ID3D11Resource *pd3d11Buffer); /// Unbinds a resource from the UAV slots. /// \note The function only unbinds the texture from the device /// context. All shader bindings are retained. - void UnbindResourceFromUAV(IDeviceObject *pResource); + void UnbindResourceFromUAV(IDeviceObject *pResource, ID3D11Resource *pd3d11Resource); /// Unbinds a texture from render target slots. - void UnbindTextureFromRenderTarget(IDeviceObject *pResource); + void UnbindTextureFromRenderTarget(TextureBaseD3D11 *pResource); /// Unbinds a texture from depth-stencil. - void UnbindTextureFromDepthStencil(IDeviceObject *pResource); - - /// Helper template function that facilitates shader binding - /// \tparam TD3D11ShaderType - Type of D3D11 shader being set (ID3D11PixelShader, ID3D11VertexShader, etc.) - /// \tparam TBindShaderMethdType - Type of the d3d11 device context mehtod that sets the shader - /// (ID3D11DeviceContext::VSSetShader, ID3D11DeviceContext::PSSetShader, etc.) - /// \param BoundShaderFlags - Flags indicating which shader stages are currently active - /// \param NewShaders - Array of pointers to the new shaders to be bound - /// \param ShaderType - Type of the shader being bound - /// \param BindShaderMethod - Pointer to the d3d11 device context mehtod that sets the shader - /// (ID3D11DeviceContext::VSSetShader, ID3D11DeviceContext::PSSetShader, etc.) - template - void SetD3D11ShaderHelper(Uint32 BoundShaderFlags, - ShaderD3D11Impl* NewShaders[], - SHADER_TYPE ShaderType, - TBindShaderMethdType BindShaderMethod); - - Diligent::CComPtr m_pd3d11DeviceContext; ///< D3D11 device context - DrawAttribs m_LastDrawAttribs; - - /// An array of D3D11 constant buffers currently bound to the D3D11 device context, - /// for each shader type. - std::vector m_BoundD3D11CBs [NumShaderTypes]; - /// An array of D3D11 shader resource views currently bound to the D3D11 device context, - /// for each shader type. - std::vector m_BoundD3D11SRVs [NumShaderTypes]; - /// An array of D3D11 samplers currently bound to the D3D11 device context, - /// for each shader type. - std::vector m_BoundD3D11Samplers[NumShaderTypes]; - /// An array of D3D11 UAVs currently bound to the D3D11 device context, - /// for each shader type. - std::vector m_BoundD3D11UAVs [NumShaderTypes]; - - /// An array of strong references to resources associated with the bound - /// constant buffers, for each shader type. - std::vector m_BoundCBs[NumShaderTypes]; - /// An array of strong references to resources associated with the - /// bound SRV, for each shader type. - std::vector m_BoundSRVs[NumShaderTypes]; - /// An array of strong references to resources associated with the - /// bound samplers, for each shader type. - std::vector m_BoundSamplers[NumShaderTypes]; - /// An array of strong references to resources associated with the - /// bound UAVs, for each shader type. - std::vector m_BoundUAVs[NumShaderTypes]; - - /// An array of D3D11 vertex buffers currently bound to the D3D device context - std::vector< Diligent::CComPtr > m_BoundD3D11VertexBuffers; - /// An array of strides of currently bound vertex buffers - std::vector< UINT > m_BoundD3D11VBStrides; - /// An array of offsets of currently bound vertex buffers - std::vector< UINT > m_BoundD3D11VBOffsets; - - /// Strong reference to the D3D11 buffer currently bound as index buffer + void UnbindTextureFromDepthStencil(TextureBaseD3D11 *pTexD3D11); + + template + void TransitionAndCommitShaderResources(IPipelineState *pPSO, IShaderResourceBinding *pShaderResourceBinding); + + void ClearStateCache(); + + CComPtr m_pd3d11DeviceContext; ///< D3D11 device context + + /// An array of D3D11 constant buffers committed to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11Buffer* m_CommittedD3D11CBs [NumShaderTypes][D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT]; + + /// An array of D3D11 shader resource views committed to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11ShaderResourceView* m_CommittedD3D11SRVs [NumShaderTypes][D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]; + + /// An array of D3D11 samplers committed to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11SamplerState* m_CommittedD3D11Samplers[NumShaderTypes][D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT]; + + /// An array of D3D11 UAVs committed to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11UnorderedAccessView* m_CommittedD3D11UAVs [NumShaderTypes][D3D11_PS_CS_UAV_REGISTER_COUNT]; + + /// An array of D3D11 resources commited as SRV to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11Resource* m_CommittedD3D11SRVResources [NumShaderTypes][D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]; + + /// An array of D3D11 resources commited as UAV to the D3D11 device context, + /// for each shader type. Device context addref's all bound resources, so we do + /// not need to keep strong references + ID3D11Resource* m_CommittedD3D11UAVResources [NumShaderTypes][D3D11_PS_CS_UAV_REGISTER_COUNT]; + + Uint8 m_NumCommittedCBs[NumShaderTypes] = {}; + Uint8 m_NumCommittedSRVs[NumShaderTypes]= {}; + Uint8 m_NumCommittedSamplers[NumShaderTypes]= {}; + Uint8 m_NumCommittedUAVs[NumShaderTypes]= {}; + + /// An array of D3D11 vertex buffers committed to the D3D device context + /// There is no need to keep strong references because D3D11 device context + /// already does. Buffers cannot be destroyed while bound to the context. + /// We only mirror all bindings. + ID3D11Buffer* m_CommittedD3D11VertexBuffers[MaxBufferSlots] = {}; + /// An array of strides of committed vertex buffers + UINT m_CommittedD3D11VBStrides[MaxBufferSlots]; + /// An array of offsets of committed vertex buffers + UINT m_CommittedD3D11VBOffsets[MaxBufferSlots]; + /// Number committed vertex buffers + UINT m_NumCommittedD3D11VBs; + /// Flag indicating if currently committed D3D11 vertex buffers are up to date + bool m_bCommittedD3D11VBsUpToDate = false; + + /// D3D11 input layout committed to the device object. + /// Device context keeps the layout alive, so there is no need + /// to keep strong reference + ID3D11InputLayout *m_CommittedD3D11InputLayout = nullptr; + + /// Strong reference to the D3D11 buffer committed as index buffer /// to the D3D device context - Diligent::CComPtr m_BoundD3D11IndexBuffer; - /// Format of currently bound D3D11 index buffer - DXGI_FORMAT m_BoundD3D11IndexFmt; - /// Offset of currently bound D3D11 index buffer - Uint32 m_BoundD3D11IndexDataStartOffset; + CComPtr m_CommittedD3D11IndexBuffer; + /// Format of the committed D3D11 index buffer + VALUE_TYPE m_CommittedIBFormat; + /// Offset of the committed D3D11 index buffer + Uint32 m_CommittedD3D11IndexDataStartOffset; + /// Flag indicating if currently committed D3D11 index buffer is up to date + bool m_bCommittedD3D11IBUpToDate = false; - /// Strong references to the currently bound D3D11 shaders - Diligent::CComPtr m_BoundD3DShaders[NumShaderTypes]; + D3D11_PRIMITIVE_TOPOLOGY m_CommittedD3D11PrimTopology = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; + PRIMITIVE_TOPOLOGY m_CommittedPrimitiveTopology = PRIMITIVE_TOPOLOGY_UNDEFINED; -#ifdef VERIFY_CONTEXT_BINDINGS - /// Helper template function used to facilitate context verification - template - void dbgVerifyContextResources(std::vector BoundD3D11ResourcesArr[], - TGetD3D11ResourcesType GetD3D11ResMethods[], - const Char *ResourceName, - SHADER_TYPE ShaderType); + /// Strong references to the committed D3D11 shaders + CComPtr m_CommittedD3DShaders[NumShaderTypes]; - /// Debug function that verifies that SRVs cached in m_BoundD3D11SRVs - /// array comply with resources actually bound to the D3D11 device context - void dbgVerifyContextSRVs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + Uint32 m_DebugFlags; - /// Debug function that verifies that UAVs cached in m_BoundD3D11UAVs - /// array comply with resources actually bound to the D3D11 device context - void dbgVerifyContextUAVs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + FixedBlockMemoryAllocator m_CmdListAllocator; - /// Debug function that verifies that samplers cached in m_BoundD3D11Samplers - /// array comply with resources actually bound to the D3D11 device context - void dbgVerifyContextSamplers(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); +#ifdef VERIFY_CONTEXT_BINDINGS + /// Verifies that bound render target formats are consistent with the PSO + void dbgVerifyRenderTargetFormats(); - /// Debug function that verifies that constant buffers cached in m_BoundD3D11CBs - /// array comply with buffers actually bound to the D3D11 device context - void dbgVerifyContextCBs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + /// Helper template function used to facilitate context verification + template + void dbgVerifyCommittedResources(TD3D11ResourceType CommittedD3D11ResourcesArr[][MaxResources], + Uint8 NumCommittedResourcesArr[], + TGetD3D11ResourcesType GetD3D11ResMethods[], + const Char *ResourceName, + SHADER_TYPE ShaderType); + + /// Helper template function used to facilitate validation of SRV and UAV consistency with D3D11 resources + template + void dbgVerifyViewConsistency(TD3D11ViewType CommittedD3D11ViewArr[][MaxResources], + ID3D11Resource* CommittedD3D11ResourcesArr[][MaxResources], + Uint8 NumCommittedResourcesArr[], + const Char *ResourceName, + SHADER_TYPE ShaderType); + + /// Debug function that verifies that SRVs cached in m_CommittedD3D11SRVs + /// array comply with resources actually committed to the D3D11 device context + void dbgVerifyCommittedSRVs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + + /// Debug function that verifies that UAVs cached in m_CommittedD3D11UAVs + /// array comply with resources actually committed to the D3D11 device context + void dbgVerifyCommittedUAVs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + + /// Debug function that verifies that samplers cached in m_CommittedD3D11Samplers + /// array comply with resources actually committed to the D3D11 device context + void dbgVerifyCommittedSamplers(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); + + /// Debug function that verifies that constant buffers cached in m_CommittedD3D11CBs + /// array comply with buffers actually committed to the D3D11 device context + void dbgVerifyCommittedCBs(SHADER_TYPE ShaderType = SHADER_TYPE_UNKNOWN); /// Debug function that verifies that the index buffer cached in - /// m_BoundD3D11IndexBuffer is the buffer actually bound to the D3D11 + /// m_CommittedD3D11IndexBuffer is the buffer actually committed to the D3D11 /// device context - void dbgVerifyIndexBuffer(); + void dbgVerifyCommittedIndexBuffer(); /// Debug function that verifies that vertex buffers cached in - /// m_BoundD3D11VertexBuffers are the buffers actually bound to the D3D11 + /// m_CommittedD3D11VertexBuffers are the buffers actually committed to the D3D11 /// device context - void dbgVerifyVertexBuffers(); + void dbgVerifyCommittedVertexBuffers(); /// Debug function that verifies that shaders cached in - /// m_BoundD3DShaders are the shaders actually bound to the D3D11 + /// m_CommittedD3DShaders are the shaders actually committed to the D3D11 /// device context - void dbgVerifyShaders(); + void dbgVerifyCommittedShaders(); #else - - #define dbgVerifyContextSRVs(...) - #define dbgVerifyContextUAVs(...) - #define dbgVerifyContextSamplers(...) - #define dbgVerifyContextCBs(...) - #define dbgVerifyIndexBuffer(...) - #define dbgVerifyVertexBuffers(...) - #define dbgVerifyShaders(...) + #define dbgVerifyRenderTargetFormats(...) + #define dbgVerifyCommittedSRVs(...) + #define dbgVerifyCommittedUAVs(...) + #define dbgVerifyCommittedSamplers(...) + #define dbgVerifyCommittedCBs(...) + #define dbgVerifyCommittedIndexBuffer(...) + #define dbgVerifyCommittedVertexBuffers(...) + #define dbgVerifyCommittedShaders(...) #endif }; diff --git a/Graphics/GraphicsEngineD3D11/include/EngineD3D11Defines.h b/Graphics/GraphicsEngineD3D11/include/EngineD3D11Defines.h new file mode 100644 index 00000000..9a5cee9b --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/EngineD3D11Defines.h @@ -0,0 +1,28 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +#ifdef _DEBUG +# define VERIFY_SHADER_BINDINGS +#endif diff --git a/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions.fxh b/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions.fxh deleted file mode 100644 index fd19be08..00000000 --- a/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions.fxh +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef _HLSL_DEFINITIONS_ -#define _HLSL_DEFINITIONS_ - -#define HLSL - -#define NDC_MIN_Z 0.0 // Minimal z in the normalized device space - -#define F3NDC_XYZ_TO_UVD_SCALE float3(0.5, -0.5, 1.0) - -float2 NormalizedDeviceXYToTexUV( float2 f2ProjSpaceXY ) -{ - return float2(0.5,0.5) + float2(0.5,-0.5) * f2ProjSpaceXY.xy; -} - -float NormalizedDeviceZToDepth(float fNDC_Z) -{ - return fNDC_Z; -} - -float DepthToNormalizedDeviceZ(float fDepth) -{ - return fDepth; -} - -// Relational and logical operators -#define Less(x,y) ((x)<(y)) -#define LessEqual(x,y) ((x)<=(y)) -#define Greater(x,y) ((x)>(y)) -#define GreaterEqual(x,y) ((x)>=(y)) -#define Equal(x,y) ((x)==(y)) -#define NotEqual(x,y) ((x)!=(y)) -#define Not(x) (!(x)) -#define And(x,y) ((x)&&(y)) -#define Or(x,y) ((x)||(y)) - -float4 BoolToFloat( bool4 b4 ) -{ - return float4(b4.x ? 1.0 : 0.0, - b4.y ? 1.0 : 0.0, - b4.z ? 1.0 : 0.0, - b4.w ? 1.0 : 0.0); -} -float3 BoolToFloat( bool3 b3 ) -{ - return float3(b3.x ? 1.0 : 0.0, - b3.y ? 1.0 : 0.0, - b3.z ? 1.0 : 0.0); -} -float2 BoolToFloat( bool2 b2 ) -{ - return float2(b2.x ? 1.0 : 0.0, - b2.y ? 1.0 : 0.0); -} -float BoolToFloat( bool b ) -{ - return b.x ? 1.0 : 0.0; -} - -#define MATRIX_ELEMENT(mat, row, col) mat[row][col] - -#endif // _HLSL_DEFINITIONS_ diff --git a/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions_inc.fxh b/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions_inc.fxh deleted file mode 100644 index 84012ff1..00000000 --- a/Graphics/GraphicsEngineD3D11/include/HLSLDefinitions_inc.fxh +++ /dev/null @@ -1,61 +0,0 @@ -"#ifndef _HLSL_DEFINITIONS_\n" -"#define _HLSL_DEFINITIONS_\n" -"\n" -"#define HLSL\n" -"\n" -"#define NDC_MIN_Z 0.0 // Minimal z in the normalized device space\n" -"\n" -"#define F3NDC_XYZ_TO_UVD_SCALE float3(0.5, -0.5, 1.0)\n" -"\n" -"float2 NormalizedDeviceXYToTexUV( float2 f2ProjSpaceXY )\n" -"{\n" -" return float2(0.5,0.5) + float2(0.5,-0.5) * f2ProjSpaceXY.xy;\n" -"}\n" -"\n" -"float NormalizedDeviceZToDepth(float fNDC_Z)\n" -"{\n" -" return fNDC_Z;\n" -"}\n" -"\n" -"float DepthToNormalizedDeviceZ(float fDepth)\n" -"{\n" -" return fDepth;\n" -"}\n" -"\n" -"// Relational and logical operators\n" -"#define Less(x,y) ((x)<(y))\n" -"#define LessEqual(x,y) ((x)<=(y))\n" -"#define Greater(x,y) ((x)>(y))\n" -"#define GreaterEqual(x,y) ((x)>=(y))\n" -"#define Equal(x,y) ((x)==(y))\n" -"#define NotEqual(x,y) ((x)!=(y))\n" -"#define Not(x) (!(x))\n" -"#define And(x,y) ((x)&&(y))\n" -"#define Or(x,y) ((x)||(y))\n" -"\n" -"float4 BoolToFloat( bool4 b4 )\n" -"{\n" -" return float4(b4.x ? 1.0 : 0.0,\n" -" b4.y ? 1.0 : 0.0,\n" -" b4.z ? 1.0 : 0.0,\n" -" b4.w ? 1.0 : 0.0);\n" -"}\n" -"float3 BoolToFloat( bool3 b3 )\n" -"{\n" -" return float3(b3.x ? 1.0 : 0.0,\n" -" b3.y ? 1.0 : 0.0,\n" -" b3.z ? 1.0 : 0.0);\n" -"}\n" -"float2 BoolToFloat( bool2 b2 )\n" -"{\n" -" return float2(b2.x ? 1.0 : 0.0,\n" -" b2.y ? 1.0 : 0.0);\n" -"}\n" -"float BoolToFloat( bool b )\n" -"{\n" -" return b.x ? 1.0 : 0.0;\n" -"}\n" -"\n" -"#define MATRIX_ELEMENT(mat, row, col) mat[row][col]\n" -"\n" -"#endif // _HLSL_DEFINITIONS_\n" diff --git a/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h new file mode 100644 index 00000000..cb89e92a --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/PipelineStateD3D11Impl.h @@ -0,0 +1,100 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of Diligent::PipelineStateD3D11Impl class + +#include "PipelineStateD3D11.h" +#include "RenderDeviceD3D11.h" +#include "PipelineStateBase.h" +#include "ShaderD3D11Impl.h" +#include "AdaptiveFixedBlockAllocator.h" + +namespace Diligent +{ + +class FixedBlockMemoryAllocator; +/// Implementation of the Diligent::IPipelineStateD3D11 interface +class PipelineStateD3D11Impl : public PipelineStateBase +{ +public: + typedef PipelineStateBase TPipelineStateBase; + + PipelineStateD3D11Impl(FixedBlockMemoryAllocator &PSOAllocator, class RenderDeviceD3D11Impl *pDeviceD3D11, const PipelineStateDesc& PipelineDesc); + ~PipelineStateD3D11Impl(); + + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + + /// Implementation of the IPipelineStateD3D11::GetD3D11BlendState() method. + virtual ID3D11BlendState* GetD3D11BlendState()override final; + + /// Implementation of the IPipelineStateD3D11::GetD3D11RasterizerState() method. + virtual ID3D11RasterizerState* GetD3D11RasterizerState()override final; + + /// Implementation of the IPipelineStateD3D11::GetD3D11DepthStencilState() method. + virtual ID3D11DepthStencilState* GetD3D11DepthStencilState()override final; + + virtual ID3D11InputLayout* GetD3D11InputLayout()override final; + + virtual ID3D11VertexShader* GetD3D11VertexShader()override final; + virtual ID3D11PixelShader* GetD3D11PixelShader()override final; + virtual ID3D11GeometryShader* GetD3D11GeometryShader()override final; + virtual ID3D11DomainShader* GetD3D11DomainShader()override final; + virtual ID3D11HullShader* GetD3D11HullShader()override final; + virtual ID3D11ComputeShader* GetD3D11ComputeShader()override final; + + virtual void BindShaderResources( IResourceMapping *pResourceMapping, Uint32 Flags )override final; + + virtual void CreateShaderResourceBinding( IShaderResourceBinding **ppShaderResourceBinding )override final; + + class ShaderResourceBindingD3D11Impl* GetDefaultResourceBinding(){return m_pDefaultShaderResBinding.get();} + IMemoryAllocator &GetResourceCacheDataAllocator(Uint32 Ind) + { + VERIFY_EXPR(Ind < _countof(m_ResourceCacheDataAllocators)); + return m_ResourceCacheDataAllocators[Ind]; + } + IMemoryAllocator &GetShaderResLayoutDataAllocators(Uint32 Ind) + { + VERIFY_EXPR(Ind < _countof(m_ShaderResLayoutDataAllocators)); + return m_ShaderResLayoutDataAllocators[Ind]; + } + IShaderVariable* GetDummyShaderVariable(){return &m_DummyShaderVar;} + +private: + CComPtr m_pd3d11BlendState; + CComPtr m_pd3d11RasterizerState; + CComPtr m_pd3d11DepthStencilState; + CComPtr m_pd3d11InputLayout; + + AdaptiveFixedBlockAllocator m_ShaderResLayoutDataAllocators[5]; // Use separate allocator for every shader stage + AdaptiveFixedBlockAllocator m_ResourceCacheDataAllocators[5]; // Use separate allocator for every shader stage + + // Do not use strong reference to avoid cyclic references + std::unique_ptr > m_pDefaultShaderResBinding; + + DummyShaderVariable m_DummyShaderVar; ///< Dummy shader variable +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/RasterizerStateD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/RasterizerStateD3D11Impl.h deleted file mode 100644 index aad6f2ad..00000000 --- a/Graphics/GraphicsEngineD3D11/include/RasterizerStateD3D11Impl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of Diligent::RasterizerStateD3D11Impl class - -#include "RasterizerStateD3D11.h" -#include "RenderDeviceD3D11.h" -#include "RasterizerStateBase.h" - -namespace Diligent -{ - -/// Implementation of the Diligent::IRasterizerStateD3D11 interface -class RasterizerStateD3D11Impl : public RasterizerStateBase -{ -public: - typedef RasterizerStateBase TRasterizerStateBase; - - RasterizerStateD3D11Impl(class RenderDeviceD3D11Impl *pDeviceD3D11, const RasterizerStateDesc& BuffDesc); - ~RasterizerStateD3D11Impl(); - - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); - - ID3D11RasterizerState *GetD3D11RasterizerState(){ return m_pd3d11RasterizerState; } - -private: - /// D3D11 rasterizer state - Diligent::CComPtr m_pd3d11RasterizerState; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h index 0f374b5c..0d4547e5 100644 --- a/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/RenderDeviceD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,47 +27,41 @@ /// Declaration of Diligent::RenderDeviceD3D11Impl class #include "RenderDeviceD3D11.h" -#include "RenderDeviceBase.h" +#include "RenderDeviceD3DBase.h" #include "DeviceContextD3D11.h" +#include "EngineD3D11Attribs.h" -/// Namespace for the Direct3D11 implementation of the graphics engine namespace Diligent { /// Implementation of the Diligent::IRenderDeviceD3D11 interface -class RenderDeviceD3D11Impl : public RenderDeviceBase +class RenderDeviceD3D11Impl : public RenderDeviceD3DBase { public: - typedef RenderDeviceBase TRenderDeviceBase; + typedef RenderDeviceD3DBase TRenderDeviceBase; - RenderDeviceD3D11Impl( ID3D11Device *pd3d11Device ); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + RenderDeviceD3D11Impl( IMemoryAllocator &RawMemAllocator, const EngineD3D11Attribs& EngineAttribs, ID3D11Device *pd3d11Device, Uint32 NumDeferredContexts ); + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData &BuffData, IBuffer **ppBuffer); + virtual void CreateBuffer(const BufferDesc& BuffDesc, const BufferData &BuffData, IBuffer **ppBuffer)override final; - virtual void CreateVertexDescription( const LayoutDesc& LayoutDesc, IShader *pVertexShader, IVertexDescription **ppVertexDesc ); + virtual void CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader)override final; - virtual void CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader); - - virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData &Data, ITexture **ppTexture); + virtual void CreateTexture(const TextureDesc& TexDesc, const TextureData &Data, ITexture **ppTexture)override final; - virtual void CreateSampler(const SamplerDesc& SamplerDesc, ISampler **ppSampler); - - virtual void CreateDepthStencilState( const DepthStencilStateDesc &DSSDesc, IDepthStencilState **ppDepthStencilState ); + virtual void CreateSampler(const SamplerDesc& SamplerDesc, ISampler **ppSampler)override final; - virtual void CreateRasterizerState( const RasterizerStateDesc &RSDesc, IRasterizerState **ppRasterizerState ); + virtual void CreatePipelineState( const PipelineStateDesc &PipelineDesc, IPipelineState **ppPipelineState )override final; - virtual void CreateBlendState( const BlendStateDesc &BSDesc, IBlendState **ppBlendState ); + ID3D11Device* GetD3D11Device()override final{return m_pd3d11Device;} - ID3D11Device* GetD3D11Device(){return m_pd3d11Device;} - private: virtual void TestTextureFormat( TEXTURE_FORMAT TexFormat ); - void FlagSupportedTexFormats(); + EngineD3D11Attribs m_EngineAttribs; /// D3D11 device - Diligent::CComPtr m_pd3d11Device; + CComPtr m_pd3d11Device; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h index f48d645e..3fd8b138 100644 --- a/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/SamplerD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,23 +33,23 @@ namespace Diligent { +class FixedBlockMemoryAllocator; /// Implementation of the Diligent::ISamplerD3D11 interface -class SamplerD3D11Impl : public SamplerBase +class SamplerD3D11Impl : public SamplerBase { public: - typedef SamplerBase TSamplerBase; + typedef SamplerBase TSamplerBase; - SamplerD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const SamplerDesc& SamplerDesc); + SamplerD3D11Impl(FixedBlockMemoryAllocator &SamplerObjAllocator, class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const SamplerDesc& SamplerDesc); ~SamplerD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ) final; - virtual ID3D11SamplerState* GetD3D11SamplerState(){ return m_pd3dSampler; } + virtual ID3D11SamplerState* GetD3D11SamplerState()override final{ return m_pd3dSampler; } private: - friend class ShaderD3D11Impl; /// D3D11 sampler - Diligent::CComPtr m_pd3dSampler; + CComPtr m_pd3dSampler; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h index 4066947e..44ecad0f 100644 --- a/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/ShaderD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,203 +29,55 @@ #include "ShaderD3D11.h" #include "RenderDeviceD3D11.h" #include "ShaderBase.h" - -#ifdef _DEBUG -# define VERIFY_SHADER_BINDINGS -#endif +#include "ShaderD3DBase.h" +#include "ShaderResourceLayoutD3D11.h" +#include "ShaderResourceCacheD3D11.h" +#include "EngineD3D11Defines.h" +#include "ShaderResourcesD3D11.h" namespace Diligent { +class FixedBlockMemoryAllocator; class ResourceMapping; /// Implementation of the Diligent::IShaderD3D11 interface -class ShaderD3D11Impl : public ShaderBase +class ShaderD3D11Impl : public ShaderBase, public ShaderD3DBase { public: - typedef ShaderBase TShaderBase; + typedef ShaderBase TShaderBase; - ShaderD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const ShaderCreationAttribs &ShaderCreationAttribs); + ShaderD3D11Impl(FixedBlockMemoryAllocator &ShaderObjAllocator, class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const ShaderCreationAttribs &CreationAttribs); ~ShaderD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override; + virtual void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags )override final; - virtual IShaderVariable* GetShaderVariable( const Char* Name )override; - - /// Describes resources associated with the bound constant buffer - struct BoundCB - { - /// Strong reference to the buffer - Diligent::RefCntAutoPtr pBuff; - /// Strong referene to the D3D11 buffer interface - Diligent::CComPtr pd3d11Buff; - }; - - /// Describes resources associated with the bound sampler - struct BoundSampler - { - /// Strong reference to the sampler - Diligent::RefCntAutoPtr pSampler; - /// Strong referene to the D3D11 sampler state interface - Diligent::CComPtr pd3d11Sampler; - }; - - /// Describes resources associated with the bound SRV - struct BoundSRV - { - /// Strong reference to the resource bound as SRV - Diligent::RefCntAutoPtr pResource; - /// Strong reference to the resource view - Diligent::RefCntAutoPtr pView; - /// Strong referene to the D3D11 SRV interface - Diligent::CComPtr pd3d11View; - }; - - /// Describes resources associated with the bound UAV - struct BoundUAV - { - /// Strong reference to the resource bound as UAV - Diligent::RefCntAutoPtr pResource; - /// Strong reference to the resource view - Diligent::RefCntAutoPtr pView; - /// Strong referene to the D3D11 UAV interface - Diligent::CComPtr pd3d11View; - }; - - /// Returns a const reference to the zero-slot-based array of bound constant buffers - const std::vector< BoundCB >& GetBoundCBs() { return m_BoundCBs; } - /// Returns a const reference to the zero-slot-based array of bound samplers - const std::vector< BoundSampler >& GetBoundSamplers() { return m_BoundSamplers; } - /// Returns a const reference to the zero-slot-based array bound SRVs - const std::vector< BoundSRV >& GetBoundSRVs() { return m_BoundSRVs; } - /// Returns a const reference to the zero-slot-based array bound UAVs - const std::vector< BoundUAV >& GetBoundUAVs() { return m_BoundUAVs; } - - virtual ID3D11DeviceChild* GetD3D11Shader()override{ return m_pShader; } - -#ifdef VERIFY_SHADER_BINDINGS - void dbgVerifyBindings(); -#endif + virtual IShaderVariable* GetShaderVariable( const Char* Name )override final; -private: - void BindConstantBuffers( IResourceMapping* pResourceMapping, Uint32 Flags ); - - void BindSRVsAndSamplers( IResourceMapping* pResourceMapping, Uint32 Flags ); - - void BindUAVs( IResourceMapping* pResourceMapping, Uint32 Flags ); - - static const String m_SamplerSuffix; - - struct D3D11ShaderVarBase : ShaderVariableBase - { - D3D11ShaderVarBase( ShaderD3D11Impl *pShader, const String& _Name, UINT _BindPoint ) : - ShaderVariableBase( pShader ), - Name(_Name), - BindPoint(_BindPoint) - {} - - String Name; - UINT BindPoint; - const String& GetName(){ return Name; } - }; - - struct ConstBuffBindInfo : D3D11ShaderVarBase - { - ConstBuffBindInfo( ShaderD3D11Impl *pShader, const String& _Name, UINT _BindPoint ) : - D3D11ShaderVarBase( pShader, _Name, _BindPoint ) - {} - virtual void Set(IDeviceObject *pObject)override; - bool IsBound(); - }; - - struct TexAndSamplerBindInfo : D3D11ShaderVarBase - { - TexAndSamplerBindInfo( ShaderD3D11Impl *pShader, const String& _TexName, UINT _TexBindPoint, const String &_SamplerName, UINT _SamplerBindPoint ) : - D3D11ShaderVarBase( pShader, _TexName, _TexBindPoint), - SamplerName(_SamplerName), - SamplerBindPoint(_SamplerBindPoint) - {} - - String SamplerName; - UINT SamplerBindPoint; - virtual void Set(IDeviceObject *pObject)override; - bool IsBound(); - }; - - struct UAVBindInfoBase : public D3D11ShaderVarBase - { - UAVBindInfoBase( ShaderD3D11Impl *pShader, const String& _Name, UINT _BindPoint, D3D_SHADER_INPUT_TYPE _Type ) : - D3D11ShaderVarBase( pShader, _Name, _BindPoint), - Type(_Type) - {} - - bool IsBound(); - D3D_SHADER_INPUT_TYPE Type; - }; - - struct TexUAVBindInfo : UAVBindInfoBase - { - TexUAVBindInfo( ShaderD3D11Impl *pShader, const String& _Name, UINT _BindPoint, D3D_SHADER_INPUT_TYPE _Type ) : - UAVBindInfoBase( pShader, _Name, _BindPoint, _Type ) - {} - - virtual void Set(IDeviceObject *pObject)override; - }; - - struct BuffUAVBindInfo : UAVBindInfoBase - { - BuffUAVBindInfo( ShaderD3D11Impl *pShader, const String& _Name, UINT _BindPoint, D3D_SHADER_INPUT_TYPE _Type ) : - UAVBindInfoBase( pShader, _Name, _BindPoint, _Type ) - {} - - virtual void Set(IDeviceObject *pObject)override; - }; - - struct BuffSRVBindInfo : D3D11ShaderVarBase - { - BuffSRVBindInfo( ShaderD3D11Impl *pShader, const String &_Name, UINT _BindPoint ) : - D3D11ShaderVarBase( pShader, _Name, _BindPoint) - {} - - virtual void Set(IDeviceObject *pObject)override; - bool IsBound(); - }; - - void LoadShaderResources(); - - friend class VertexDescD3D11Impl; - friend class DeviceContextD3D11Impl; - /// D3D11 shader - Diligent::CComPtr m_pShader; - Diligent::CComPtr m_pShaderByteCode;// Only stored for Vertex Shader + virtual ID3D11DeviceChild* GetD3D11Shader()override final{ return m_pShader; } - std::vector m_ConstanBuffers; - std::vector m_TexAndSamplers; - std::vector m_TexUAVs; - std::vector m_BuffUAVs; - std::vector m_BuffSRVs; + ID3DBlob* GetBytecode(){return m_pShaderByteCode;} + ShaderResourceLayoutD3D11& GetStaticResourceLayout(){return m_StaticResLayout;} + const std::shared_ptr& GetResources(){return m_pShaderResources;} + Uint32 GetShaderTypeIndex(){return m_ShaderTypeIndex;} - /// An array of bound constant buffers. The data always starts at - /// slot 0 even when no resource is actually bound to the slot. - std::vector m_BoundCBs; - - /// An array of bound samplers. The data always starts at - /// slot 0 even when no sampler is actually bound to the slot. - std::vector m_BoundSamplers; +private: - /// An array of bound SRVs. The data always starts at - /// slot 0 even when no resource is actually bound to the slot. - std::vector m_BoundSRVs; + DummyShaderVariable m_DummyShaderVar; ///< Dummy shader variable - /// An array of bound UAVs. The data always starts at - /// slot 0 even when no resource is actually bound to the slot. - std::vector m_BoundUAVs; + /// D3D11 shader + CComPtr m_pShader; + + // ShaderResources class instance must be referenced through the shared pointer, because + // it is referenced by ShaderResourceLayoutD3D11 class instances + std::shared_ptr m_pShaderResources; - /// Hash map to look up shader variables by name. - std::unordered_map m_VariableHash; + ShaderResourceCacheD3D11 m_StaticResCache; + ShaderResourceLayoutD3D11 m_StaticResLayout; + Uint32 m_ShaderTypeIndex; // VS == 0, PS == 1, GS == 2, HS == 3, DS == 4, CS == 5 }; } diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h new file mode 100644 index 00000000..8afcab2c --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceBindingD3D11Impl.h @@ -0,0 +1,81 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of Diligent::ShaderResourceBindingD3D11Impl class + +#include "ShaderResourceBindingD3D11.h" +#include "RenderDeviceD3D11.h" +#include "ShaderResourceBindingBase.h" +#include "ShaderResourceCacheD3D11.h" +#include "ShaderResourceLayoutD3D11.h" +#include "STDAllocator.h" + +namespace Diligent +{ + +class FixedBlockMemoryAllocator; +/// Implementation of the Diligent::IShaderResourceBindingD3D11 interface +class ShaderResourceBindingD3D11Impl : public ShaderResourceBindingBase +{ +public: + typedef ShaderResourceBindingBase TBase; + ShaderResourceBindingD3D11Impl(FixedBlockMemoryAllocator &SRBAllocator, class PipelineStateD3D11Impl *pPSO, bool IsInternal); + ~ShaderResourceBindingD3D11Impl(); + + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; + + virtual void BindResources(Uint32 ShaderFlags, IResourceMapping *pResMapping, Uint32 Flags)override final; + + virtual IShaderVariable *GetVariable(SHADER_TYPE ShaderType, const char *Name)override final; + + ShaderResourceCacheD3D11 &GetResourceCache(Uint32 Ind){VERIFY_EXPR(Ind < m_NumActiveShaders); return m_pBoundResourceCaches[Ind];} + ShaderResourceLayoutD3D11 &GetResourceLayout(Uint32 Ind){VERIFY_EXPR(Ind < m_NumActiveShaders); return m_pResourceLayouts[Ind];} + + void BindStaticShaderResources(); + inline bool IsStaticResourcesBound(){return m_bIsStaticResourcesBound;} + + Uint32 GetNumActiveShaders() + { + return static_cast(m_NumActiveShaders); + } + + Int32 GetActiveShaderTypeIndex(Uint32 s){return m_ShaderTypeIndex[s];} + +private: + // The caches are indexed by the shader order in the PSO, not shader index + ShaderResourceCacheD3D11* m_pBoundResourceCaches = nullptr; + ShaderResourceLayoutD3D11* m_pResourceLayouts = nullptr; + + Int8 m_ShaderTypeIndex[6] = {}; + + // Resource layout index in m_ResourceLayouts[] array for every shader stage + Int8 m_ResourceLayoutIndex[6]; + Uint8 m_NumActiveShaders = 0; + + bool m_bIsStaticResourcesBound = false; +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h new file mode 100644 index 00000000..0964ba9c --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceCacheD3D11.h @@ -0,0 +1,316 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of Diligent::ShaderResourceCacheD3D11 class + +#include "TextureBaseD3D11.h" +#include "BufferD3D11Impl.h" +#include "SamplerD3D11Impl.h" + +namespace Diligent +{ + +/// The class implements a cache that holds resources bound to a specific shader stage +// All resources are stored in the continuous memory using the following layout: +// +// | CachedCB | ID3D11Buffer* || CachedResource | ID3D11ShaderResourceView* || CachedSampler | ID3D11SamplerState* || CachedResource | ID3D11UnorderedAccessView*|| +// |---------------------------------------------------||--------------------------|---------------------------||------------------------------|-----------------------------||-------------------------|---------------------------|| +// | 0 | 1 | ... | CBCount-1 | 0 | 1 | ...| CBCount-1 || 0 | 1 | ... | SRVCount-1 | 0 | 1 | ... | SRVCount-1 || 0 | 1 | ... | SamplerCount-1 | 0 | 1 | ...| SamplerCount-1 ||0 | 1 | ... | UAVCount-1 | 0 | 1 | ... | UAVCount-1 || +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// +// +class ShaderResourceCacheD3D11 +{ +public: + ShaderResourceCacheD3D11() + {} + + ~ShaderResourceCacheD3D11(); + + + ShaderResourceCacheD3D11(const ShaderResourceCacheD3D11&) = delete; + ShaderResourceCacheD3D11& operator = (const ShaderResourceCacheD3D11&) = delete; + ShaderResourceCacheD3D11(ShaderResourceCacheD3D11&&) = delete; + ShaderResourceCacheD3D11& operator = (ShaderResourceCacheD3D11&&) = delete; + + /// Describes resources associated with the cached constant buffer + struct CachedCB + { + /// Strong reference to the buffer + RefCntAutoPtr pBuff; + __forceinline void Set(RefCntAutoPtr &&_pBuff) + { + pBuff = std::move(_pBuff); + } + }; + + /// Describes resources associated with the cached sampler + struct CachedSampler + { + /// Strong reference to the sampler + RefCntAutoPtr pSampler; + __forceinline void Set(SamplerD3D11Impl *pSam) + { + pSampler = pSam; + } + }; + + /// Describes resources associated with the cached SRV or UAV + struct CachedResource + { + /// Wee keep strong reference to the view instead of the reference + /// to the texture or buffer because this is more efficient from + /// performance point of view: this avoids one pair of + /// AddStrongRef()/ReleaseStrongRef(). The view holds strong reference + /// to the texture or the buffer, so it makes no difference. + RefCntAutoPtr pView; + TextureBaseD3D11* pTexture; + BufferD3D11Impl* pBuffer; + // There is no need to keep strong reference to D3D11 resource as + // it is already kept by either pTexture or pBuffer + ID3D11Resource *pd3d11Resource; + CachedResource() : pTexture(nullptr), pBuffer(nullptr), pd3d11Resource(nullptr) + {} + + __forceinline void Set(RefCntAutoPtr&& pTexView) + { + pBuffer = nullptr; + // Avoid unnecessary virtual function calls + pTexture = pTexView ? ValidatedCast(pTexView->TextureViewD3D11Impl::GetTexture()) : nullptr; + pView.Attach(pTexView.Detach()); + pd3d11Resource = pTexture ? pTexture->TextureBaseD3D11::GetD3D11Texture() : nullptr; + } + + __forceinline void Set(RefCntAutoPtr&& pBufView) + { + pTexture = nullptr; + // Avoid unnecessary virtual function calls + pBuffer = pBufView ? ValidatedCast(pBufView->BufferViewD3D11Impl::GetBuffer()) : nullptr; + pView.Attach(pBufView.Detach()); + pd3d11Resource = pBuffer ? pBuffer->BufferD3D11Impl::GetD3D11Buffer() : nullptr; + } + }; + + void Initialize(Int32 CBCount, Int32 SRVCount, Int32 SamplerCount, Int32 UAVCount, class IMemoryAllocator &MemAllocator); + void Destroy(class IMemoryAllocator &MemAllocator); + + + __forceinline void SetCB(Uint32 Slot, RefCntAutoPtr &&pBuffD3D11Impl) + { + auto *pd3d11Buff = pBuffD3D11Impl ? pBuffD3D11Impl->BufferD3D11Impl::GetD3D11Buffer() : nullptr; + SetD3D11ResourceInternal(Slot, GetCBCount(), &ShaderResourceCacheD3D11::GetCBArrays, std::move(pBuffD3D11Impl), pd3d11Buff); + } + + __forceinline void SetTexSRV(Uint32 Slot, RefCntAutoPtr&& pTexView) + { + auto pd3d11SRV = pTexView ? static_cast(pTexView->TextureViewD3D11Impl::GetD3D11View()) : nullptr; + SetD3D11ResourceInternal(Slot, GetSRVCount(), &ShaderResourceCacheD3D11::GetSRVArrays, std::move(pTexView), pd3d11SRV); + } + + __forceinline void SetBufSRV(Uint32 Slot, RefCntAutoPtr &&pBuffView) + { + auto pd3d11SRV = pBuffView ? static_cast(pBuffView->BufferViewD3D11Impl::GetD3D11View()) : nullptr; + SetD3D11ResourceInternal(Slot, GetSRVCount(), &ShaderResourceCacheD3D11::GetSRVArrays, std::move(pBuffView), pd3d11SRV); + } + + __forceinline void SetTexUAV(Uint32 Slot, RefCntAutoPtr&& pTexView) + { + auto pd3d11UAV = pTexView ? static_cast(pTexView->TextureViewD3D11Impl::GetD3D11View()) : nullptr; + SetD3D11ResourceInternal(Slot, GetUAVCount(), &ShaderResourceCacheD3D11::GetUAVArrays, std::move(pTexView), pd3d11UAV); + } + + __forceinline void SetBufUAV(Uint32 Slot, RefCntAutoPtr &&pBuffView) + { + auto pd3d11UAV = pBuffView ? static_cast(pBuffView->BufferViewD3D11Impl::GetD3D11View()) : nullptr; + SetD3D11ResourceInternal(Slot, GetUAVCount(), &ShaderResourceCacheD3D11::GetUAVArrays, std::move(pBuffView), pd3d11UAV); + } + + __forceinline void SetSampler(Uint32 Slot, SamplerD3D11Impl *pSampler) + { + auto *pd3d11Sampler = pSampler ? pSampler->SamplerD3D11Impl::GetD3D11SamplerState() : nullptr; + SetD3D11ResourceInternal(Slot, GetSamplerCount(), &ShaderResourceCacheD3D11::GetSamplerArrays, pSampler, pd3d11Sampler); + } + + __forceinline bool IsCBBound(Uint32 Slot)const + { + CachedCB* CBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + const_cast(this)->GetCBArrays(CBs, d3d11CBs); + if( Slot < GetCBCount() && d3d11CBs[Slot] != nullptr ) + { + VERIFY(CBs[Slot].pBuff != nullptr, "No relevant buffer resource") + return true; + } + return false; + } + + __forceinline bool IsSRVBound(Uint32 Slot, bool dbgIsTextureView)const + { + CachedResource* SRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + const_cast(this)->GetSRVArrays(SRVResources, d3d11SRVs); + if( Slot < GetSRVCount() && d3d11SRVs[Slot] != nullptr ) + { + VERIFY( ( dbgIsTextureView && SRVResources[Slot].pTexture != nullptr) || + (!dbgIsTextureView && SRVResources[Slot].pBuffer != nullptr), "No relevant resource"); + return true; + } + return false; + } + + __forceinline bool IsUAVBound(Uint32 Slot, bool dbgIsTextureView)const + { + CachedResource* UAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + const_cast(this)->GetUAVArrays(UAVResources, d3d11UAVs); + if( Slot < GetUAVCount() && d3d11UAVs[Slot] != nullptr ) + { + VERIFY( ( dbgIsTextureView && UAVResources[Slot].pTexture != nullptr) || + (!dbgIsTextureView && UAVResources[Slot].pBuffer != nullptr), "No relevant resource"); + return true; + } + return false; + } + + __forceinline bool IsSamplerBound(Uint32 Slot)const + { + CachedSampler* Samplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + const_cast(this)->GetSamplerArrays(Samplers, d3d11Samplers); + if( Slot < GetSamplerCount() && d3d11Samplers[Slot] != nullptr ) + { + VERIFY(Samplers[Slot].pSampler != nullptr, "No relevant sampler") + return true; + } + return false; + } + + void dbgVerifyCacheConsistency(); + + + static __forceinline Uint32 PackResourceCounts(Uint32 CBCount, Uint32 SRVCount, Uint32 SamplerCount, Uint32 UAVCount) + { + VERIFY_EXPR(CBCount <= D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ); + VERIFY_EXPR(SRVCount <= D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT); + VERIFY_EXPR(SamplerCount <= D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT); + VERIFY_EXPR(UAVCount <= D3D11_PS_CS_UAV_REGISTER_COUNT); + return (CBCount & 0xFF) | ((SRVCount & 0xFF) << 8) | ((SamplerCount & 0xFF) << 16) | ((UAVCount & 0xFF) << 24); + } + + static __forceinline Uint32 UnpackCBCount (Uint32 PackedCounts) {return (PackedCounts >> 0) & 0xFF; } + static __forceinline Uint32 UnpackSRVCount (Uint32 PackedCounts) {return (PackedCounts >> 8) & 0xFF; } + static __forceinline Uint32 UnpackSamplerCount (Uint32 PackedCounts) {return (PackedCounts >> 16) & 0xFF; } + static __forceinline Uint32 UnpackUAVCount (Uint32 PackedCounts) {return (PackedCounts >> 24) & 0xFF; } + + __forceinline Uint32 GetCBCount() const{ return UnpackCBCount (m_ResourceCounts);} + __forceinline Uint32 GetSRVCount() const{ return UnpackSRVCount (m_ResourceCounts);} + __forceinline Uint32 GetSamplerCount()const{ return UnpackSamplerCount(m_ResourceCounts);} + __forceinline Uint32 GetUAVCount() const{ return UnpackUAVCount (m_ResourceCounts);} + __forceinline Uint32 GetPackedCounts()const{ return m_ResourceCounts;} + + __forceinline void GetResourceArrays(CachedCB* &CBs, ID3D11Buffer** &pd3d11CBs, + CachedResource* &SRVResources, ID3D11ShaderResourceView** &d3d11SRVs, + CachedSampler* &Samplers, ID3D11SamplerState** &pd3d11Samplers, + CachedResource* &UAVResources, ID3D11UnorderedAccessView** &pd3d11UAVs) + { + VERIFY_EXPR(IsInitialized()); + CBs = reinterpret_cast( m_pResourceData ); + pd3d11CBs = reinterpret_cast( CBs + GetCBCount() ); + SRVResources = reinterpret_cast( pd3d11CBs + GetCBCount() ); + d3d11SRVs = reinterpret_cast( SRVResources + GetSRVCount() ); + Samplers = reinterpret_cast( d3d11SRVs + GetSRVCount() ); + pd3d11Samplers = reinterpret_cast( Samplers + GetSamplerCount() ); + UAVResources = reinterpret_cast( pd3d11Samplers + GetSamplerCount() ); + pd3d11UAVs = reinterpret_cast( UAVResources + GetUAVCount() ); + } + + __forceinline void GetCBArrays(CachedCB* &CBs, ID3D11Buffer** &pd3d11CBs) + { + CBs = reinterpret_cast( m_pResourceData ); + pd3d11CBs = reinterpret_cast( CBs + GetCBCount() ); + } + + __forceinline void GetSRVArrays(CachedResource* &SRVResources, ID3D11ShaderResourceView** &d3d11SRVs) + { + SRVResources = reinterpret_cast( m_pResourceData + (sizeof(CachedCB) + sizeof(ID3D11Buffer*)) * GetCBCount() ); + d3d11SRVs = reinterpret_cast( SRVResources + GetSRVCount() ); + } + + __forceinline void GetSamplerArrays(CachedSampler* &Samplers, ID3D11SamplerState** &pd3d11Samplers) + { + Samplers = reinterpret_cast( m_pResourceData + + (sizeof(CachedCB) + sizeof(ID3D11Buffer*)) * GetCBCount() + + (sizeof(CachedResource) + sizeof(ID3D11ShaderResourceView*)) * GetSRVCount() ); + pd3d11Samplers = reinterpret_cast( Samplers + GetSamplerCount() ); + } + + __forceinline void GetUAVArrays(CachedResource* &UAVResources, ID3D11UnorderedAccessView** &pd3d11UAVs) + { + UAVResources = reinterpret_cast( m_pResourceData + + (sizeof(CachedCB) + sizeof(ID3D11Buffer*)) * GetCBCount() + + (sizeof(CachedResource) + sizeof(ID3D11ShaderResourceView*)) * GetSRVCount() + + (sizeof(CachedSampler) + sizeof(ID3D11SamplerState*)) * GetSamplerCount() ); + pd3d11UAVs = reinterpret_cast( UAVResources + GetUAVCount() ); + } + + __forceinline bool IsInitialized()const{return m_ResourceCounts != InvalidResourceCounts;} + +private: + + template + __forceinline void SetD3D11ResourceInternal(Uint32 Slot, Uint32 Size, + TGetResourceArraysFunc GetArrays, + TSrcResourceType &&pResource, + TD3D11ResourceType *pd3d11Resource) + { + VERIFY(Slot < Size, "Resource cache is not big enough" ) + VERIFY(pResource != nullptr && pd3d11Resource != nullptr || pResource == nullptr && pd3d11Resource == nullptr, + "Resource and D3D11 resource must be set/unset atomically") + TCachedResourceType* Resources; + TD3D11ResourceType** d3d11ResArr; + (this->*GetArrays)(Resources, d3d11ResArr); + Resources[Slot].Set(std::forward(pResource)); + d3d11ResArr[Slot] = pd3d11Resource; + } + + static const Uint32 InvalidResourceCounts = 0xFFFFFFFF; + // Resource limits in D3D11: + // Max CB count: 14 + // Max SRV count: 128 + // Max Sampler count: 16 + // Max UAV count: 8 + Uint32 m_ResourceCounts = InvalidResourceCounts; // CBCount == (m_ResourceCounts >> 0) & 0xFF + // SRVCount == (m_ResourceCounts >> 8) & 0xFF + // SamplerCount == (m_ResourceCounts >> 16) & 0xFF + // UAVCount == (m_ResourceCounts >> 24) & 0xFF + Uint8 *m_pResourceData = nullptr; + +#ifdef _DEBUG + IMemoryAllocator *m_pdbgMemoryAllocator = nullptr; +#endif +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h new file mode 100644 index 00000000..f55b4dce --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourceLayoutD3D11.h @@ -0,0 +1,300 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of Diligent::ShaderResourceLayoutD3D11 class + +// Set this define to 1 to use unordered_map to store shader variables. +// Note that sizeof(m_VariableHash)==128 (release mode, MS compiler, x64). +#define USE_VARIABLE_HASH_MAP 0 + + +#include "ShaderResources.h" +#include "ShaderBase.h" +#include "ShaderResourceCacheD3D11.h" +#include "EngineD3D11Defines.h" +#include "STDAllocator.h" +#include "ShaderVariableD3DBase.h" +#include "ShaderResourcesD3D11.h" + +namespace Diligent +{ + +class IMemoryAllocator; + +/// Diligent::ShaderResourceLayoutD3D11 class +class ShaderResourceLayoutD3D11 +{ +public: + ShaderResourceLayoutD3D11(IObject &Owner, IMemoryAllocator& ResLayoutDataAllocator); + ~ShaderResourceLayoutD3D11(); + + ShaderResourceLayoutD3D11(const ShaderResourceLayoutD3D11&) = delete; + ShaderResourceLayoutD3D11& operator = (const ShaderResourceLayoutD3D11&) = delete; + ShaderResourceLayoutD3D11(ShaderResourceLayoutD3D11&&) = default; + ShaderResourceLayoutD3D11& operator = (ShaderResourceLayoutD3D11&&) = delete; + + void Initialize(const std::shared_ptr& pSrcResources, + const SHADER_VARIABLE_TYPE *VarTypes, + Uint32 NumVarTypes, + ShaderResourceCacheD3D11& ResourceCache, + IMemoryAllocator& ResCacheDataAllocator, + IMemoryAllocator& ResLayoutDataAllocator); + + void CopyResources(ShaderResourceCacheD3D11 &DstCache); + + using ShaderVariableD3D11Base = ShaderVariableD3DBase; + + struct ConstBuffBindInfo : ShaderVariableD3D11Base + { + ConstBuffBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, + ShaderResourceLayoutD3D11 &ParentResLayout ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + {} + // Non-virtual function + __forceinline void BindResource(IDeviceObject *pObject, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout); + virtual void Set(IDeviceObject *pObject)override final{ BindResource(pObject, 0, nullptr); } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + for(Uint32 elem=0; elem < NumElements; ++elem) + BindResource(ppObjects[elem], FirstElement+elem, nullptr); + } + + __forceinline bool IsBound(Uint32 ArrayIndex); + }; + + struct TexAndSamplerBindInfo : ShaderVariableD3D11Base + { + TexAndSamplerBindInfo( const D3DShaderResourceAttribs& _TextureAttribs, + const D3DShaderResourceAttribs& _SamplerAttribs, + ShaderResourceLayoutD3D11 &ParentResLayout) : + ShaderVariableD3D11Base(ParentResLayout, _TextureAttribs), + SamplerAttribs(_SamplerAttribs) + {} + + // Non-virtual function + __forceinline void BindResource(IDeviceObject *pObject, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout); + virtual void Set(IDeviceObject *pObject)override final{ BindResource(pObject, 0, nullptr); } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + for(Uint32 elem=0; elem < NumElements; ++elem) + BindResource(ppObjects[elem], FirstElement+elem, nullptr); + } + + __forceinline bool IsBound(Uint32 ArrayIndex); + + static const D3DShaderResourceAttribs InvalidSamplerAttribs; + + const D3DShaderResourceAttribs &SamplerAttribs; + }; + + struct TexUAVBindInfo : ShaderVariableD3D11Base + { + TexUAVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, + ShaderResourceLayoutD3D11 &ParentResLayout ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + {} + + // Provide non-virtual function + __forceinline void BindResource(IDeviceObject *pObject, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout); + virtual void Set(IDeviceObject *pObject)override final{ BindResource(pObject, 0, nullptr); } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + for(Uint32 elem=0; elem < NumElements; ++elem) + BindResource(ppObjects[elem], FirstElement+elem, nullptr); + } + + __forceinline bool IsBound(Uint32 ArrayIndex); + }; + + struct BuffUAVBindInfo : ShaderVariableD3D11Base + { + BuffUAVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, + ShaderResourceLayoutD3D11 &ParentResLayout ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + {} + + // Non-virtual function + __forceinline void BindResource(IDeviceObject *pObject, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout); + virtual void Set(IDeviceObject *pObject)override final{ BindResource(pObject, 0, nullptr); } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + for(Uint32 elem=0; elem < NumElements; ++elem) + BindResource(ppObjects[elem], FirstElement+elem, nullptr); + } + + __forceinline bool IsBound(Uint32 ArrayIndex); + }; + + struct BuffSRVBindInfo : ShaderVariableD3D11Base + { + BuffSRVBindInfo( const D3DShaderResourceAttribs& ResourceAttribs, + ShaderResourceLayoutD3D11 &ParentResLayout ) : + ShaderVariableD3D11Base(ParentResLayout, ResourceAttribs) + {} + + // Non-virtual function + __forceinline void BindResource(IDeviceObject *pObject, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout); + virtual void Set(IDeviceObject *pObject)override final{ BindResource(pObject, 0, nullptr); } + + virtual void SetArray(IDeviceObject* const* ppObjects, Uint32 FirstElement, Uint32 NumElements)override final + { + for(Uint32 elem=0; elem < NumElements; ++elem) + BindResource(ppObjects[elem], FirstElement+elem, nullptr); + } + + __forceinline bool IsBound(Uint32 ArrayIndex); + }; + + // dbgResourceCache is only used for sanity check and as a remainder that the resource cache must be alive + // while Layout is alive + void BindResources( IResourceMapping* pResourceMapping, Uint32 Flags, const ShaderResourceCacheD3D11 &dbgResourceCache ); + +#ifdef VERIFY_SHADER_BINDINGS + void dbgVerifyBindings()const; +#endif + + IShaderVariable* GetShaderVariable( const Char* Name ); + __forceinline SHADER_TYPE GetShaderType()const{return m_pResources->GetShaderType();} + + IObject& GetOwner(){return m_Owner;} +private: + + void InitVariablesHashMap(); + + const Char* GetShaderName()const; + + // No need to use shared pointer, as the resource cache is either part of the same + // ShaderD3D11Impl object, or ShaderResourceBindingD3D11Impl object + ShaderResourceCacheD3D11 *m_pResourceCache = nullptr; + + std::unique_ptr > m_ResourceBuffer; + + // Offsets in bytes + Uint16 m_TexAndSamplersOffset = 0; + Uint16 m_TexUAVsOffset = 0; + Uint16 m_BuffUAVsOffset = 0; + Uint16 m_BuffSRVsOffset = 0; + + Uint8 m_NumCBs = 0; // Max == 14 + Uint8 m_NumTexSRVs = 0; // Max == 128 + Uint8 m_NumTexUAVs = 0; // Max == 8 + Uint8 m_NumBufUAVs = 0; // Max == 8 + Uint8 m_NumBufSRVs = 0; // Max == 128 + + ConstBuffBindInfo& GetCB(Uint32 cb) + { + VERIFY_EXPR(cb(m_ResourceBuffer.get())[cb]; + } + const ConstBuffBindInfo& GetCB(Uint32 cb)const + { + VERIFY_EXPR(cb(m_ResourceBuffer.get())[cb]; + } + + TexAndSamplerBindInfo& GetTexSRV(Uint32 t) + { + VERIFY_EXPR(t( reinterpret_cast(m_ResourceBuffer.get()) + m_TexAndSamplersOffset )[t]; + } + const TexAndSamplerBindInfo& GetTexSRV(Uint32 t)const + { + VERIFY_EXPR(t( reinterpret_cast(m_ResourceBuffer.get()) + m_TexAndSamplersOffset )[t]; + } + + TexUAVBindInfo& GetTexUAV(Uint32 u) + { + VERIFY_EXPR(u < m_NumTexUAVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_TexUAVsOffset)[u]; + } + const TexUAVBindInfo& GetTexUAV(Uint32 u)const + { + VERIFY_EXPR(u < m_NumTexUAVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_TexUAVsOffset)[u]; + } + + BuffUAVBindInfo& GetBufUAV(Uint32 u) + { + VERIFY_EXPR(u < m_NumBufUAVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_BuffUAVsOffset)[u]; + } + const BuffUAVBindInfo& GetBufUAV(Uint32 u)const + { + VERIFY_EXPR(u < m_NumBufUAVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_BuffUAVsOffset)[u]; + } + + BuffSRVBindInfo& GetBufSRV(Uint32 s) + { + VERIFY_EXPR(s < m_NumBufSRVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_BuffSRVsOffset)[s]; + } + const BuffSRVBindInfo& GetBufSRV(Uint32 s)const + { + VERIFY_EXPR(s < m_NumBufSRVs); + return reinterpret_cast( reinterpret_cast(m_ResourceBuffer.get()) + m_BuffSRVsOffset)[s]; + } + + template + void HandleResources(THandleCB HandleCB, + THandleTexSRV HandleTexSRV, + THandleTexUAV HandleTexUAV, + THandleBufSRV HandleBufSRV, + THandleBufUAV HandleBufUAV) + { + for (Uint32 cb = 0; cb < m_NumCBs; ++cb) + HandleCB(GetCB(cb)); + for (Uint32 t = 0; t < m_NumTexSRVs; ++t) + HandleTexSRV(GetTexSRV(t)); + for (Uint32 u = 0; u < m_NumTexUAVs; ++u) + HandleTexUAV(GetTexUAV(u)); + for (Uint32 s = 0; s < m_NumBufSRVs; ++s) + HandleBufSRV(GetBufSRV(s)); + for (Uint32 u = 0; u < m_NumBufUAVs; ++u) + HandleBufUAV(GetBufUAV(u)); + } + +#if USE_VARIABLE_HASH_MAP + // Hash map to look up shader variables by name. + // Note that sizeof(m_VariableHash)==128 (release mode, MS compiler, x64). + typedef std::pair VariableHashData; + std::unordered_map, std::equal_to, STDAllocatorRawMem > m_VariableHash; +#endif + + std::shared_ptr m_pResources; + IObject &m_Owner; +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h new file mode 100644 index 00000000..772de5b9 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/include/ShaderResourcesD3D11.h @@ -0,0 +1,139 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Declaration of Diligent::ShaderResourcesD3D11 class + + +// ShaderResourcesD3D11 are created by ShaderD3D11Impl instances. They are then referenced by ShaderResourceLayoutD3D11 objects, which are in turn +// created by instances of ShaderResourceBindingsD3D11Impl (and ShaderD3D11Impl too) +// +// _________________ +// | | +// | ShaderD3D11Impl | +// |_________________| +// | +// |shared_ptr +// ________V_____________ _____________________________________________________________________ +// | | unique_ptr | | | | | | | +// | ShaderResourcesD3D11 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | +// |______________________| |________|___________|___________|___________|___________|____________| +// A A A A A A A +// | \ \ \ \ \ | +// |shared_ptr Ref Ref Ref Ref Ref | +// ________|__________________ ____\_________\__________\__________\___________\_______ | +// | | unique_ptr | | | | | | | +// | ShaderResourceLayoutD3D11 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | | +// |___________________________| |________|___________|___________|___________|___________| | +// | Ref +// |______________________________________________| +// +// +// One ShaderResources instance can be referenced by multiple objects +// +// +// _______ ________________________________ +// | | | | +// ----| ShaderResourceLayoutD3D11 |<-----| ShaderResourceBindingD3D11Impl | +// | |___________________________| |________________________________| +// | +// | +// _________________ ______________________ | _______ ________________________________ +// | | shared_ptr | | shared_ptr| | | | | +// | ShaderD3D11Impl |--------------->| ShaderResourcesD3D11 |<---------------| ShaderResourceLayoutD3D11 |<-----| ShaderResourceBindingD3D11Impl | +// |_________________| |______________________| | |___________________________| |________________________________| +// | A | +// V | | +// ________ | | _______ ________________________________ +// | | shared_ptr | | | | | | +// | ShaderResourceLayoutD3D11 |------------------- ----| ShaderResourceLayoutD3D11 |<-----| ShaderResourceBindingD3D11Impl | +// |___________________________| |___________________________| |________________________________| +// +// + + +#include "ShaderResources.h" + +namespace Diligent +{ + +/// Diligent::ShaderResources class +class ShaderResourcesD3D11 : public ShaderResources +{ +public: + // Loads shader resources from the compiled shader bytecode + ShaderResourcesD3D11(class RenderDeviceD3D11Impl *pDeviceD3D11Impl, ID3DBlob *pShaderBytecode, const ShaderDesc &ShdrDesc); + ~ShaderResourcesD3D11(); + + __forceinline Int32 GetMaxCBBindPoint() const{return m_MaxCBBindPoint; } + __forceinline Int32 GetMaxSRVBindPoint() const{return m_MaxSRVBindPoint; } + __forceinline Int32 GetMaxSamplerBindPoint()const{return m_MaxSamplerBindPoint; } + __forceinline Int32 GetMaxUAVBindPoint() const{return m_MaxUAVBindPoint; } + +#ifdef VERIFY_SHADER_BINDINGS + void dbgVerifyCommittedResources(ID3D11Buffer* CommittedD3D11CBs[], + ID3D11ShaderResourceView* CommittedD3D11SRVs[], + ID3D11Resource* CommittedD3D11SRVResources[], + ID3D11SamplerState* CommittedD3D11Samplers[], + ID3D11UnorderedAccessView* CommittedD3D11UAVs[], + ID3D11Resource* CommittedD3D11UAVResources[], + class ShaderResourceCacheD3D11 &ResourceCache)const; +#endif + + const Char *GetShaderName()const{return m_ShaderName;} + + void InitStaticSamplers(class ShaderResourceCacheD3D11 &ResourceCache)const; + +private: + typedef Int8 MaxBindPointType; + + MaxBindPointType m_MaxCBBindPoint = -1; // Max == 13 + MaxBindPointType m_MaxSRVBindPoint = -1; // Max == 127 + MaxBindPointType m_MaxSamplerBindPoint = -1; // Max == 15 + MaxBindPointType m_MaxUAVBindPoint = -1; // Max == 7 + Uint8 m_NumStaticSamplers = 0; // Max == 16 + + static const UINT MaxAllowedBindPoint = std::numeric_limits::max(); + static_assert(D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max CB slot" ); + static_assert(D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max SRV slot"); + static_assert(D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max Sampler slot"); + static_assert(D3D11_PS_CS_UAV_REGISTER_COUNT-1 <= MaxAllowedBindPoint, "Not enough bits to represent max UAV slot"); + + // ShaderResourcesD3D11 is part of the ShaderD3D11Impl object, so we can simply + // reference shader name without the need to copy it + const Char* m_ShaderName; + + typedef std::pair > StaticSamplerAttribs; + StaticSamplerAttribs& GetStaticSampler(Uint32 n) + { + VERIFY_EXPR(n < m_NumStaticSamplers); + return reinterpret_cast< StaticSamplerAttribs* >(m_StaticSamplers.get())[n]; + } + + // We have to use void, because we will be calling destructors manually + std::unique_ptr< void, STDDeleterRawMem > m_StaticSamplers; +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h index 32cef19f..d7a15c7d 100644 --- a/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/SwapChainD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,21 +32,23 @@ namespace Diligent { +class IMemoryAllocator; /// Implementation of the Diligent::ISwapChainD3D11 interface -class SwapChainD3D11Impl : public SwapChainBase +class SwapChainD3D11Impl : public SwapChainBase { public: - typedef SwapChainBase TSwapChainBase; - SwapChainD3D11Impl(const SwapChainDesc& SwapChainDesc, - class RenderDeviceD3D11Impl* pRenderDeviceD3D11, - class DeviceContextD3D11Impl* pDeviceContextD3D11, - void* pNativeWndHandle); + typedef SwapChainBase TSwapChainBase; + SwapChainD3D11Impl(IMemoryAllocator &Allocator, + const SwapChainDesc& SwapChainDesc, + class RenderDeviceD3D11Impl* pRenderDeviceD3D11, + class DeviceContextD3D11Impl* pDeviceContextD3D11, + void* pNativeWndHandle); ~SwapChainD3D11Impl(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual void Present(); - virtual void Resize( Uint32 NewWidth, Uint32 NewHeight ); + virtual void Present()override final; + virtual void Resize( Uint32 NewWidth, Uint32 NewHeight )override final; virtual IDXGISwapChain *GetDXGISwapChain(){ return m_pSwapChain; } @@ -56,11 +58,11 @@ public: private: void CreateRTVandDSV(); /// D3D11 swap chain - Diligent::CComPtr m_pSwapChain; + CComPtr m_pSwapChain; /// Back buffer render target view - Diligent::CComPtr m_pRenderTargetView; + CComPtr m_pRenderTargetView; /// Back buffer depth-stencil view - Diligent::CComPtr m_pDepthStencilView; + CComPtr m_pDepthStencilView; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/Texture1D_D3D11.h b/Graphics/GraphicsEngineD3D11/include/Texture1D_D3D11.h index e1cdcb2f..3e53aad5 100644 --- a/Graphics/GraphicsEngineD3D11/include/Texture1D_D3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/Texture1D_D3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,17 +31,22 @@ namespace Diligent { +/// Implementation of a 1D texture class Texture1D_D3D11 : public TextureBaseD3D11 { public: - Texture1D_D3D11(class RenderDeviceD3D11Impl *pDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData = TextureData()); + Texture1D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + class RenderDeviceD3D11Impl *pDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData = TextureData()); ~Texture1D_D3D11(); protected: - virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ); - virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV ); - virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV ); - virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV ); + virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV )override final; + virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV )override final; + virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV )override final; + virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV )override final; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/Texture2D_D3D11.h b/Graphics/GraphicsEngineD3D11/include/Texture2D_D3D11.h index e098bce1..ed958499 100644 --- a/Graphics/GraphicsEngineD3D11/include/Texture2D_D3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/Texture2D_D3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,17 +31,22 @@ namespace Diligent { +/// Implementation of a 2D texture class Texture2D_D3D11 : public TextureBaseD3D11 { public: - Texture2D_D3D11(class RenderDeviceD3D11Impl *pDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData = TextureData()); + Texture2D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + class RenderDeviceD3D11Impl *pDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData = TextureData()); ~Texture2D_D3D11(); protected: - virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ); - virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV ); - virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV ); - virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV ); + virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV )override final; + virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV )override final; + virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV )override final; + virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV )override final; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/Texture3D_D3D11.h b/Graphics/GraphicsEngineD3D11/include/Texture3D_D3D11.h index d5e11c8a..44e4ced9 100644 --- a/Graphics/GraphicsEngineD3D11/include/Texture3D_D3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/Texture3D_D3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,17 +31,22 @@ namespace Diligent { +/// Implementation of a 3D texture class Texture3D_D3D11 : public TextureBaseD3D11 { public: - Texture3D_D3D11(class RenderDeviceD3D11Impl *pDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData = TextureData()); + Texture3D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + class RenderDeviceD3D11Impl *pDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData = TextureData()); ~Texture3D_D3D11(); protected: - virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ); - virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV ); - virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV ); - virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV ); + virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV )override final; + virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV )override final; + virtual void CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilView **ppD3D11DSV )override final; + virtual void CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV )override final; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h b/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h index e787f238..66da6f6e 100644 --- a/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h +++ b/Graphics/GraphicsEngineD3D11/include/TextureBaseD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,24 +34,40 @@ namespace Diligent { +class FixedBlockMemoryAllocator; + +enum class D3D11TextureState +{ + Undefined = 0x0, + ShaderResource = 0x1, + RenderTarget = 0x2, + DepthStencil = 0x4, + UnorderedAccess = 0x8, + Output = RenderTarget | DepthStencil | UnorderedAccess +}; + /// Base implementation of the Diligent::ITextureD3D11 interface -class TextureBaseD3D11 : public TextureBase +class TextureBaseD3D11 : public TextureBase { public: - typedef TextureBase TTextureBase; + typedef TextureBase TTextureBase; - TextureBaseD3D11(class RenderDeviceD3D11Impl *pDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData = TextureData()); + TextureBaseD3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + class RenderDeviceD3D11Impl *pDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData = TextureData()); ~TextureBaseD3D11(); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual void UpdateData( IDeviceContext *pContext, Uint32 MipLevel, Uint32 Slice, const Box &DstBox, const TextureSubResData &SubresData )override; + virtual void UpdateData( IDeviceContext *pContext, Uint32 MipLevel, Uint32 Slice, const Box &DstBox, const TextureSubResData &SubresData )override final; //virtual void CopyData(CTexture *pSrcTexture, Uint32 SrcOffset, Uint32 DstOffset, Uint32 Size); - virtual void Map( IDeviceContext *pContext, MAP_TYPE MapType, Uint32 MapFlags, PVoid &pMappedData )override; - virtual void Unmap( IDeviceContext *pContext )override; + virtual void Map( IDeviceContext *pContext, MAP_TYPE MapType, Uint32 MapFlags, PVoid &pMappedData )override final; + virtual void Unmap( IDeviceContext *pContext, MAP_TYPE MapType )override final; - virtual ID3D11Resource* GetD3D11Texture(){ return m_pd3d11Texture; } + virtual ID3D11Resource* GetD3D11Texture()override final{ return m_pd3d11Texture; } void CopyData(IDeviceContext *pContext, ITexture *pSrcTexture, @@ -64,9 +80,15 @@ public: Uint32 DstY, Uint32 DstZ); + void ResetState(D3D11TextureState State){m_State = static_cast(State);} + void AddState(D3D11TextureState State){m_State |= static_cast(State);} + void ClearState(D3D11TextureState State){m_State &= ~static_cast(State);} + bool CheckState(D3D11TextureState State){return (m_State & static_cast(State)) ? true : false;} + protected: - void CreateViewInternal( const struct TextureViewDesc &ViewDesc, ITextureView **ppView, bool bIsDefaultView )override; - void PrepareD3D11InitData(const TextureData &InitData, Uint32 NumSubresources, std::vector &D3D11InitData); + void CreateViewInternal( const struct TextureViewDesc &ViewDesc, ITextureView **ppView, bool bIsDefaultView )override final; + void PrepareD3D11InitData(const TextureData &InitData, Uint32 NumSubresources, + std::vector > &D3D11InitData); virtual void CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ) = 0; virtual void CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetView **ppD3D11RTV ) = 0; @@ -75,7 +97,9 @@ protected: friend class RenderDeviceD3D11Impl; /// D3D11 texture - Diligent::CComPtr m_pd3d11Texture; + CComPtr m_pd3d11Texture; + + Uint32 m_State = static_cast(D3D11TextureState::Undefined); }; } diff --git a/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h index 6e138b41..7a35d7e3 100644 --- a/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h +++ b/Graphics/GraphicsEngineD3D11/include/TextureViewD3D11Impl.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,27 +33,33 @@ namespace Diligent { +class FixedBlockMemoryAllocator; + /// Implementation of the Diligent::ITextureViewD3D11 interface -class TextureViewD3D11Impl : public TextureViewBase +class TextureViewD3D11Impl : public TextureViewBase { public: - typedef TextureViewBase TTextureViewBase; + typedef TextureViewBase TTextureViewBase; - TextureViewD3D11Impl( IRenderDevice *pDevice, + TextureViewD3D11Impl( FixedBlockMemoryAllocator &TexViewAllocator, + IRenderDevice *pDevice, const TextureViewDesc& ViewDesc, class ITexture *pTexture, ID3D11View* pD3D11View, bool bIsDefaultView); - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override; + virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface )override final; - virtual ID3D11View* GetD3D11View()override; + virtual ID3D11View* GetD3D11View()override final + { + return m_pD3D11View; + } - void GenerateMips( IDeviceContext *pContext )override; + void GenerateMips( IDeviceContext *pContext )override final; protected: /// D3D11 view - Diligent::CComPtr m_pD3D11View; + CComPtr m_pD3D11View; }; } diff --git a/Graphics/GraphicsEngineD3D11/include/VertexDescD3D11Impl.h b/Graphics/GraphicsEngineD3D11/include/VertexDescD3D11Impl.h deleted file mode 100644 index 84b9ea78..00000000 --- a/Graphics/GraphicsEngineD3D11/include/VertexDescD3D11Impl.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Declaration of Diligent::VertexDescD3D11Impl class - -#include "VertexDescriptionD3D11.h" -#include "RenderDeviceD3D11.h" -#include "VertexDescriptionBase.h" - -namespace Diligent -{ - -/// Implementation of the Diligent::IVertexDescriptionD3D11 interface -class VertexDescD3D11Impl : public VertexDescriptionBase -{ -public: - typedef VertexDescriptionBase TVertexDescriptionBase; - - VertexDescD3D11Impl( class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const LayoutDesc &LayoutDesc, IShader *pVertexShader ); - ~VertexDescD3D11Impl(); - - virtual void QueryInterface( const Diligent::INTERFACE_ID &IID, IObject **ppInterface ); - - virtual ID3D11InputLayout* GetD3D11InputLayout(){ return m_pd3d11InputLayout; } - -private: - friend class DeviceContextD3D11Impl; - /// D3D11 input layout - Diligent::CComPtr m_pd3d11InputLayout; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/include/pch.h b/Graphics/GraphicsEngineD3D11/include/pch.h index d948fd48..e55827a0 100644 --- a/Graphics/GraphicsEngineD3D11/include/pch.h +++ b/Graphics/GraphicsEngineD3D11/include/pch.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,13 +38,13 @@ #include #include #include -#if defined(PLATFORM_WINDOWS) +#if defined(PLATFORM_WIN32) #include -#elif defined(PLATFORM_WINDOWS_STORE) +#elif defined(PLATFORM_UNIVERSAL_WINDOWS) #include #endif -#include "PlatformDefinitions.h" +#include "EngineD3D11Defines.h" #include "Errors.h" #include "RefCntAutoPtr.h" #include "DebugUtilities.h" @@ -52,4 +52,4 @@ #include "RenderDeviceBase.h" #include "D3D11TypeConversions.h" #include "ValidatedCast.h" -#include "ComPtr.h" \ No newline at end of file +#include \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/include/targetver.h b/Graphics/GraphicsEngineD3D11/include/targetver.h index e76fe941..5a309b33 100644 --- a/Graphics/GraphicsEngineD3D11/include/targetver.h +++ b/Graphics/GraphicsEngineD3D11/include/targetver.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/BlendStateD3D11.h b/Graphics/GraphicsEngineD3D11/interface/BlendStateD3D11.h deleted file mode 100644 index 8fe1c302..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/BlendStateD3D11.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Diligent::IBlendStateD3D11 interface - -#include "BlendState.h" - -namespace Diligent -{ - -// {18FEA836-1DD6-4100-9C83-CEF71F8EC8F1} -static const Diligent::INTERFACE_ID IID_BlendStateD3D11 = -{ 0x18fea836, 0x1dd6, 0x4100, { 0x9c, 0x83, 0xce, 0xf7, 0x1f, 0x8e, 0xc8, 0xf1 } }; - -/// Interface to the blend state object implemented in D3D11 -class IBlendStateD3D11 : public Diligent::IBlendState -{ -public: - - /// Returns a pointer to the ID3D11BlendState interface of the internal Direct3D11 object. - - /// The method does *NOT* call AddRef() on the returned interface, - /// so Release() must not be called. - virtual ID3D11BlendState *GetD3D11BlendState() = 0; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/interface/BufferD3D11.h b/Graphics/GraphicsEngineD3D11/interface/BufferD3D11.h index 46195298..cdd1c72b 100644 --- a/Graphics/GraphicsEngineD3D11/interface/BufferD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/BufferD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/BufferViewD3D11.h b/Graphics/GraphicsEngineD3D11/interface/BufferViewD3D11.h index 32a75461..3b9d3d5c 100644 --- a/Graphics/GraphicsEngineD3D11/interface/BufferViewD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/BufferViewD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/DepthStencilStateD3D11.h b/Graphics/GraphicsEngineD3D11/interface/DepthStencilStateD3D11.h deleted file mode 100644 index 7e8bd567..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/DepthStencilStateD3D11.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Diligent::IDepthStencilStateD3D11 interface - -#include "DepthStencilState.h" - -namespace Diligent -{ - -// {77EA665B-4D63-4D5F-AD8F-791FE79FC305} -static const Diligent::INTERFACE_ID IID_DepthStencilStateD3D11 = -{ 0x77ea665b, 0x4d63, 0x4d5f, { 0xad, 0x8f, 0x79, 0x1f, 0xe7, 0x9f, 0xc3, 0x5 } }; - -/// Interface to the depth stencil state object implemented in D3D11 -class IDepthStencilStateD3D11 : public Diligent::IDepthStencilState -{ -public: - - /// Returns a pointer to the ID3D11DepthStencilState interface of the internal Direct3D11 object. - - /// The method does *NOT* call AddRef() on the returned interface, - /// so Release() must not be called. - virtual ID3D11DepthStencilState *GetD3D11DepthStencilState() = 0; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/interface/DeviceContextD3D11.h b/Graphics/GraphicsEngineD3D11/interface/DeviceContextD3D11.h index 972249b4..e5d1cb54 100644 --- a/Graphics/GraphicsEngineD3D11/interface/DeviceContextD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/DeviceContextD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h b/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h new file mode 100644 index 00000000..88fcaf66 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/interface/EngineD3D11Attribs.h @@ -0,0 +1,65 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Definition of the Engine D3D11 attribs + +#include "BasicTypes.h" + +namespace Diligent +{ + /// Debug flags that can be specified when creating Direct3D11-based engine implementation. + /// + /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 + enum class EngineD3D11DebugFlags : Uint32 + { + /// Before executing draw/dispatch command, verify that + /// all required shader resources are bound to the device context + VerifyCommittedShaderResources = 0x01, + + /// Verify that all committed cotext resources are relevant, + /// i.e. they are consistent with the committed resource cache. + /// This is very expensive operation and should generally not be + /// necessary. + VerifyCommittedResourceRelevance = 0x02 + }; + + /// Attributes of the Direct3D11-based engine implementation + struct EngineD3D11Attribs : public EngineCreationAttribs + { + /// Debug flags. See Diligent::EngineD3D11DebugFlags for a list of allowed values. + /// + /// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11 + Uint32 DebugFlags; + + EngineD3D11Attribs() : + DebugFlags(0) + { + #ifdef _DEBUG + DebugFlags = static_cast(EngineD3D11DebugFlags::VerifyCommittedShaderResources); + #endif + } + }; +} diff --git a/Graphics/GraphicsEngineD3D11/interface/PipelineStateD3D11.h b/Graphics/GraphicsEngineD3D11/interface/PipelineStateD3D11.h new file mode 100644 index 00000000..8eab72e4 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/interface/PipelineStateD3D11.h @@ -0,0 +1,107 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Definition of the Diligent::IPipeplineStateD3D11 interface + +#include "PipelineState.h" + +namespace Diligent +{ + +// {3EA6E3F4-9966-47FC-8CE8-0EB3E2273061} +static const INTERFACE_ID IID_PipelineStateD3D11 = +{ 0x3ea6e3f4, 0x9966, 0x47fc, { 0x8c, 0xe8, 0xe, 0xb3, 0xe2, 0x27, 0x30, 0x61 } }; + +/// Interface to the blend state object implemented in D3D11 +class IPipelineStateD3D11 : public IPipelineState +{ +public: + + /// Returns a pointer to the ID3D11BlendState interface of the internal Direct3D11 object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11BlendState* GetD3D11BlendState() = 0; + + + /// Returns a pointer to the ID3D11RasterizerState interface of the internal Direct3D11 object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11RasterizerState* GetD3D11RasterizerState() = 0; + + + /// Returns a pointer to the ID3D11DepthStencilState interface of the internal Direct3D11 object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11DepthStencilState* GetD3D11DepthStencilState() = 0; + + /// Returns a pointer to the ID3D11InputLayout interface of the internal Direct3D11 object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11InputLayout* GetD3D11InputLayout() = 0; + + /// Returns a pointer to the ID3D11VertexShader interface of the internal vertex shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11VertexShader* GetD3D11VertexShader() = 0; + + /// Returns a pointer to the interface of the internal pixel shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11PixelShader* GetD3D11PixelShader() = 0; + + + /// Returns a pointer to the ID3D11GeometryShader interface of the internal geometry shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11GeometryShader* GetD3D11GeometryShader() = 0; + + /// Returns a pointer to the ID3D11DomainShader interface of the internal domain shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11DomainShader* GetD3D11DomainShader() = 0; + + /// Returns a pointer to the ID3D11HullShader interface of the internal hull shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11HullShader* GetD3D11HullShader() = 0; + + /// Returns a pointer to the ID3D11ComputeShader interface of the internal compute shader object. + + /// The method does *NOT* call AddRef() on the returned interface, + /// so Release() must not be called. + virtual ID3D11ComputeShader* GetD3D11ComputeShader() = 0; +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/interface/RasterizerStateD3D11.h b/Graphics/GraphicsEngineD3D11/interface/RasterizerStateD3D11.h deleted file mode 100644 index 7ebb7bf0..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/RasterizerStateD3D11.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Diligent::IRasterizerStateD3D11 interface - -#include "RasterizerState.h" - -namespace Diligent -{ - -// {10E96D54-1A17-4AB4-8A87-CD39211B348D} -static const Diligent::INTERFACE_ID IID_RasterizerStateD3D11 = -{ 0x10e96d54, 0x1a17, 0x4ab4, { 0x8a, 0x87, 0xcd, 0x39, 0x21, 0x1b, 0x34, 0x8d } }; - -/// Interface to the rasterizer state object implemented in D3D11 -class IRasterizerStateD3D11 : public Diligent::IRasterizerState -{ -public: - - /// Returns a pointer to the ID3D11RasterizerState interface of the internal Direct3D11 object. - - /// The method does *NOT* call AddRef() on the returned interface, - /// so Release() must not be called. - virtual ID3D11RasterizerState *GetD3D11RasterizerState() = 0; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceD3D11.h b/Graphics/GraphicsEngineD3D11/interface/RenderDeviceD3D11.h index 2baaa564..cd003a85 100644 --- a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/RenderDeviceD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ static const Diligent::INTERFACE_ID IID_RenderDeviceD3D11 = { 0x5b1cbb8, 0xfcad, 0x49ee, { 0xba, 0xda, 0x78, 0x1, 0x22, 0x3e, 0xc3, 0xfe } }; /// Interface to the render device object implemented in D3D11 -class IRenderDeviceD3D11 : public Diligent::IRenderDevice +class IRenderDeviceD3D11 : public IRenderDevice { public: diff --git a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h b/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h index d289fb65..c651a1e6 100644 --- a/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/RenderDeviceFactoryD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,24 +23,30 @@ #pragma once +/// \file +/// Declaration of functions that initialize Direct3D11-based engine implementation + #include "Errors.h" +#include "EngineD3D11Attribs.h" extern "C" { #ifdef ENGINE_DLL - typedef void (*CreateDeviceAndImmediateContextD3D11Type)( - const Diligent::EngineCreationAttribs& CreationAttribs, + + typedef void (*CreateDeviceAndContextsD3D11Type)( + const Diligent::EngineD3D11Attribs& EngineAttribs, Diligent::IRenderDevice **ppDevice, - Diligent::IDeviceContext **ppContext ); + Diligent::IDeviceContext **ppContexts, + Diligent::Uint32 NumDeferredContexts ); typedef void (*CreateSwapChainD3D11Type)( Diligent::IRenderDevice *pDevice, Diligent::IDeviceContext *pImmediateContext, - const Diligent::SwapChainDesc& SwapChainDesc, + const Diligent::SwapChainDesc& SCDesc, void* pNativeWndHandle, Diligent::ISwapChain **ppSwapChain ); - static void LoadGraphicsEngineD3D11(CreateDeviceAndImmediateContextD3D11Type &CreateDeviceFunc, CreateSwapChainD3D11Type &CreateSwapChainFunc) + static void LoadGraphicsEngineD3D11(CreateDeviceAndContextsD3D11Type &CreateDeviceFunc, CreateSwapChainD3D11Type &CreateSwapChainFunc) { CreateDeviceFunc = nullptr; CreateSwapChainFunc = nullptr; @@ -66,10 +72,10 @@ extern "C" return; } - CreateDeviceFunc = reinterpret_cast( GetProcAddress(hModule, "CreateDeviceAndImmediateContextD3D11") ); + CreateDeviceFunc = reinterpret_cast( GetProcAddress(hModule, "CreateDeviceAndContextsD3D11") ); if( CreateDeviceFunc == NULL ) { - LOG_ERROR_MESSAGE( "Failed to load CreateDeviceAndImmediateContextD3D11() from ", LibName, " library." ); + LOG_ERROR_MESSAGE( "Failed to load CreateDeviceAndContextsD3D11() from ", LibName, " library." ); FreeLibrary( hModule ); return; } @@ -83,12 +89,14 @@ extern "C" } } #else - void CreateDeviceAndImmediateContextD3D11( const Diligent::EngineCreationAttribs& CreationAttribs, - Diligent::IRenderDevice **ppDevice, - Diligent::IDeviceContext **ppContext ); - void CreateSwapChainD3D11( Diligent::IRenderDevice *pDevice, + void CreateDeviceAndContextsD3D11( const Diligent::EngineD3D11Attribs& EngineAttribs, + Diligent::IRenderDevice **ppDevice, + Diligent::IDeviceContext **ppContexts, + Diligent::Uint32 NumDeferredContexts ); + + void CreateSwapChainD3D11( Diligent::IRenderDevice *pDevice, Diligent::IDeviceContext *pImmediateContext, - const Diligent::SwapChainDesc& SwapChainDesc, + const Diligent::SwapChainDesc& SCDesc, void* pNativeWndHandle, Diligent::ISwapChain **ppSwapChain ); #endif diff --git a/Graphics/GraphicsEngineD3D11/interface/SamplerD3D11.h b/Graphics/GraphicsEngineD3D11/interface/SamplerD3D11.h index 4266f89b..b5266bf1 100644 --- a/Graphics/GraphicsEngineD3D11/interface/SamplerD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/SamplerD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/ShaderD3D11.h b/Graphics/GraphicsEngineD3D11/interface/ShaderD3D11.h index c05cf13f..e6c43492 100644 --- a/Graphics/GraphicsEngineD3D11/interface/ShaderD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/ShaderD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/ShaderResourceBindingD3D11.h b/Graphics/GraphicsEngineD3D11/interface/ShaderResourceBindingD3D11.h new file mode 100644 index 00000000..fd0be846 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/interface/ShaderResourceBindingD3D11.h @@ -0,0 +1,45 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#pragma once + +/// \file +/// Definition of the Diligent::IShaderResourceBindingD3D11 interface and related data structures + +#include "ShaderResourceBinding.h" + +namespace Diligent +{ + +// {97A6D4AC-D4AF-4AA9-B46C-67417B89026A} +static const Diligent::INTERFACE_ID IID_ShaderResourceBindingD3D11 = +{ 0x97a6d4ac, 0xd4af, 0x4aa9, { 0xb4, 0x6c, 0x67, 0x41, 0x7b, 0x89, 0x2, 0x6a } }; + +/// Shader resource binding interface +class IShaderResourceBindingD3D11 : public IShaderResourceBinding +{ +public: + +}; + +} diff --git a/Graphics/GraphicsEngineD3D11/interface/SwapChainD3D11.h b/Graphics/GraphicsEngineD3D11/interface/SwapChainD3D11.h index 2419a8ec..54a4d0ae 100644 --- a/Graphics/GraphicsEngineD3D11/interface/SwapChainD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/SwapChainD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/TextureD3D11.h b/Graphics/GraphicsEngineD3D11/interface/TextureD3D11.h index a08ff236..59ffd8ad 100644 --- a/Graphics/GraphicsEngineD3D11/interface/TextureD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/TextureD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/TextureViewD3D11.h b/Graphics/GraphicsEngineD3D11/interface/TextureViewD3D11.h index 7b44ca0b..93bd2492 100644 --- a/Graphics/GraphicsEngineD3D11/interface/TextureViewD3D11.h +++ b/Graphics/GraphicsEngineD3D11/interface/TextureViewD3D11.h @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/interface/VertexDescriptionD3D11.h b/Graphics/GraphicsEngineD3D11/interface/VertexDescriptionD3D11.h deleted file mode 100644 index ab75bfba..00000000 --- a/Graphics/GraphicsEngineD3D11/interface/VertexDescriptionD3D11.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#pragma once - -/// \file -/// Definition of the Diligent::IVertexDescriptionD3D11 interface - -#include "VertexDescription.h" - -namespace Diligent -{ - -// {7BCB2412-60EB-451C-9167-F31B869484C1} -static const Diligent::INTERFACE_ID IID_VertexDescriptionD3D11 = -{ 0x7bcb2412, 0x60eb, 0x451c, { 0x91, 0x67, 0xf3, 0x1b, 0x86, 0x94, 0x84, 0xc1 } }; - -/// Interface to the vertex description object implemented in D3D11 -class IVertexDescriptionD3D11 : public Diligent::IVertexDescription -{ -public: - - /// Returns a pointer to the ID3D11InputLayout interface of the internal Direct3D11 object. - - /// The method does *NOT* call AddRef() on the returned interface, - /// so Release() must not be called. - virtual ID3D11InputLayout* GetD3D11InputLayout() = 0; -}; - -} diff --git a/Graphics/GraphicsEngineD3D11/src/BlendStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/BlendStateD3D11Impl.cpp deleted file mode 100644 index eb336523..00000000 --- a/Graphics/GraphicsEngineD3D11/src/BlendStateD3D11Impl.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#include "pch.h" -#include "BlendStateD3D11Impl.h" -#include "RenderDeviceD3D11Impl.h" - -namespace Diligent -{ - -D3D11_BLEND BlendFactorToD3D11Blend( BLEND_FACTOR bf ) -{ - // Note that this code is safe for multithreaded environments since - // bIsInit is set to true only AFTER the entire map is initialized. - static bool bIsInit = false; - static D3D11_BLEND D3D11Blend[BLEND_FACTOR_NUM_FACTORS] = {}; - if( !bIsInit ) - { - // In a multithreaded environment, several threads can potentially enter - // this block. This is not a problem since they will just initialize the - // memory with the same values more than once - D3D11Blend[ BLEND_FACTOR_ZERO ] = D3D11_BLEND_ZERO; - D3D11Blend[ BLEND_FACTOR_ONE ] = D3D11_BLEND_ONE; - D3D11Blend[ BLEND_FACTOR_SRC_COLOR ] = D3D11_BLEND_SRC_COLOR; - D3D11Blend[ BLEND_FACTOR_INV_SRC_COLOR ] = D3D11_BLEND_INV_SRC_COLOR; - D3D11Blend[ BLEND_FACTOR_SRC_ALPHA ] = D3D11_BLEND_SRC_ALPHA; - D3D11Blend[ BLEND_FACTOR_INV_SRC_ALPHA ] = D3D11_BLEND_INV_SRC_ALPHA; - D3D11Blend[ BLEND_FACTOR_DEST_ALPHA ] = D3D11_BLEND_DEST_ALPHA; - D3D11Blend[ BLEND_FACTOR_INV_DEST_ALPHA ] = D3D11_BLEND_INV_DEST_ALPHA; - D3D11Blend[ BLEND_FACTOR_DEST_COLOR ] = D3D11_BLEND_DEST_COLOR; - D3D11Blend[ BLEND_FACTOR_INV_DEST_COLOR ] = D3D11_BLEND_INV_DEST_COLOR; - D3D11Blend[ BLEND_FACTOR_SRC_ALPHA_SAT ] = D3D11_BLEND_SRC_ALPHA_SAT; - D3D11Blend[ BLEND_FACTOR_BLEND_FACTOR ] = D3D11_BLEND_BLEND_FACTOR; - D3D11Blend[ BLEND_FACTOR_INV_BLEND_FACTOR ] = D3D11_BLEND_INV_BLEND_FACTOR; - D3D11Blend[ BLEND_FACTOR_SRC1_COLOR ] = D3D11_BLEND_SRC1_COLOR; - D3D11Blend[ BLEND_FACTOR_INV_SRC1_COLOR ] = D3D11_BLEND_INV_SRC1_COLOR; - D3D11Blend[ BLEND_FACTOR_SRC1_ALPHA ] = D3D11_BLEND_SRC1_ALPHA; - D3D11Blend[ BLEND_FACTOR_INV_SRC1_ALPHA ] = D3D11_BLEND_INV_SRC1_ALPHA; - - bIsInit = true; - } - if( bf > BLEND_FACTOR_UNDEFINED && bf < BLEND_FACTOR_NUM_FACTORS ) - { - auto d3dbf = D3D11Blend[bf]; - VERIFY( d3dbf != 0, "Incorrect blend factor" ); - return d3dbf; - } - else - { - UNEXPECTED("Incorrect blend factor (", bf, ")" ) - return static_cast( 0 ); - } -} - -D3D11_BLEND_OP BlendOperation2D3D11BlendOp( BLEND_OPERATION BlendOp ) -{ - static bool bIsInit = false; - static D3D11_BLEND_OP D3D11BlendOp[BLEND_OPERATION_NUM_OPERATIONS] = {}; - if( !bIsInit ) - { - D3D11BlendOp[ BLEND_OPERATION_ADD ] = D3D11_BLEND_OP_ADD; - D3D11BlendOp[ BLEND_OPERATION_SUBTRACT ] = D3D11_BLEND_OP_SUBTRACT; - D3D11BlendOp[ BLEND_OPERATION_REV_SUBTRACT ] = D3D11_BLEND_OP_REV_SUBTRACT; - D3D11BlendOp[ BLEND_OPERATION_MIN ] = D3D11_BLEND_OP_MIN; - D3D11BlendOp[ BLEND_OPERATION_MAX ] = D3D11_BLEND_OP_MAX; - - bIsInit = true; - } - - if( BlendOp > BLEND_OPERATION_UNDEFINED && BlendOp < BLEND_OPERATION_NUM_OPERATIONS ) - { - auto d3dbop = D3D11BlendOp[BlendOp]; - VERIFY( d3dbop != 0, "Incorrect blend operation" ); - return d3dbop; - } - else - { - UNEXPECTED( "Incorrect blend operation (", BlendOp, ")" ) - return static_cast(0); - } -} - -BlendStateD3D11Impl::BlendStateD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, - const BlendStateDesc& BlendStateDesc) : - TBlendStateBase(pRenderDeviceD3D11, BlendStateDesc) -{ - D3D11_BLEND_DESC D3D11BSDesc; - D3D11BSDesc.AlphaToCoverageEnable = BlendStateDesc.AlphaToCoverageEnable ? TRUE : FALSE; - D3D11BSDesc.IndependentBlendEnable = BlendStateDesc.IndependentBlendEnable ? TRUE : FALSE; - VERIFY( BlendStateDesc.MaxRenderTargets >= 8, "Number of render targets is expected to be at least 8" ); - for( int i = 0; i < 8; ++i ) - { - const auto& SrcRTDesc = BlendStateDesc.RenderTargets[i]; - auto &DstRTDesc = D3D11BSDesc.RenderTarget[i]; - DstRTDesc.BlendEnable = SrcRTDesc.BlendEnable ? TRUE : FALSE; - - DstRTDesc.SrcBlend = BlendFactorToD3D11Blend(SrcRTDesc.SrcBlend); - DstRTDesc.DestBlend = BlendFactorToD3D11Blend(SrcRTDesc.DestBlend); - DstRTDesc.BlendOp = BlendOperation2D3D11BlendOp(SrcRTDesc.BlendOp); - - DstRTDesc.SrcBlendAlpha = BlendFactorToD3D11Blend(SrcRTDesc.SrcBlendAlpha); - DstRTDesc.DestBlendAlpha = BlendFactorToD3D11Blend(SrcRTDesc.DestBlendAlpha); - DstRTDesc.BlendOpAlpha = BlendOperation2D3D11BlendOp(SrcRTDesc.BlendOpAlpha); - - DstRTDesc.RenderTargetWriteMask = - ((SrcRTDesc.RenderTargetWriteMask & COLOR_MASK_RED) ? D3D11_COLOR_WRITE_ENABLE_RED : 0) | - ((SrcRTDesc.RenderTargetWriteMask & COLOR_MASK_GREEN) ? D3D11_COLOR_WRITE_ENABLE_GREEN : 0) | - ((SrcRTDesc.RenderTargetWriteMask & COLOR_MASK_BLUE) ? D3D11_COLOR_WRITE_ENABLE_BLUE : 0) | - ((SrcRTDesc.RenderTargetWriteMask & COLOR_MASK_ALPHA) ? D3D11_COLOR_WRITE_ENABLE_ALPHA : 0); - } - - auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); - CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateBlendState( &D3D11BSDesc, &m_pd3d11BlendState ), - "Failed to create D3D11 blend state object" ); -} - -BlendStateD3D11Impl::~BlendStateD3D11Impl() -{ - -} - -IMPLEMENT_QUERY_INTERFACE( BlendStateD3D11Impl, IID_BlendStateD3D11, TBlendStateBase ) - -} diff --git a/Graphics/GraphicsEngineD3D11/src/BufferD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/BufferD3D11Impl.cpp index 97905e47..7c4282d4 100644 --- a/Graphics/GraphicsEngineD3D11/src/BufferD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/BufferD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,20 +22,25 @@ */ #include "pch.h" +#include + #include "BufferD3D11Impl.h" #include "RenderDeviceD3D11Impl.h" #include "DeviceContextD3D11Impl.h" #include "D3D11TypeConversions.h" #include "BufferViewD3D11Impl.h" #include "GraphicsUtilities.h" - -using namespace Diligent; +#include "EngineMemory.h" namespace Diligent { -BufferD3D11Impl :: BufferD3D11Impl(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const BufferDesc& BuffDesc, const BufferData &BuffData /*= BufferData()*/) : - TBufferBase(pRenderDeviceD3D11, BuffDesc) +BufferD3D11Impl :: BufferD3D11Impl(FixedBlockMemoryAllocator &BufferObjMemAllocator, + FixedBlockMemoryAllocator &BuffViewObjMemAllocator, + RenderDeviceD3D11Impl *pRenderDeviceD3D11, + const BufferDesc& BuffDesc, + const BufferData &BuffData /*= BufferData()*/) : + TBufferBase(BufferObjMemAllocator, BuffViewObjMemAllocator, pRenderDeviceD3D11, BuffDesc, false) { #define LOG_BUFFER_ERROR_AND_THROW(...) LOG_ERROR_AND_THROW("Buffer \"", BuffDesc.Name ? BuffDesc.Name : "", "\": ", ##__VA_ARGS__); @@ -141,9 +146,9 @@ void BufferD3D11Impl :: Map(IDeviceContext *pContext, MAP_TYPE MapType, Uint32 M VERIFY( pMappedData || (MapFlags & MAP_FLAG_DO_NOT_WAIT) && (hr == DXGI_ERROR_WAS_STILL_DRAWING), "Map failed" ); } -void BufferD3D11Impl::Unmap( IDeviceContext *pContext ) +void BufferD3D11Impl::Unmap( IDeviceContext *pContext, MAP_TYPE MapType ) { - TBufferBase::Unmap( pContext ); + TBufferBase::Unmap( pContext, MapType ); auto *pd3d11DeviceContext = static_cast(pContext)->GetD3D11DeviceContext(); pd3d11DeviceContext->Unmap(m_pd3d11Buffer, 0); @@ -159,18 +164,22 @@ void BufferD3D11Impl::CreateViewInternal( const BufferViewDesc &OrigViewDesc, IB try { + auto *pDeviceD3D11Impl = ValidatedCast(GetDevice()); + auto &BuffViewAllocator = pDeviceD3D11Impl->GetBuffViewObjAllocator(); + VERIFY( &BuffViewAllocator == &m_dbgBuffViewAllocator, "Buff view allocator does not match allocator provided at buffer initialization" ); + BufferViewDesc ViewDesc = OrigViewDesc; if( ViewDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS ) { CComPtr pUAV; CreateUAV( ViewDesc, &pUAV ); - *ppView = new BufferViewD3D11Impl( GetDevice(), ViewDesc, this, pUAV, bIsDefaultView ); + *ppView = NEW(BuffViewAllocator, "BufferViewD3D11Impl instance", BufferViewD3D11Impl, pDeviceD3D11Impl, ViewDesc, this, pUAV, bIsDefaultView ); } else if( ViewDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE ) { CComPtr pSRV; CreateSRV( ViewDesc, &pSRV ); - *ppView = new BufferViewD3D11Impl( GetDevice(), ViewDesc, this, pSRV, bIsDefaultView ); + *ppView = NEW(BuffViewAllocator, "BufferViewD3D11Impl instance", BufferViewD3D11Impl, pDeviceD3D11Impl, ViewDesc, this, pSRV, bIsDefaultView ); } if( !bIsDefaultView && *ppView ) @@ -185,24 +194,10 @@ void BufferD3D11Impl::CreateViewInternal( const BufferViewDesc &OrigViewDesc, IB void BufferD3D11Impl::CreateUAV( BufferViewDesc &UAVDesc, ID3D11UnorderedAccessView **ppD3D11UAV ) { - D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UAVDesc; - memset( &D3D11_UAVDesc, 0, sizeof(D3D11_UAVDesc) ); - const auto &BuffFmt = m_Desc.Format; - if( m_Desc.Mode == BUFFER_MODE_FORMATED ) - D3D11_UAVDesc.Format = TypeToDXGI_Format( BuffFmt.ValueType, BuffFmt.NumComponents, BuffFmt.IsNormalized ); - CorrectBufferViewDesc( UAVDesc ); - if( UAVDesc.ByteOffset != 0 ) - { - VERIFY( m_Desc.Mode == BUFFER_MODE_STRUCTURED, "Non-zero byte offset is only supported for structured buffers" ); - } - VERIFY( UAVDesc.ViewType == BUFFER_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected" ); - VERIFY( (UAVDesc.ByteOffset % m_Desc.ElementByteStride) == 0, "Byte offest is not multiple of element byte stride" ); - VERIFY( (UAVDesc.ByteWidth % m_Desc.ElementByteStride) == 0, "Byte width is not multiple of element byte stride" ); - D3D11_UAVDesc.Buffer.FirstElement = UAVDesc.ByteOffset / m_Desc.ElementByteStride; - D3D11_UAVDesc.Buffer.NumElements = UAVDesc.ByteWidth / m_Desc.ElementByteStride; - D3D11_UAVDesc.Buffer.Flags = 0; // D3D11_BUFFER_UAV_FLAG_RAW, D3D11_BUFFER_UAV_FLAG_APPEND, D3D11_BUFFER_UAV_FLAG_COUNTER - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; + + D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UAVDesc; + BufferViewDesc_to_D3D11_UAV_DESC(m_Desc, UAVDesc, D3D11_UAVDesc); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateUnorderedAccessView( m_pd3d11Buffer, &D3D11_UAVDesc, ppD3D11UAV ), @@ -211,23 +206,10 @@ void BufferD3D11Impl::CreateUAV( BufferViewDesc &UAVDesc, ID3D11UnorderedAccessV void BufferD3D11Impl::CreateSRV( struct BufferViewDesc &SRVDesc, ID3D11ShaderResourceView **ppD3D11SRV ) { - D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SRVDesc; - memset( &D3D11_SRVDesc, 0, sizeof( D3D11_SRVDesc ) ); - const auto &BuffFmt = m_Desc.Format; - if( m_Desc.Mode == BUFFER_MODE_FORMATED ) - D3D11_SRVDesc.Format = TypeToDXGI_Format( BuffFmt.ValueType, BuffFmt.NumComponents, BuffFmt.IsNormalized ); - CorrectBufferViewDesc( SRVDesc ); - if( SRVDesc.ByteOffset != 0 ) - { - VERIFY( m_Desc.Mode == BUFFER_MODE_STRUCTURED, "Non-zero byte offset is only supported for structured buffers" ); - } - VERIFY( SRVDesc.ViewType == BUFFER_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected" ); - VERIFY( (SRVDesc.ByteOffset % m_Desc.ElementByteStride) == 0, "Byte offest is not multiple of element byte stride" ); - VERIFY( (SRVDesc.ByteWidth % m_Desc.ElementByteStride) == 0, "Byte width is not multiple of element byte stride" ); - D3D11_SRVDesc.Buffer.FirstElement = SRVDesc.ByteOffset / m_Desc.ElementByteStride; - D3D11_SRVDesc.Buffer.NumElements = SRVDesc.ByteWidth / m_Desc.ElementByteStride; - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; + + D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SRVDesc; + BufferViewDesc_to_D3D11_SRV_DESC(m_Desc, SRVDesc, D3D11_SRVDesc); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateShaderResourceView( m_pd3d11Buffer, &D3D11_SRVDesc, ppD3D11SRV ), diff --git a/Graphics/GraphicsEngineD3D11/src/BufferViewD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/BufferViewD3D11Impl.cpp index 6f8239d8..3aa8ca1b 100644 --- a/Graphics/GraphicsEngineD3D11/src/BufferViewD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/BufferViewD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,17 @@ namespace Diligent { -BufferViewD3D11Impl::BufferViewD3D11Impl( IRenderDevice *pDevice, - const BufferViewDesc& ViewDesc, - IBuffer *pBuffer, - ID3D11View* pD3D11View, - bool bIsDefaultView ) : - TBufferViewBase( pDevice, ViewDesc, pBuffer, bIsDefaultView ), +BufferViewD3D11Impl::BufferViewD3D11Impl( FixedBlockMemoryAllocator &BuffViewObjAllocator, + IRenderDevice *pDevice, + const BufferViewDesc& ViewDesc, + IBuffer *pBuffer, + ID3D11View* pD3D11View, + bool bIsDefaultView ) : + TBufferViewBase( BuffViewObjAllocator, pDevice, ViewDesc, pBuffer, bIsDefaultView ), m_pD3D11View( pD3D11View ) { } -ID3D11View* BufferViewD3D11Impl::GetD3D11View() -{ - return m_pD3D11View; -} - IMPLEMENT_QUERY_INTERFACE( BufferViewD3D11Impl, IID_BufferViewD3D11, TBufferViewBase ) } diff --git a/Graphics/GraphicsEngineD3D11/src/CommandListD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/CommandListD3D11Impl.cpp new file mode 100644 index 00000000..2c74c3ec --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/CommandListD3D11Impl.cpp @@ -0,0 +1,45 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" +#include + +#include "CommandListD3D11Impl.h" +#include "EngineMemory.h" + +namespace Diligent +{ + +CommandListD3D11Impl :: CommandListD3D11Impl(FixedBlockMemoryAllocator &CommandListObjMemAllocator, + IRenderDevice *pDevice, + ID3D11CommandList *pd3d11CommandList) : + TCommandListBase(CommandListObjMemAllocator, pDevice), + m_pd3d11CommandList(pd3d11CommandList) +{ +} + +CommandListD3D11Impl :: ~CommandListD3D11Impl() +{ +} + +} diff --git a/Graphics/GraphicsEngineD3D11/src/D3D11DebugUtilities.cpp b/Graphics/GraphicsEngineD3D11/src/D3D11DebugUtilities.cpp index 686df365..440a616e 100644 --- a/Graphics/GraphicsEngineD3D11/src/D3D11DebugUtilities.cpp +++ b/Graphics/GraphicsEngineD3D11/src/D3D11DebugUtilities.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,176 +23,9 @@ #include "pch.h" #include "D3D11DebugUtilities.h" -#include "TextureViewD3D11.h" -#include "BufferViewD3D11.h" -#include "BufferD3D11.h" -#include "SamplerD3D11.h" -#include "GraphicsUtilities.h" -namespace Diligent -{ - -#ifdef VERIFY_RESOURCE_ARRAYS - -template -void dbgVerifyResourceArraysInternal( TResourceArr &Resources, TD3D11ResourceArr& d3d11Resources, TTestProc TestProc ) -{ - VERIFY( Resources.size() == d3d11Resources.size(), "Inconsistent resource array sizes (", Resources.size(), ",", d3d11Resources.size(), ")" ); - auto NumSlots = std::min(Resources.size(), d3d11Resources.size()); - for( Uint32 Slot = 0; Slot < NumSlots; ++Slot ) - { - auto &Res = Resources.at(Slot); - const auto &d3d11Res = d3d11Resources.at( Slot ); - TestProc( Slot, Res, d3d11Res ); - } -} - -static const Char* GetD3D11ResName( const ID3D11ShaderResourceView* ){ return "SRV"; } -static const Char* GetD3D11ResName( const ID3D11UnorderedAccessView* ){ return "UAV"; } -static const Char* GetD3D11ResName( const ID3D11Buffer* ){ return "constant buffer"; } -static const Char* GetD3D11ResName( const ID3D11SamplerState* ){ return "sampler"; } -template -class dbgVerifyResourceViewArrays -{ -public: - dbgVerifyResourceViewArrays( TEXTURE_VIEW_TYPE TVT, BUFFER_VIEW_TYPE BVT, IShader *pShader ) : - TexViewType( TVT ), - BuffViewType( BVT ), - ShaderTypeName(GetShaderTypeLiteralName(pShader->GetDesc().ShaderType)), - ShaderName(pShader->GetDesc().Name) - {} - - void operator()( int Slot, const TBoundResourceType& BoundRes, const TD3D11ResourceType* d3d11View ) - { - TD3D11ResourceType *pD3D11ResTypeMarker = nullptr; -#define VERFIY_RESOURCE_BINDING(Exp, Intro, Res, ...) \ - VERIFY(Exp, Intro, " \"", Res->GetDesc().Name, "\" bound as ", GetD3D11ResName(pD3D11ResTypeMarker)," to shader \"", ShaderName, "\" (", ShaderTypeName, ") at slot ", Slot, ' ', __VA_ARGS__) - - if( !d3d11View ) - { - VERFIY_RESOURCE_BINDING( !BoundRes.pResource, "Unexpected non-null resource", BoundRes.pResource ) - VERFIY_RESOURCE_BINDING( !BoundRes.pView, "Unexpected non-null resource view", BoundRes.pView ) - } - - if( BoundRes.pView ) - { - auto ncView = const_cast(BoundRes.pView.RawPtr()); - RefCntAutoPtr pTexView; - ncView->QueryInterface( IID_TextureViewD3D11, reinterpret_cast(static_cast(&pTexView)) ); - RefCntAutoPtr pBuffView; - ncView->QueryInterface( IID_BufferViewD3D11, reinterpret_cast(static_cast(&pBuffView)) ); - VERFIY_RESOURCE_BINDING( pTexView || pBuffView, "Resource", ncView, "is expected to be a texture view or a buffer view" ); - if( pTexView ) - { - auto ViewType = pTexView->GetDesc().ViewType; - VERFIY_RESOURCE_BINDING( ViewType == TexViewType, "Texture view", ncView, "has incorrect type: ", GetTexViewTypeLiteralName( TexViewType ), " is expected, while ", GetTexViewTypeLiteralName( ViewType ), " provided" ); - auto *d3d11RefView = pTexView->GetD3D11View(); - VERFIY_RESOURCE_BINDING( d3d11RefView == d3d11View && BoundRes.pd3d11View.RawPtr() == d3d11RefView, "Texture view", ncView, "does not match D3D11 resoruce" ); - auto *pTex = pTexView->GetTexture(); - VERFIY_RESOURCE_BINDING( pTex == BoundRes.pResource, "Texture view", ncView, "is not the view of resource \"", BoundRes.pResource->GetDesc().Name, "\"" ); - } - - if( pBuffView ) - { - auto ViewType = pBuffView->GetDesc().ViewType; - VERFIY_RESOURCE_BINDING( ViewType == BuffViewType, "Buffer view", ncView, "has incorrect type: ", GetBufferViewTypeLiteralName( BuffViewType ), " is expected, while ", GetBufferViewTypeLiteralName( ViewType ), " provided" ); - auto *d3d11RefView = pBuffView->GetD3D11View(); - VERFIY_RESOURCE_BINDING( d3d11RefView == d3d11View && BoundRes.pd3d11View.RawPtr() == d3d11RefView, "Buffer view", ncView, "does not match D3D11 resource" ); - auto *pBuf = pBuffView->GetBuffer(); - VERFIY_RESOURCE_BINDING( pBuf == BoundRes.pResource, "Buffer view", ncView, "is not the view of resource \"", BoundRes.pResource->GetDesc().Name, "\"" ); - } - } - else - { - VERIFY( !BoundRes.pResource, "Unexpected non-null resource bound to shader \"", ShaderName, "\" (", ShaderTypeName, ") at slot ", Slot); - VERIFY( !BoundRes.pd3d11View, "Unexpected non-null D3D11 resource view bound to shader \"", ShaderName, "\" (", ShaderTypeName, ") at slot ", Slot); - } - } -private: - TEXTURE_VIEW_TYPE TexViewType; - BUFFER_VIEW_TYPE BuffViewType; - const Char* ShaderTypeName; - const char* ShaderName; -}; - -void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundSRV >&SRVs, const std::vector d3d11SRVs, IShader *pShader ) -{ - dbgVerifyResourceArraysInternal(SRVs, d3d11SRVs, dbgVerifyResourceViewArrays(TEXTURE_VIEW_SHADER_RESOURCE, BUFFER_VIEW_SHADER_RESOURCE, pShader)); -} - -void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundUAV >&UAVs, const std::vector d3d11UAVs, IShader *pShader ) -{ - dbgVerifyResourceArraysInternal(UAVs, d3d11UAVs, dbgVerifyResourceViewArrays(TEXTURE_VIEW_UNORDERED_ACCESS, BUFFER_VIEW_UNORDERED_ACCESS, pShader)); -} - -void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundCB >&CBs, const std::vector d3d11CBs, IShader *pShader ) -{ - const auto* ShaderTypeName = GetShaderTypeLiteralName( pShader->GetDesc().ShaderType ); - const auto &ShaderName = pShader->GetDesc().Name; - ID3D11Buffer *pD3D11ResTypeMarker = nullptr; - - dbgVerifyResourceArraysInternal( CBs, d3d11CBs, - [&]( int Slot, const ShaderD3D11Impl::BoundCB& CB, const ID3D11Buffer* d3d11CB ) - { - if( !d3d11CB ) - { - VERFIY_RESOURCE_BINDING( !CB.pBuff, "Unexpected non-null resource", CB.pBuff ) - } - - if( CB.pBuff ) - { - auto ncCB = const_cast(CB.pBuff.RawPtr()); - RefCntAutoPtr pBuff; - ncCB->QueryInterface( IID_BufferD3D11, reinterpret_cast(static_cast(&pBuff)) ); - VERFIY_RESOURCE_BINDING( pBuff, "Resource", ncCB, "is expected to be a buffer" ); - if( pBuff ) - { - auto *d3d11RefBuff = pBuff->GetD3D11Buffer(); - VERFIY_RESOURCE_BINDING( d3d11RefBuff == d3d11CB && d3d11RefBuff == CB.pd3d11Buff, "Constant buffer", ncCB, "does not match D3D11 buffer" ); - } - } - else - { - VERIFY( !d3d11CB, "Unexpected non-null D3D11 buffer bound to shader \"", ShaderName, "\" (", ShaderTypeName, ") at slot ", Slot); - } - } - ); -} - -void dbgVerifyResourceArrays( const std::vector< ShaderD3D11Impl::BoundSampler >&Samplers, const std::vector d3d11Samplers, IShader *pShader ) +namespace Diligent { - const auto* ShaderTypeName = GetShaderTypeLiteralName( pShader->GetDesc().ShaderType ); - const auto &ShaderName = pShader->GetDesc().Name; - ID3D11SamplerState *pD3D11ResTypeMarker = nullptr; - - dbgVerifyResourceArraysInternal( Samplers, d3d11Samplers, - [&]( int Slot, const ShaderD3D11Impl::BoundSampler& Sampler, const ID3D11SamplerState* d3d11Sampler ) - { - if( !d3d11Sampler ) - { - VERFIY_RESOURCE_BINDING( !Sampler.pSampler, "Unexpected non-null resource", Sampler.pSampler ) - } - if( Sampler.pSampler ) - { - auto ncSampler = const_cast(Sampler.pSampler.RawPtr()); - RefCntAutoPtr pSamplerD3D11; - ncSampler->QueryInterface( IID_SamplerD3D11, reinterpret_cast(static_cast(&pSamplerD3D11)) ); - VERFIY_RESOURCE_BINDING( pSamplerD3D11, "Resource", ncSampler, "is expected to be a sampler" ); - if( pSamplerD3D11 ) - { - auto *d3d11RefSampler = pSamplerD3D11->GetD3D11SamplerState(); - VERFIY_RESOURCE_BINDING( d3d11RefSampler == d3d11Sampler && d3d11RefSampler == Sampler.pd3d11Sampler, "Sampler", ncSampler, "does not match D3D11 sampler" ); - } - } - else - { - VERIFY( !d3d11Sampler, "Unexpected non-null D3D11 sampler bound to shader \"", ShaderName, "\" (", ShaderTypeName, ") at slot ", Slot ); - } - } - ); -} - -#endif } diff --git a/Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp b/Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp index ac6265f2..5c340a30 100644 --- a/Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp +++ b/Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,481 +24,98 @@ #include "pch.h" #include "D3D11TypeConversions.h" +#include "D3D11TypeDefinitions.h" +#include "D3DTypeConversionImpl.h" +#include "D3DViewDescConversionImpl.h" + namespace Diligent { -DXGI_FORMAT TypeToDXGI_Format(VALUE_TYPE ValType, Uint32 NumComponents, Bool bIsNormalized) +D3D11_FILTER FilterTypeToD3D11Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter) { - switch(ValType) - { - case VT_FLOAT16: - { - VERIFY( !bIsNormalized, "Floating point formats cannot be normalized" ); - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R16_FLOAT; - case 2: return DXGI_FORMAT_R16G16_FLOAT; - case 4: return DXGI_FORMAT_R16G16B16A16_FLOAT; - default: UNEXPECTED("Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - - case VT_FLOAT32: - { - VERIFY( !bIsNormalized, "Floating point formats cannot be normalized" ); - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R32_FLOAT; - case 2: return DXGI_FORMAT_R32G32_FLOAT; - case 3: return DXGI_FORMAT_R32G32B32_FLOAT; - case 4: return DXGI_FORMAT_R32G32B32A32_FLOAT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - - case VT_INT32: - { - VERIFY( !bIsNormalized, "32-bit UNORM formats are not supported. Use R32_FLOAT instead" ); - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R32_SINT; - case 2: return DXGI_FORMAT_R32G32_SINT; - case 3: return DXGI_FORMAT_R32G32B32_SINT; - case 4: return DXGI_FORMAT_R32G32B32A32_SINT; - default: UNEXPECTED("Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - - case VT_UINT32: - { - VERIFY( !bIsNormalized, "32-bit UNORM formats are not supported. Use R32_FLOAT instead" ); - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R32_UINT; - case 2: return DXGI_FORMAT_R32G32_UINT; - case 3: return DXGI_FORMAT_R32G32B32_UINT; - case 4: return DXGI_FORMAT_R32G32B32A32_UINT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - - case VT_INT16: - { - if( bIsNormalized ) - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R16_SNORM; - case 2: return DXGI_FORMAT_R16G16_SNORM; - case 4: return DXGI_FORMAT_R16G16B16A16_SNORM; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - else - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R16_SINT; - case 2: return DXGI_FORMAT_R16G16_SINT; - case 4: return DXGI_FORMAT_R16G16B16A16_SINT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - } - - case VT_UINT16: - { - if( bIsNormalized ) - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R16_UNORM; - case 2: return DXGI_FORMAT_R16G16_UNORM; - case 4: return DXGI_FORMAT_R16G16B16A16_UNORM; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - else - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R16_UINT; - case 2: return DXGI_FORMAT_R16G16_UINT; - case 4: return DXGI_FORMAT_R16G16B16A16_UINT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - } - - case VT_INT8: - { - if( bIsNormalized ) - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R8_SNORM; - case 2: return DXGI_FORMAT_R8G8_SNORM; - case 4: return DXGI_FORMAT_R8G8B8A8_SNORM; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - else - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R8_SINT; - case 2: return DXGI_FORMAT_R8G8_SINT; - case 4: return DXGI_FORMAT_R8G8B8A8_SINT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - } - - case VT_UINT8: - { - if( bIsNormalized ) - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R8_UNORM; - case 2: return DXGI_FORMAT_R8G8_UNORM; - case 4: return DXGI_FORMAT_R8G8B8A8_UNORM; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - else - { - switch(NumComponents) - { - case 1: return DXGI_FORMAT_R8_UINT; - case 2: return DXGI_FORMAT_R8G8_UINT; - case 4: return DXGI_FORMAT_R8G8B8A8_UINT; - default: UNEXPECTED( "Unusupported number of components" ); return DXGI_FORMAT_UNKNOWN; - } - } - } + return FilterTypeToD3DFilter(MinFilter, MagFilter, MipFilter); +} - default: UNEXPECTED( "Unusupported format" ); return DXGI_FORMAT_UNKNOWN; - } +D3D11_TEXTURE_ADDRESS_MODE TexAddressModeToD3D11AddressMode(TEXTURE_ADDRESS_MODE Mode) +{ + return TexAddressModeToD3DAddressMode(Mode); } -DXGI_FORMAT CorrectDXGIFormat( DXGI_FORMAT DXGIFormat, Uint32 BindFlags ) +D3D11_COMPARISON_FUNC ComparisonFuncToD3D11ComparisonFunc(COMPARISON_FUNCTION Func) { - if( (BindFlags & BIND_DEPTH_STENCIL) && (BindFlags != BIND_DEPTH_STENCIL) ) - { - switch( DXGIFormat ) - { - case DXGI_FORMAT_R32_FLOAT: - case DXGI_FORMAT_D32_FLOAT: - DXGIFormat = DXGI_FORMAT_R32_TYPELESS; - break; + return ComparisonFuncToD3DComparisonFunc(Func); +} - case DXGI_FORMAT_R16_UNORM: - case DXGI_FORMAT_D16_UNORM: - DXGIFormat = DXGI_FORMAT_R16_TYPELESS; - break; +void DepthStencilStateDesc_To_D3D11_DEPTH_STENCIL_DESC(const DepthStencilStateDesc &DepthStencilDesc, D3D11_DEPTH_STENCIL_DESC &d3d11DSSDesc) +{ + DepthStencilStateDesc_To_D3D_DEPTH_STENCIL_DESC(DepthStencilDesc, d3d11DSSDesc); +} - default: - UNEXPECTED( "Unsupported format" ); - break; - } - } +void RasterizerStateDesc_To_D3D11_RASTERIZER_DESC(const RasterizerStateDesc &RasterizerDesc, D3D11_RASTERIZER_DESC &d3d11RSDesc) +{ + RasterizerStateDesc_To_D3D_RASTERIZER_DESC(RasterizerDesc, d3d11RSDesc); + d3d11RSDesc.ScissorEnable = RasterizerDesc.ScissorEnable ? TRUE : FALSE; +} - if( BindFlags == BIND_DEPTH_STENCIL ) - { - switch( DXGIFormat ) - { - case DXGI_FORMAT_R32_FLOAT: - DXGIFormat = DXGI_FORMAT_D32_FLOAT; - break; - case DXGI_FORMAT_R16_UNORM: - DXGIFormat = DXGI_FORMAT_D16_UNORM; - break; - } - } +void BlendStateDesc_To_D3D11_BLEND_DESC(const BlendStateDesc &BSDesc, D3D11_BLEND_DESC &d3d11BSDesc) +{ + BlendStateDescToD3DBlendDesc(BSDesc, d3d11BSDesc); - if( BindFlags == BIND_SHADER_RESOURCE || BindFlags == BIND_UNORDERED_ACCESS ) + for( int i = 0; i < 8; ++i ) { - switch( DXGIFormat ) + const auto& SrcRTDesc = BSDesc.RenderTargets[i]; + if (SrcRTDesc.LogicOperationEnable) { - case DXGI_FORMAT_D32_FLOAT: - DXGIFormat = DXGI_FORMAT_R32_FLOAT; - break; - - case DXGI_FORMAT_D16_UNORM: - DXGIFormat = DXGI_FORMAT_R16_UNORM; - break; + LOG_ERROR("Logical operations on render targets are not supported by D3D11 device"); } } - - return DXGIFormat; } -DXGI_FORMAT TexFormatToDXGI_Format(TEXTURE_FORMAT TexFormat, Uint32 BindFlags) +void LayoutElements_To_D3D11_INPUT_ELEMENT_DESCs(const std::vector > &LayoutElements, + std::vector > &D3D11InputElements) { - static Bool bFormatMapIntialized = false; - static DXGI_FORMAT FmtToDXGIFmtMap[TEX_FORMAT_NUM_FORMATS] = {DXGI_FORMAT_UNKNOWN}; - if( !bFormatMapIntialized ) - { - FmtToDXGIFmtMap[ TEX_FORMAT_UNKNOWN ] = DXGI_FORMAT_UNKNOWN; - - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA32_TYPELESS ] = DXGI_FORMAT_R32G32B32A32_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA32_FLOAT ] = DXGI_FORMAT_R32G32B32A32_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA32_UINT ] = DXGI_FORMAT_R32G32B32A32_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA32_SINT ] = DXGI_FORMAT_R32G32B32A32_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RGB32_TYPELESS ] = DXGI_FORMAT_R32G32B32_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB32_FLOAT ] = DXGI_FORMAT_R32G32B32_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB32_UINT ] = DXGI_FORMAT_R32G32B32_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB32_SINT ] = DXGI_FORMAT_R32G32B32_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_TYPELESS ] = DXGI_FORMAT_R16G16B16A16_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_FLOAT ] = DXGI_FORMAT_R16G16B16A16_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_UNORM ] = DXGI_FORMAT_R16G16B16A16_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_UINT ] = DXGI_FORMAT_R16G16B16A16_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_SNORM ] = DXGI_FORMAT_R16G16B16A16_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA16_SINT ] = DXGI_FORMAT_R16G16B16A16_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RG32_TYPELESS ] = DXGI_FORMAT_R32G32_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RG32_FLOAT ] = DXGI_FORMAT_R32G32_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_RG32_UINT ] = DXGI_FORMAT_R32G32_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RG32_SINT ] = DXGI_FORMAT_R32G32_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R32G8X24_TYPELESS ] = DXGI_FORMAT_R32G8X24_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_D32_FLOAT_S8X24_UINT ] = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_R32_FLOAT_X8X24_TYPELESS ]= DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_X32_TYPELESS_G8X24_UINT ]= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RGB10A2_TYPELESS ] = DXGI_FORMAT_R10G10B10A2_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB10A2_UNORM ] = DXGI_FORMAT_R10G10B10A2_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB10A2_UINT ] = DXGI_FORMAT_R10G10B10A2_UINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R11G11B10_FLOAT ] = DXGI_FORMAT_R11G11B10_FLOAT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_TYPELESS ] = DXGI_FORMAT_R8G8B8A8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_UNORM ] = DXGI_FORMAT_R8G8B8A8_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_UNORM_SRGB ] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_UINT ] = DXGI_FORMAT_R8G8B8A8_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_SNORM ] = DXGI_FORMAT_R8G8B8A8_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RGBA8_SINT ] = DXGI_FORMAT_R8G8B8A8_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_TYPELESS ] = DXGI_FORMAT_R16G16_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_FLOAT ] = DXGI_FORMAT_R16G16_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_UNORM ] = DXGI_FORMAT_R16G16_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_UINT ] = DXGI_FORMAT_R16G16_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_SNORM ] = DXGI_FORMAT_R16G16_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RG16_SINT ] = DXGI_FORMAT_R16G16_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R32_TYPELESS ] = DXGI_FORMAT_R32_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_D32_FLOAT ] = DXGI_FORMAT_D32_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_R32_FLOAT ] = DXGI_FORMAT_R32_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_R32_UINT ] = DXGI_FORMAT_R32_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_R32_SINT ] = DXGI_FORMAT_R32_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R24G8_TYPELESS ] = DXGI_FORMAT_R24G8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_D24_UNORM_S8_UINT ] = DXGI_FORMAT_D24_UNORM_S8_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_R24_UNORM_X8_TYPELESS ] = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_X24_TYPELESS_G8_UINT ] = DXGI_FORMAT_X24_TYPELESS_G8_UINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_TYPELESS ] = DXGI_FORMAT_R8G8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_UNORM ] = DXGI_FORMAT_R8G8_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_UINT ] = DXGI_FORMAT_R8G8_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_SNORM ] = DXGI_FORMAT_R8G8_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_SINT ] = DXGI_FORMAT_R8G8_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R16_TYPELESS ] = DXGI_FORMAT_R16_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_R16_FLOAT ] = DXGI_FORMAT_R16_FLOAT; - FmtToDXGIFmtMap[ TEX_FORMAT_D16_UNORM ] = DXGI_FORMAT_D16_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_R16_UNORM ] = DXGI_FORMAT_R16_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_R16_UINT ] = DXGI_FORMAT_R16_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_R16_SNORM ] = DXGI_FORMAT_R16_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_R16_SINT ] = DXGI_FORMAT_R16_SINT; - - FmtToDXGIFmtMap[ TEX_FORMAT_R8_TYPELESS ] = DXGI_FORMAT_R8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_R8_UNORM ] = DXGI_FORMAT_R8_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_R8_UINT ] = DXGI_FORMAT_R8_UINT; - FmtToDXGIFmtMap[ TEX_FORMAT_R8_SNORM ] = DXGI_FORMAT_R8_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_R8_SINT ] = DXGI_FORMAT_R8_SINT; - FmtToDXGIFmtMap[ TEX_FORMAT_A8_UNORM ] = DXGI_FORMAT_A8_UNORM; - - FmtToDXGIFmtMap[ TEX_FORMAT_R1_UNORM ] = DXGI_FORMAT_R1_UNORM ; - FmtToDXGIFmtMap[ TEX_FORMAT_RGB9E5_SHAREDEXP ] = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; - FmtToDXGIFmtMap[ TEX_FORMAT_RG8_B8G8_UNORM ] = DXGI_FORMAT_R8G8_B8G8_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_G8R8_G8B8_UNORM ] = DXGI_FORMAT_G8R8_G8B8_UNORM; - - FmtToDXGIFmtMap[ TEX_FORMAT_BC1_TYPELESS ] = DXGI_FORMAT_BC1_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC1_UNORM ] = DXGI_FORMAT_BC1_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC1_UNORM_SRGB ] = DXGI_FORMAT_BC1_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_BC2_TYPELESS ] = DXGI_FORMAT_BC2_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC2_UNORM ] = DXGI_FORMAT_BC2_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC2_UNORM_SRGB ] = DXGI_FORMAT_BC2_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_BC3_TYPELESS ] = DXGI_FORMAT_BC3_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC3_UNORM ] = DXGI_FORMAT_BC3_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC3_UNORM_SRGB ] = DXGI_FORMAT_BC3_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_BC4_TYPELESS ] = DXGI_FORMAT_BC4_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC4_UNORM ] = DXGI_FORMAT_BC4_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC4_SNORM ] = DXGI_FORMAT_BC4_SNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC5_TYPELESS ] = DXGI_FORMAT_BC5_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC5_UNORM ] = DXGI_FORMAT_BC5_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC5_SNORM ] = DXGI_FORMAT_BC5_SNORM; - - FmtToDXGIFmtMap[ TEX_FORMAT_B5G6R5_UNORM ] = DXGI_FORMAT_B5G6R5_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_B5G5R5A1_UNORM ] = DXGI_FORMAT_B5G5R5A1_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BGRA8_UNORM ] = DXGI_FORMAT_B8G8R8A8_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BGRX8_UNORM ] = DXGI_FORMAT_B8G8R8X8_UNORM; + LayoutElements_To_D3D_INPUT_ELEMENT_DESCs(LayoutElements, D3D11InputElements); +} - FmtToDXGIFmtMap[ TEX_FORMAT_R10G10B10_XR_BIAS_A2_UNORM ]= DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM; +D3D11_PRIMITIVE_TOPOLOGY TopologyToD3D11Topology(PRIMITIVE_TOPOLOGY Topology) +{ + return TopologyToD3DTopology(Topology); +} - FmtToDXGIFmtMap[ TEX_FORMAT_BGRA8_TYPELESS ] = DXGI_FORMAT_B8G8R8A8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BGRA8_UNORM_SRGB ] = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_BGRX8_TYPELESS ] = DXGI_FORMAT_B8G8R8X8_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BGRX8_UNORM_SRGB ] = DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - FmtToDXGIFmtMap[ TEX_FORMAT_BC6H_TYPELESS ] = DXGI_FORMAT_BC6H_TYPELESS; - FmtToDXGIFmtMap[ TEX_FORMAT_BC6H_UF16 ] = DXGI_FORMAT_BC6H_UF16; - FmtToDXGIFmtMap[ TEX_FORMAT_BC6H_SF16 ] = DXGI_FORMAT_BC6H_SF16; - FmtToDXGIFmtMap[ TEX_FORMAT_BC7_TYPELESS ] = DXGI_FORMAT_BC7_TYPELESS ; - FmtToDXGIFmtMap[ TEX_FORMAT_BC7_UNORM ] = DXGI_FORMAT_BC7_UNORM; - FmtToDXGIFmtMap[ TEX_FORMAT_BC7_UNORM_SRGB ] = DXGI_FORMAT_BC7_UNORM_SRGB; - - bFormatMapIntialized = true; - } - if( TexFormat >= TEX_FORMAT_UNKNOWN && TexFormat < TEX_FORMAT_NUM_FORMATS ) - { - auto DXGIFormat = FmtToDXGIFmtMap[TexFormat]; - VERIFY( TexFormat == TEX_FORMAT_UNKNOWN || DXGIFormat != DXGI_FORMAT_UNKNOWN, "Unsupported texture format" ); - if( BindFlags != 0 ) - DXGIFormat = CorrectDXGIFormat( DXGIFormat, BindFlags ); - return DXGIFormat; - } - else - { - UNEXPECTED( "Texture format (", TexFormat, ") is out of allowed range [0, ", TEX_FORMAT_NUM_FORMATS-1, "]" ); - return DXGI_FORMAT_UNKNOWN; - } +void TextureViewDesc_to_D3D11_SRV_DESC(const TextureViewDesc& TexViewDesc, D3D11_SHADER_RESOURCE_VIEW_DESC &D3D11SRVDesc, Uint32 SampleCount) +{ + TextureViewDesc_to_D3D_SRV_DESC(TexViewDesc, D3D11SRVDesc, SampleCount); } -D3D11_FILTER FilterTypeToD3D11Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter) +void TextureViewDesc_to_D3D11_RTV_DESC(const TextureViewDesc& TexViewDesc, D3D11_RENDER_TARGET_VIEW_DESC &D3D11RTVDesc, Uint32 SampleCount) { - switch( MinFilter ) - { - case FILTER_TYPE_POINT: - if( MagFilter == FILTER_TYPE_POINT ) - { - if( MipFilter == FILTER_TYPE_POINT ) - return D3D11_FILTER_MIN_MAG_MIP_POINT; - else if( MipFilter == FILTER_TYPE_LINEAR ) - return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; - } - else if( MagFilter == FILTER_TYPE_LINEAR ) - { - if( MipFilter == FILTER_TYPE_POINT ) - return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; - else if( MipFilter == FILTER_TYPE_LINEAR ) - return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; - } - break; - - case FILTER_TYPE_LINEAR: - if( MagFilter == FILTER_TYPE_POINT ) - { - if( MipFilter == FILTER_TYPE_POINT ) - return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; - else if( MipFilter == FILTER_TYPE_LINEAR ) - return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; - } - else if( MagFilter == FILTER_TYPE_LINEAR ) - { - if( MipFilter == FILTER_TYPE_POINT ) - return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; - else if( MipFilter == FILTER_TYPE_LINEAR ) - return D3D11_FILTER_MIN_MAG_MIP_LINEAR; - } - break; + TextureViewDesc_to_D3D_RTV_DESC(TexViewDesc, D3D11RTVDesc, SampleCount); +} - case FILTER_TYPE_ANISOTROPIC: - VERIFY( MagFilter == FILTER_TYPE_ANISOTROPIC && MipFilter == FILTER_TYPE_ANISOTROPIC, - "For anistropic filtering, all filters must be anisotropic" ); - return D3D11_FILTER_ANISOTROPIC; - break; +void TextureViewDesc_to_D3D11_DSV_DESC(const TextureViewDesc& TexViewDesc, D3D11_DEPTH_STENCIL_VIEW_DESC &D3D11DSVDesc, Uint32 SampleCount) +{ + TextureViewDesc_to_D3D_DSV_DESC(TexViewDesc, D3D11DSVDesc, SampleCount); +} - case FILTER_TYPE_COMPARISON_POINT: - if( MagFilter == FILTER_TYPE_COMPARISON_POINT ) - { - if( MipFilter == FILTER_TYPE_COMPARISON_POINT ) - return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT; - else if( MipFilter == FILTER_TYPE_COMPARISON_LINEAR ) - return D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR; - } - else if( MagFilter == FILTER_TYPE_COMPARISON_LINEAR ) - { - if( MipFilter == FILTER_TYPE_COMPARISON_POINT ) - return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT; - else if( MipFilter == FILTER_TYPE_COMPARISON_LINEAR ) - return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR; - } - break; +void TextureViewDesc_to_D3D11_UAV_DESC(const TextureViewDesc& TexViewDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC &D3D11UAVDesc) +{ + TextureViewDesc_to_D3D_UAV_DESC(TexViewDesc, D3D11UAVDesc); +} - case FILTER_TYPE_COMPARISON_LINEAR: - if( MagFilter == FILTER_TYPE_COMPARISON_POINT ) - { - if( MipFilter == FILTER_TYPE_COMPARISON_POINT ) - return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT; - else if( MipFilter == FILTER_TYPE_COMPARISON_LINEAR ) - return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR; - } - else if( MagFilter == FILTER_TYPE_COMPARISON_LINEAR ) - { - if( MipFilter == FILTER_TYPE_COMPARISON_POINT ) - return D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - else if( MipFilter == FILTER_TYPE_COMPARISON_LINEAR ) - return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; - } - break; - case FILTER_TYPE_COMPARISON_ANISOTROPIC: - VERIFY( MagFilter == FILTER_TYPE_COMPARISON_ANISOTROPIC && MipFilter == FILTER_TYPE_COMPARISON_ANISOTROPIC, - "For comparison anistropic filtering, all filters must be anisotropic" ); - return D3D11_FILTER_COMPARISON_ANISOTROPIC; - break; - } - UNEXPECTED( "Unsupported filter combination" ); - return D3D11_FILTER_MIN_MAG_MIP_POINT; +void BufferViewDesc_to_D3D11_SRV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& SRVDesc, D3D11_SHADER_RESOURCE_VIEW_DESC &D3D11SRVDesc) +{ + BufferViewDesc_to_D3D_SRV_DESC(BuffDesc, SRVDesc, D3D11SRVDesc); } -D3D11_STENCIL_OP StencilOpToD3D11StencilOp( STENCIL_OP StencilOp ) +void BufferViewDesc_to_D3D11_UAV_DESC(const BufferDesc &BuffDesc, const BufferViewDesc& UAVDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC &D3D11UAVDesc) { - static bool bIsInit = false; - static D3D11_STENCIL_OP StOp2D3D11StOpMap[STENCIL_OP_NUM_OPS] = {}; - if( !bIsInit ) - { - StOp2D3D11StOpMap[ STENCIL_OP_KEEP ] = D3D11_STENCIL_OP_KEEP; - StOp2D3D11StOpMap[ STENCIL_OP_ZERO ] = D3D11_STENCIL_OP_ZERO; - StOp2D3D11StOpMap[ STENCIL_OP_REPLACE ] = D3D11_STENCIL_OP_REPLACE; - StOp2D3D11StOpMap[ STENCIL_OP_INCR_SAT ] = D3D11_STENCIL_OP_INCR_SAT; - StOp2D3D11StOpMap[ STENCIL_OP_DECR_SAT ] = D3D11_STENCIL_OP_DECR_SAT; - StOp2D3D11StOpMap[ STENCIL_OP_INVERT ] = D3D11_STENCIL_OP_INVERT; - StOp2D3D11StOpMap[ STENCIL_OP_INCR_WRAP] = D3D11_STENCIL_OP_INCR; - StOp2D3D11StOpMap[ STENCIL_OP_DECR_WRAP] = D3D11_STENCIL_OP_DECR; - - bIsInit = true; - } - - if( StencilOp > STENCIL_OP_UNDEFINED && StencilOp < STENCIL_OP_NUM_OPS ) - { - auto D3D11StencilOp = StOp2D3D11StOpMap[StencilOp]; - VERIFY( D3D11StencilOp != 0, "Unexpected stencil op" ); - return D3D11StencilOp; - } - else - { - UNEXPECTED( "Stencil operation (", StencilOp, ") is out of allowed range [1, ", STENCIL_OP_NUM_OPS - 1, "]" ) - return static_cast(0); - } + BufferViewDesc_to_D3D_UAV_DESC(BuffDesc, UAVDesc, D3D11UAVDesc); + D3D11UAVDesc.Buffer.Flags = 0; // D3D11_BUFFER_UAV_FLAG_RAW, D3D11_BUFFER_UAV_FLAG_APPEND, D3D11_BUFFER_UAV_FLAG_COUNTER } - } diff --git a/Graphics/GraphicsEngineD3D11/src/DLLMain.cpp b/Graphics/GraphicsEngineD3D11/src/DLLMain.cpp index 373d1570..fff890c0 100644 --- a/Graphics/GraphicsEngineD3D11/src/DLLMain.cpp +++ b/Graphics/GraphicsEngineD3D11/src/DLLMain.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Graphics/GraphicsEngineD3D11/src/DSStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/DSStateD3D11Impl.cpp deleted file mode 100644 index 218664c1..00000000 --- a/Graphics/GraphicsEngineD3D11/src/DSStateD3D11Impl.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#include "pch.h" -#include "DSStateD3D11Impl.h" -#include "RenderDeviceD3D11Impl.h" - -namespace Diligent -{ - -D3D11_DEPTH_STENCILOP_DESC StencilOpDesc2D3D11StencilOpDesc(const StencilOpDesc &StOpDesc) -{ - D3D11_DEPTH_STENCILOP_DESC D3D11StOpDesc; - D3D11StOpDesc.StencilFailOp = StencilOpToD3D11StencilOp( StOpDesc.StencilFailOp ); - D3D11StOpDesc.StencilDepthFailOp = StencilOpToD3D11StencilOp( StOpDesc.StencilDepthFailOp ); - D3D11StOpDesc.StencilPassOp = StencilOpToD3D11StencilOp( StOpDesc.StencilPassOp ); - D3D11StOpDesc.StencilFunc = ComparisonFuncToD3D11ComparisonFunc( StOpDesc.StencilFunc ); - return D3D11StOpDesc; -} - -DSStateD3D11Impl::DSStateD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const DepthStencilStateDesc& DepthStencilStateDesc) : - TDepthStencilStateBase(pRenderDeviceD3D11, DepthStencilStateDesc) -{ - D3D11_DEPTH_STENCIL_DESC D3D11DSSDesc; - D3D11DSSDesc.DepthEnable = DepthStencilStateDesc.DepthEnable ? TRUE : FALSE; - D3D11DSSDesc.DepthWriteMask = DepthStencilStateDesc.DepthWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; - D3D11DSSDesc.DepthFunc = ComparisonFuncToD3D11ComparisonFunc( DepthStencilStateDesc.DepthFunc ); - D3D11DSSDesc.StencilEnable = DepthStencilStateDesc.StencilEnable ? TRUE : FALSE; - D3D11DSSDesc.StencilReadMask = DepthStencilStateDesc.StencilReadMask; - D3D11DSSDesc.StencilWriteMask = DepthStencilStateDesc.StencilWriteMask; - D3D11DSSDesc.FrontFace = StencilOpDesc2D3D11StencilOpDesc( DepthStencilStateDesc.FrontFace ); - D3D11DSSDesc.BackFace = StencilOpDesc2D3D11StencilOpDesc( DepthStencilStateDesc.BackFace ); - - auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); - CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateDepthStencilState( &D3D11DSSDesc, &m_pd3d11DepthStencilState ), - "Failed to create D3D11 depth stencil state" ); -} - -DSStateD3D11Impl::~DSStateD3D11Impl() -{ - -} - -IMPLEMENT_QUERY_INTERFACE( DSStateD3D11Impl, IID_DepthStencilStateD3D11, TDepthStencilStateBase ) - -} diff --git a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp index a6e14dd5..69514bf0 100644 --- a/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/DeviceContextD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ #include "pch.h" #include "DeviceContextD3D11Impl.h" #include "BufferD3D11Impl.h" -#include "VertexDescD3D11Impl.h" #include "ShaderD3D11Impl.h" #include "Texture1D_D3D11.h" #include "Texture2D_D3D11.h" @@ -32,209 +31,86 @@ #include "SamplerD3D11Impl.h" #include "D3D11TypeConversions.h" #include "TextureViewD3D11Impl.h" -#include "DSStateD3D11Impl.h" -#include "RasterizerStateD3D11Impl.h" -#include "BlendStateD3D11Impl.h" -#include "DSStateD3D11Impl.h" +#include "PipelineStateD3D11Impl.h" #include "SwapChainD3D11Impl.h" #include "D3D11DebugUtilities.h" +#include "ShaderResourceBindingD3D11Impl.h" +#include "EngineD3D11Attribs.h" +#include "EngineD3D11Defines.h" +#include "CommandListD3D11Impl.h" using namespace Diligent; namespace Diligent { - - DeviceContextD3D11Impl::DeviceContextD3D11Impl( IRenderDevice *pDevice, ID3D11DeviceContext *pd3d11DeviceContext ) : - TDeviceContextBase(pDevice), + DeviceContextD3D11Impl::DeviceContextD3D11Impl( IMemoryAllocator &Allocator, IRenderDevice *pDevice, ID3D11DeviceContext *pd3d11DeviceContext, const struct EngineD3D11Attribs &EngineAttribs, bool bIsDeferred ) : + TDeviceContextBase(Allocator, pDevice, bIsDeferred), m_pd3d11DeviceContext( pd3d11DeviceContext ), - m_BoundD3D11IndexFmt(DXGI_FORMAT_UNKNOWN), - m_BoundD3D11IndexDataStartOffset(0) + m_CommittedIBFormat(VT_UNDEFINED), + m_CommittedD3D11IndexDataStartOffset(0), + m_DebugFlags(EngineAttribs.DebugFlags), + m_NumCommittedD3D11VBs(0), + m_CmdListAllocator(GetRawAllocator(), sizeof(CommandListD3D11Impl), 64 ) { - for( int ShaderType = 0; ShaderType < NumShaderTypes; ++ShaderType ) - { - m_BoundCBs [ShaderType].reserve( D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ); // 14 - m_BoundD3D11CBs[ShaderType].reserve( D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ); // 14 - - m_BoundSamplers [ShaderType].reserve( D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT );// 16 - m_BoundD3D11Samplers[ShaderType].reserve( D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT );// 16 - - m_BoundSRVs [ShaderType].reserve( D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );// 128 - m_BoundD3D11SRVs[ShaderType].reserve( D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );// 128 - - m_BoundUAVs [ShaderType].reserve( D3D11_PS_CS_UAV_REGISTER_COUNT );// 8 - m_BoundD3D11UAVs[ShaderType].reserve( D3D11_PS_CS_UAV_REGISTER_COUNT );// 8 - } + memset(m_NumCommittedCBs, 0, sizeof(m_NumCommittedCBs)); + memset(m_NumCommittedSRVs, 0, sizeof(m_NumCommittedSRVs)); + memset(m_NumCommittedSamplers, 0, sizeof(m_NumCommittedSamplers)); + memset(m_NumCommittedUAVs, 0, sizeof(m_NumCommittedUAVs)); + + memset(m_CommittedD3D11CBs, 0, sizeof(m_CommittedD3D11CBs)); + memset(m_CommittedD3D11SRVs, 0, sizeof(m_CommittedD3D11SRVs)); + memset(m_CommittedD3D11Samplers, 0, sizeof(m_CommittedD3D11Samplers)); + memset(m_CommittedD3D11UAVs, 0, sizeof(m_CommittedD3D11UAVs)); + memset(m_CommittedD3D11SRVResources, 0, sizeof(m_CommittedD3D11SRVResources)); + memset(m_CommittedD3D11UAVResources, 0, sizeof(m_CommittedD3D11UAVResources)); + + memset(m_CommittedD3D11VBStrides, 0, sizeof(m_CommittedD3D11VBStrides)); + memset(m_CommittedD3D11VBOffsets, 0, sizeof(m_CommittedD3D11VBOffsets)); } IMPLEMENT_QUERY_INTERFACE( DeviceContextD3D11Impl, IID_DeviceContextD3D11, TDeviceContextBase ) - void DeviceContextD3D11Impl::SetShaders( IShader **ppShaders, Uint32 NumShadersToSet ) + void DeviceContextD3D11Impl::SetPipelineState(IPipelineState *pPipelineState) { - TDeviceContextBase::SetShaders( ppShaders, NumShadersToSet ); - } - - void DeviceContextD3D11Impl::BindShaderResources( IResourceMapping *pResourceMapping, Uint32 Flags ) - { - TDeviceContextBase::BindShaderResources( pResourceMapping, Flags ); - for( auto it = m_pBoundShaders.begin(); it != m_pBoundShaders.end(); ++it ) + TDeviceContextBase::SetPipelineState( pPipelineState ); + auto *pPipelineStateD3D11 = ValidatedCast(pPipelineState); + auto &Desc = pPipelineStateD3D11->GetDesc(); + if (Desc.IsComputePipeline) { - (*it)->BindResources( pResourceMapping, Flags ); - } - } - - - SHADER_TYPE GetShaderTypeFromIndex( Int32 Index ) - { - return static_cast(1 << Index); - } - - Int32 GetShaderTypeIndex( SHADER_TYPE Type ) - { - auto ShaderIndex = 0; - switch( Type ) - { - case SHADER_TYPE_UNKNOWN: ShaderIndex = -1; break; - case SHADER_TYPE_VERTEX: ShaderIndex = 0; break; - case SHADER_TYPE_PIXEL: ShaderIndex = 1; break; - case SHADER_TYPE_GEOMETRY:ShaderIndex = 2; break; - case SHADER_TYPE_HULL: ShaderIndex = 3; break; - case SHADER_TYPE_DOMAIN: ShaderIndex = 4; break; - case SHADER_TYPE_COMPUTE: ShaderIndex = 5; break; - default: UNEXPECTED( "Unexpected shader type (", Type, ")" ); ShaderIndex = -1; - } - VERIFY( Type == GetShaderTypeFromIndex(ShaderIndex), "Incorrect shader type index" ); - return ShaderIndex; - } - - const ID3D11Buffer* GetD3D11Resource( const ShaderD3D11Impl::BoundCB &CB ) { return CB.pd3d11Buff; } - const ID3D11SamplerState* GetD3D11Resource( const ShaderD3D11Impl::BoundSampler &Sampler ){ return Sampler.pd3d11Sampler; } - const ID3D11ShaderResourceView* GetD3D11Resource( const ShaderD3D11Impl::BoundSRV &SRV ) { return SRV.pd3d11View; } - const ID3D11UnorderedAccessView* GetD3D11Resource( const ShaderD3D11Impl::BoundUAV &UAV ) { return UAV.pd3d11View; } - - /// This helper template function facilitates binding different D3D11 resources to the device context - - /// \tparam TD3D11ResourceType - Type of D3D11 resource being bound (ID3D11ShaderResourceView, - /// ID3D11UnorderedAccessView, ID3D11Buffer or ID3D11SamplerState). - /// \tparam TBoundResourceType - Type of the struct describing resources associated with the - /// bound entity (ShaderD3D11Impl::BoundCB, ShaderD3D11Impl::BoundSRV, etc.) - /// \tparam TGetResourcesMethod - Type of the method that is used to get the bound resources array from - /// the shader (such as &ShaderD3D11Impl::GetBoundCBs). - /// \tparam TUnbindProc - Type of the procedure that unbinds the resource from the context - /// (for instance, if resource is set as SRV, it must be unbound from UAV slots) - /// \tparam TD3D11ResourceSetMethod - Type of the method that bounds the new resources to the D3D11 - /// device context - /// \param pShader - Pointer to the shader whose resources are to be bound - /// \param BoundResourcesArr - Pointer to the array of structures describing currently bound - /// shader resources, for each shader stage - /// \param BoundD3D11ResourcesArr - Pointer to the array of currently bound D3D11 - /// shader resources, for each shader stage - /// \param GetResources - Pointer to the method to get array of bound shader resources from the shader - /// \param UnbindProc - Function to perform required unbind steps - /// \param D3D11ResourceSetMethod - Function to set the new D3D11 resources to the D3D11 device context - template - void UpdateBoundResources(ShaderD3D11Impl *pShader, - std::vector BoundResourcesArr[], - std::vector BoundD3D11ResourcesArr[], - TGetResourcesMethod GetResources, - TUnbindProc UnbindProc, - TD3D11ResourceSetMethod D3D11ResourceSetMethod) - { - const auto &NewResources = (pShader->*GetResources)(); - auto NumNewResources = NewResources.size(); - if( NumNewResources == 0 ) - return; - - auto ShaderType = pShader->GetDesc().ShaderType; - auto ShaderInd = GetShaderTypeIndex(ShaderType); - // Get currently bound resources for the shader type - auto &BoundResources = BoundResourcesArr [ShaderInd]; - auto &BoundD3D11Resources = BoundD3D11ResourcesArr[ShaderInd]; - - VERIFY(BoundD3D11Resources.size() == BoundResources.size(), "Inconsistent array sizes") - if( NumNewResources > BoundD3D11Resources.size() ) - BoundD3D11Resources.resize(NumNewResources); - if( NumNewResources > BoundResources.size() ) - BoundResources.resize(NumNewResources); - - // Compute the minimum and the maximum slot numbers of updated D3D11 resources - Int32 MinSlot = std::numeric_limits::max(); - Int32 MaxSlot = std::numeric_limits::min(); - for( Int32 iSlot = 0; iSlot < static_cast(NumNewResources); ++iSlot ) - { - const auto& pNewRes = NewResources [iSlot]; - const auto& pNewD3D11Res = GetD3D11Resource(pNewRes); - if( pNewD3D11Res != nullptr && pNewD3D11Res != BoundD3D11Resources[iSlot] ) + auto *pd3d11CS = pPipelineStateD3D11->GetD3D11ComputeShader(); + if (pd3d11CS == nullptr) { - // Perform the required steps to unbind the resource - UnbindProc( pNewRes ); + LOG_ERROR("Compute shader is not set in the pipeline"); + return; + } - MinSlot = std::min( MinSlot, iSlot ); - MaxSlot = std::max( MaxSlot, iSlot ); - BoundD3D11Resources[iSlot] = const_cast(pNewD3D11Res); - BoundResources[iSlot] = pNewRes; +#define COMMIT_SHADER(SN, ShaderName)\ + { \ + auto *pd3d11Shader = pPipelineStateD3D11->GetD3D11##ShaderName(); \ + if (m_CommittedD3DShaders[SN##Ind] != pd3d11Shader) \ + { \ + m_CommittedD3DShaders[SN##Ind] = pd3d11Shader; \ + m_pd3d11DeviceContext->SN##SetShader(pd3d11Shader, nullptr, 0); \ + } \ } - } - if( MaxSlot >= MinSlot ) + COMMIT_SHADER(CS, ComputeShader); + } + else { - D3D11ResourceSetMethod(ShaderInd, MinSlot, MaxSlot - MinSlot + 1, &BoundD3D11Resources[MinSlot]); + COMMIT_SHADER(VS, VertexShader); + COMMIT_SHADER(PS, PixelShader); + COMMIT_SHADER(GS, GeometryShader); + COMMIT_SHADER(HS, HullShader); + COMMIT_SHADER(DS, DomainShader); +#undef COMMIT_SHADER + + m_pd3d11DeviceContext->OMSetBlendState( pPipelineStateD3D11->GetD3D11BlendState(), m_BlendFactors, Desc.GraphicsPipeline.SampleMask ); + m_pd3d11DeviceContext->RSSetState( pPipelineStateD3D11->GetD3D11RasterizerState() ); + m_pd3d11DeviceContext->OMSetDepthStencilState( pPipelineStateD3D11->GetD3D11DepthStencilState(), m_StencilRef ); + + m_pd3d11DeviceContext->IASetInputLayout(pPipelineStateD3D11->GetD3D11InputLayout()); } - - // Verify that the resource array and the D3D11 resource array are consistent - dbgVerifyResourceArrays( BoundResources, BoundD3D11Resources, pShader ); - } - - /// Template function that facilitates binding D3D11 SRVs, CBs and samplers to the device context - - /// \tparam TD3D11ResourceType - Type of D3D11 resource being bound (ID3D11ShaderResourceView, - /// ID3D11Buffer or ID3D11SamplerState). - /// \tparam TBoundResourceType - Type of the struct describing resources associated with the - /// bound entity (ShaderD3D11Impl::BoundCB, ShaderD3D11Impl::BoundSRV, etc.) - /// \tparam TGetResourcesMethod - Type of the method that is used to get the bound resources array from - /// the shader (such as &ShaderD3D11Impl::GetBoundCBs). - /// \tparam TUnbindProc - Type of the procedure that unbinds the resource from the context - /// (for instance, if resource is set as SRV, it must be unbound from UAV slots) - /// \tparam TSetD3D11Resource - Type of the D3D11 device context method used to set the - /// resource (such as &ID3D11DeviceContext::SetShaderResources) - /// \param pShader - Pointer to the shader whose resources are to be bound - /// \param BoundResourcesArr - Pointer to the array of structures describing currently bound - /// shader resources, for each shader stage - /// \param BoundD3D11ResourcesArr - Pointer to the array of currently bound D3D11 - /// shader resources, for each shader stage - /// \param GetResources - Pointer to the method to get array of bound shader resources from the shader - /// \param UnbindProc - Function to perform required unbind steps - /// \param SetD3D11ResourcesArr - Pointer to the array of device context methods used - /// to set the resource, for every shader stage - /// \param pd3d11DeviceCtx - Device context - template - void UpdateBoundResources(ShaderD3D11Impl *pShader, - std::vector BoundResourcesArr[], - std::vector BoundD3D11ResourcesArr[], - TGetResourcesMethod GetResources, - TUnbindProc UnbindProc, - TSetD3D11Resource SetD3D11ResourcesArr[], - ID3D11DeviceContext *pd3d11DeviceCtx) - { - UpdateBoundResources(pShader, BoundResourcesArr, BoundD3D11ResourcesArr, - GetResources, UnbindProc, - [&](Int32 ShaderInd, UINT MinSlot, UINT NumSlots, TD3D11ResourceType** ppD3D11Resources) - { - auto SetD3D11Resources = SetD3D11ResourcesArr[ShaderInd]; - VERIFY(SetD3D11Resources, "Set D3D11 resource function pointer is null."); - if( SetD3D11Resources ) - { - (pd3d11DeviceCtx->*SetD3D11Resources)(MinSlot, NumSlots, ppD3D11Resources); - } - } - ); } /// Helper macro used to create an array of device context methods to @@ -266,347 +142,583 @@ namespace Diligent &ID3D11DeviceContext::CSSetUnorderedAccessViews }; - void DeviceContextD3D11Impl::SetD3DConstantBuffers( ShaderD3D11Impl *pShader ) - { - UpdateBoundResources(pShader, m_BoundCBs, m_BoundD3D11CBs, - &ShaderD3D11Impl::GetBoundCBs, - [&](const ShaderD3D11Impl::BoundCB &BoundCB) - { - auto *pResource = const_cast(BoundCB.pBuff.RawPtr()); - RefCntAutoPtr pBuff; - pResource->QueryInterface( IID_Buffer, reinterpret_cast( static_cast(&pBuff) ) ); - if( pBuff ) - { - if( pBuff->GetDesc().BindFlags & BIND_UNORDERED_ACCESS ) - UnbindResourceFromUAV( pBuff ); - } - else - { - UNEXPECTED( "Resource \"", pResource->GetDesc().Name, "\" is expected to be a buffer" ) - } - }, - SetCBMethods, - m_pd3d11DeviceContext ); - dbgVerifyContextCBs(pShader->GetDesc().ShaderType); - } - - void DeviceContextD3D11Impl::SetD3DSRVs( ShaderD3D11Impl *pShader ) + template + void DeviceContextD3D11Impl::TransitionAndCommitShaderResources(IPipelineState *pPSO, IShaderResourceBinding *pShaderResourceBinding) { - UpdateBoundResources(pShader, m_BoundSRVs, m_BoundD3D11SRVs, - &ShaderD3D11Impl::GetBoundSRVs, - [&](const ShaderD3D11Impl::BoundSRV &BoundSRV) - { - auto *pResource = const_cast(BoundSRV.pResource.RawPtr()); - RefCntAutoPtr pTexture; - pResource->QueryInterface( IID_Texture, reinterpret_cast( static_cast(&pTexture) ) ); - if( pTexture ) - { - auto BindFlags = pTexture->GetDesc().BindFlags; - if( BindFlags & BIND_UNORDERED_ACCESS ) - UnbindResourceFromUAV(pTexture); - if( BindFlags & BIND_RENDER_TARGET ) - UnbindTextureFromRenderTarget(pTexture); - if( BindFlags & BIND_DEPTH_STENCIL ) - UnbindTextureFromDepthStencil(pTexture); - } - else + static_assert(TransitionResources || CommitResources, "At least one of TransitionResources or CommitResources flags is expected to be true"); + +#ifdef _DEBUG + auto pdbgPipelineStateD3D11 = ValidatedCast( pPSO ); + auto ppdbgShaders = pdbgPipelineStateD3D11->GetShaders(); +#endif + + auto pShaderResBindingD3D11 = ValidatedCast(pShaderResourceBinding); + if(!pShaderResBindingD3D11) + { + auto pPipelineStateD3D11 = ValidatedCast( pPSO ); + pShaderResBindingD3D11 = pPipelineStateD3D11->GetDefaultResourceBinding(); + } +#ifdef _DEBUG + else + { + if (pdbgPipelineStateD3D11 != pShaderResourceBinding->GetPipelineState()) + { + LOG_ERROR_MESSAGE("Shader resource binding does not match Pipeline State"); + return; + } + } +#endif + + if(!pShaderResBindingD3D11->IsStaticResourcesBound()) + pShaderResBindingD3D11->BindStaticShaderResources(); + + auto NumShaders = pShaderResBindingD3D11->GetNumActiveShaders(); + VERIFY(NumShaders == pdbgPipelineStateD3D11->GetNumShaders(), "Number of active shaders in shader resource binding is not consistent with the number of shaders in the pipeline state"); + + for (Uint32 s = 0; s < NumShaders; ++s) + { + auto ShaderTypeInd = pShaderResBindingD3D11->GetActiveShaderTypeIndex(s); +#ifdef _DEBUG + auto *pShaderD3D11 = ValidatedCast(ppdbgShaders[s]); + VERIFY_EXPR( ShaderTypeInd == static_cast(pShaderD3D11->GetShaderTypeIndex()) ); +#endif + + auto &Cache = pShaderResBindingD3D11->GetResourceCache(s); + auto PackedResCounts = Cache.GetPackedCounts(); + + ShaderResourceCacheD3D11::CachedCB* CachedCBs; + ID3D11Buffer** d3d11CBs; + ShaderResourceCacheD3D11::CachedResource* CachedSRVResources; + ID3D11ShaderResourceView** d3d11SRVs; + ShaderResourceCacheD3D11::CachedSampler* CachedSamplers; + ID3D11SamplerState** d3d11Samplers; + ShaderResourceCacheD3D11::CachedResource* CachedUAVResources; + ID3D11UnorderedAccessView** d3d11UAVs; + Cache.GetResourceArrays(CachedCBs, d3d11CBs, CachedSRVResources, d3d11SRVs, CachedSamplers, d3d11Samplers, CachedUAVResources, d3d11UAVs); + +#ifdef VERIFY_SHADER_BINDINGS + { + pShaderResBindingD3D11->GetResourceLayout(s).dbgVerifyBindings(); + // Static resource bindings are verified in BindStaticShaderResources() + } +#endif + + // Transition and commit Constant Buffers + auto NumCBs = ShaderResourceCacheD3D11::UnpackCBCount(PackedResCounts); + if(NumCBs) + { + auto *CommittedD3D11CBs = m_CommittedD3D11CBs[ShaderTypeInd]; + UINT MinSlot = UINT_MAX; + UINT MaxSlot = 0; + for(Uint32 cb=0; cb < NumCBs; ++cb) + { + VERIFY_EXPR(cb < Cache.GetCBCount()); + + if(TransitionResources) + { + auto &CB = CachedCBs[cb]; + if( auto *pBuff = const_cast(CB.pBuff.RawPtr()) ) + { + // WARNING! This code is not thread-safe. If several threads change + // the buffer state, the results will be undefined. + // The solution may be to keep track of the state for each thread + // individually, or not rely on the state and check current context bindings + if(!pBuff->CheckState(D3D11BufferState::ConstantBuffer)) + { + if( pBuff->CheckState(D3D11BufferState::UnorderedAccess) ) { - RefCntAutoPtr pBuffer; - pResource->QueryInterface( IID_Buffer, reinterpret_cast(static_cast(&pBuffer)) ); - if( pBuffer ) - { - if( pBuffer->GetDesc().BindFlags & BIND_UNORDERED_ACCESS ) - UnbindResourceFromUAV( pBuffer ); - } - else - { - UNEXPECTED( "Resource \"", pResource->GetDesc().Name, "\" is expected to be a texture or a buffer." ) - } + UnbindResourceFromUAV( pBuff, d3d11CBs[cb] ); + pBuff->ClearState(D3D11BufferState::UnorderedAccess); } - }, - SetSRVMethods, - m_pd3d11DeviceContext ); - dbgVerifyContextSRVs(pShader->GetDesc().ShaderType); - } + pBuff->AddState(D3D11BufferState::ConstantBuffer); + } + } + } +#ifdef _DEBUG + else + { + VERIFY_EXPR(CommitResources) + auto &CB = CachedCBs[cb]; + if( auto *pBuff = const_cast(CB.pBuff.RawPtr()) ) + { + if (!pBuff->CheckState(D3D11BufferState::ConstantBuffer)) + { + LOG_ERROR_MESSAGE("Buffer \"", pBuff->GetDesc().Name, "\" has not been transitioned to Constant Buffer state. Did you forget to call TransitionResources()?") + } + } + } +#endif - void DeviceContextD3D11Impl::SetD3DSamplers( ShaderD3D11Impl *pShader ) - { - UpdateBoundResources(pShader, m_BoundSamplers, m_BoundD3D11Samplers, - &ShaderD3D11Impl::GetBoundSamplers, - [](const ShaderD3D11Impl::BoundSampler& ){}, // Do nothing - SetSamplerMethods, - m_pd3d11DeviceContext ); - dbgVerifyContextSamplers(pShader->GetDesc().ShaderType); - } + if(CommitResources) + { + bool IsNewCB = CommittedD3D11CBs[cb] != d3d11CBs[cb]; + MinSlot = IsNewCB ? std::min(MinSlot, cb) : MinSlot; + MaxSlot = IsNewCB ? cb : MaxSlot; + CommittedD3D11CBs[cb] = d3d11CBs[cb]; + } + } + + if(CommitResources) + { + if(MinSlot != UINT_MAX) + { + auto SetCBMethod = SetCBMethods[ShaderTypeInd]; + (m_pd3d11DeviceContext->*SetCBMethod)(MinSlot, MaxSlot-MinSlot+1, CommittedD3D11CBs+MinSlot); + m_NumCommittedCBs[ShaderTypeInd] = std::max(m_NumCommittedCBs[ShaderTypeInd], static_cast(NumCBs)); + } - void DeviceContextD3D11Impl::SetD3DUAVs( ShaderD3D11Impl *pShader ) - { - UpdateBoundResources(pShader, m_BoundUAVs, m_BoundD3D11UAVs, - &ShaderD3D11Impl::GetBoundUAVs, - [&](const ShaderD3D11Impl::BoundUAV& BoundUAV) + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedCBs(pShaderD3D11->GetDesc().ShaderType); + } + } + } + + + // Transition and commit Shader Resource Views + auto NumSRVs = ShaderResourceCacheD3D11::UnpackSRVCount(PackedResCounts); + if(NumSRVs) + { + auto *CommittedD3D11SRVs = m_CommittedD3D11SRVs[ShaderTypeInd]; + auto *CommittedD3D11SRVRes = m_CommittedD3D11SRVResources[ShaderTypeInd]; + + UINT MinSlot = UINT_MAX; + UINT MaxSlot = 0; + + for(Uint32 srv=0; srv < NumSRVs; ++srv) + { + VERIFY_EXPR(srv < Cache.GetSRVCount()); + auto &SRVRes = CachedSRVResources[srv]; + // WARNING! This code is not thread-safe. If several threads change + // the resource state, the results will be undefined. + // The solution may be to keep track of the state for each thread + // individually, or not rely on the state and check current context bindings + if( TransitionResources ) + { + if (auto *pTexture = const_cast(SRVRes.pTexture)) + { + if( !pTexture->CheckState(D3D11TextureState::ShaderResource) ) { - auto *pResource = const_cast(BoundUAV.pResource.RawPtr()); - RefCntAutoPtr pTexture; - pResource->QueryInterface( IID_Texture, reinterpret_cast( static_cast(&pTexture) ) ); - if( pTexture ) + if( pTexture->CheckState(D3D11TextureState::UnorderedAccess) ) { - // It is unlikely the texture is not used for input, so do not - // check the bind flags - UnbindTextureFromInput( pTexture ); + UnbindResourceFromUAV(pTexture, SRVRes.pd3d11Resource); + pTexture->ClearState(D3D11TextureState::UnorderedAccess); } - else + if( pTexture->CheckState(D3D11TextureState::RenderTarget) ) + UnbindTextureFromRenderTarget(pTexture); + if( pTexture->CheckState(D3D11TextureState::DepthStencil) ) + UnbindTextureFromDepthStencil(pTexture); + pTexture->ResetState(D3D11TextureState::ShaderResource); + } + } + else if(auto *pBuffer = const_cast(SRVRes.pBuffer)) + { + if( !pBuffer->CheckState(D3D11BufferState::ShaderResource) ) + { + if( pBuffer->CheckState(D3D11BufferState::UnorderedAccess) ) { - RefCntAutoPtr pBuffer; - pResource->QueryInterface( IID_Buffer, reinterpret_cast(static_cast(&pBuffer)) ); - if( pBuffer ) - { - // It is unlikely the buffer is not used for input, so do not - // check the bind flags - UnbindBufferFromInput( pBuffer ); - } - else - { - UNEXPECTED( "Resource \"", pResource->GetDesc().Name, "\" is expected to be a texture or a buffer." ) - } + UnbindResourceFromUAV( pBuffer, SRVRes.pd3d11Resource ); + pBuffer->ClearState(D3D11BufferState::UnorderedAccess); } - }, - [&](Int32 ShaderInd, UINT MinUAVSlot, UINT NumUAVSlots, ID3D11UnorderedAccessView** ppUAVs) + pBuffer->AddState(D3D11BufferState::ShaderResource); + } + } + } +#ifdef _DEBUG + else + { + VERIFY_EXPR(CommitResources) + if (auto *pTexture = const_cast(SRVRes.pTexture)) + { + if( !pTexture->CheckState(D3D11TextureState::ShaderResource) ) { - switch( ShaderInd ) - { - case 0: // SHADER_TYPE_PIXEL: - UNSUPPORTED( "UAVs are not currently implemented in pixel shader" ); - /// \TODO: need to keep track of bound RTVs and provide the render targets here. - /// Also, we need to unbind UAVs appropriatelly. - /// Maybe deffer actual render target binding to the Draw call()? - m_pd3d11DeviceContext->OMSetRenderTargetsAndUnorderedAccessViews( 0, nullptr, nullptr, MinUAVSlot, NumUAVSlots, ppUAVs, nullptr ); - break; - - case 1: //SHADER_TYPE_VERTEX: - case 2: //SHADER_TYPE_GEOMETRY: - case 3: //SHADER_TYPE_DOMAIN: - case 4: //SHADER_TYPE_HULL: - UNSUPPORTED( "UAVs are not currently supported in this type of shader" ); - break; - - case 5: //SHADER_TYPE_COMPUTE: - m_pd3d11DeviceContext->CSSetUnorderedAccessViews( MinUAVSlot, NumUAVSlots, ppUAVs, nullptr ); - break; - - default: UNEXPECTED( "Unknown shader type" ); - } + LOG_ERROR_MESSAGE("Texture \"", pTexture->GetDesc().Name, "\" has not been transitioned to Shader Resource state. Did you forget to call TransitionResources()?") } - ); - dbgVerifyContextUAVs(pShader->GetDesc().ShaderType); - } + } + else if(auto *pBuffer = const_cast(SRVRes.pBuffer)) + { + if( !pBuffer->CheckState(D3D11BufferState::ShaderResource) ) + { + LOG_ERROR_MESSAGE("Texture \"", pBuffer->GetDesc().Name, "\" has not been transitioned to Shader Resource state. Did you forget to call TransitionResources()?") + } + } + } +#endif - template - void DeviceContextD3D11Impl :: SetD3D11ShaderHelper(Uint32 BoundShaderFlags, - ShaderD3D11Impl* NewShaders[], - SHADER_TYPE ShaderType, - TBindShaderMethdType BindShaderMethod) - { - auto ShaderTypeInd = GetShaderTypeIndex( ShaderType ); - auto &BoundD3D11Shader = m_BoundD3DShaders[ShaderTypeInd]; - auto *pShaderD3D11 = NewShaders[ShaderTypeInd]; - if( BoundShaderFlags & ShaderType ) - { - VERIFY( pShaderD3D11 != nullptr, "Shader is null" ); - VERIFY( pShaderD3D11->GetDesc().ShaderType == ShaderType, "Unexpected shader type" ); - if( BoundD3D11Shader != pShaderD3D11->m_pShader ) + if(CommitResources) + { + bool IsNewSRV = CommittedD3D11SRVs[srv] != d3d11SRVs[srv]; + MinSlot = IsNewSRV ? std::min(MinSlot, srv) : MinSlot; + MaxSlot = IsNewSRV ? srv : MaxSlot; + + CommittedD3D11SRVRes[srv] = SRVRes.pd3d11Resource; + CommittedD3D11SRVs[srv] = d3d11SRVs[srv]; + } + } + + if(CommitResources) + { + if(MinSlot != UINT_MAX) + { + auto SetSRVMethod = SetSRVMethods[ShaderTypeInd]; + (m_pd3d11DeviceContext->*SetSRVMethod)(MinSlot, MaxSlot-MinSlot+1, CommittedD3D11SRVs+MinSlot); + m_NumCommittedSRVs[ShaderTypeInd] = std::max(m_NumCommittedSRVs[ShaderTypeInd], static_cast(NumSRVs)); + } + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedSRVs(pShaderD3D11->GetDesc().ShaderType); + } + } + } + + + // Commit samplers (no transitions for samplers) + if(CommitResources) { - BoundD3D11Shader = pShaderD3D11->m_pShader; - RefCntAutoPtr pd3d11Shader; - pShaderD3D11->m_pShader->QueryInterface(__uuidof(TD3D11ShaderType), reinterpret_cast( static_cast(&pd3d11Shader) ) ); - (m_pd3d11DeviceContext->*BindShaderMethod)(pd3d11Shader, nullptr, 0); + auto NumSamplers = ShaderResourceCacheD3D11::UnpackSamplerCount(PackedResCounts); + if(NumSamplers) + { + auto *CommittedD3D11Samplers = m_CommittedD3D11Samplers[ShaderTypeInd]; + UINT MinSlot = std::numeric_limits::max(); + UINT MaxSlot = 0; + for(Uint32 sam=0; sam < NumSamplers; ++sam) + { + VERIFY_EXPR(sam < Cache.GetSamplerCount()); + + bool IsNewSam = CommittedD3D11Samplers[sam] != d3d11Samplers[sam]; + MinSlot = IsNewSam ? std::min(MinSlot, sam) : MinSlot; + MaxSlot = IsNewSam ? sam : MaxSlot; + + CommittedD3D11Samplers[sam] = d3d11Samplers[sam]; + } + + if(MinSlot != UINT_MAX) + { + auto SetSamplerMethod = SetSamplerMethods[ShaderTypeInd]; + (m_pd3d11DeviceContext->*SetSamplerMethod)(MinSlot, MaxSlot-MinSlot+1, CommittedD3D11Samplers+MinSlot); + m_NumCommittedSamplers[ShaderTypeInd] = std::max(m_NumCommittedSamplers[ShaderTypeInd], static_cast(NumSamplers)); + } + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedSamplers(pShaderD3D11->GetDesc().ShaderType); + } + } } - } - else - { - if( BoundD3D11Shader != nullptr ) + + + // Commit Unordered Access Views + auto NumUAVs = ShaderResourceCacheD3D11::UnpackUAVCount(PackedResCounts); + if(NumUAVs) + { + auto *CommittedD3D11UAVs = m_CommittedD3D11UAVs[ShaderTypeInd]; + auto *CommittedD3D11UAVRes = m_CommittedD3D11UAVResources[ShaderTypeInd]; + + UINT MinSlot = UINT_MAX; + UINT MaxSlot = 0; + + for(Uint32 uav=0; uav < NumUAVs; ++uav) + { + VERIFY_EXPR(uav < Cache.GetUAVCount()); + auto &UAVRes = CachedUAVResources[uav]; + // WARNING! This code is not thread-safe. If several threads change + // the resource state, the results will be undefined. + // The solution may be to keep track of the state for each thread + // individually, or not rely on the state and check current context bindings + if(TransitionResources) + { + if ( auto* pTexture = const_cast(UAVRes.pTexture) ) + { + if( !pTexture->CheckState(D3D11TextureState::UnorderedAccess) ) + { + if( pTexture->CheckState(D3D11TextureState::ShaderResource) ) + UnbindTextureFromInput( pTexture, UAVRes.pd3d11Resource ); + pTexture->ResetState(D3D11TextureState::UnorderedAccess); + } + } + else if( auto *pBuffer = const_cast(UAVRes.pBuffer) ) + { + if( !pBuffer->CheckState(D3D11BufferState::UnorderedAccess) ) + { + if( pBuffer->CheckState(D3D11BufferState::AnyInput) ) + UnbindBufferFromInput( pBuffer, UAVRes.pd3d11Resource ); + pBuffer->ResetState(D3D11BufferState::UnorderedAccess); + } + } + } +#ifdef _DEBUG + else + { + if ( auto* pTexture = const_cast(UAVRes.pTexture) ) + { + if( !pTexture->CheckState(D3D11TextureState::UnorderedAccess) ) + { + LOG_ERROR_MESSAGE("Texture \"", pTexture->GetDesc().Name, "\" has not been transitioned to Unordered Access state. Did you forget to call TransitionResources()?") + } + } + else if( auto *pBuffer = const_cast(UAVRes.pBuffer) ) + { + if( !pBuffer->CheckState(D3D11BufferState::UnorderedAccess) ) + { + LOG_ERROR_MESSAGE("Buffer \"", pBuffer->GetDesc().Name, "\" has not been transitioned to Unordered Access state. Did you forget to call TransitionResources()?") + } + } + } +#endif + if(CommitResources) + { + bool IsNewUAV = CommittedD3D11UAVs[uav] != d3d11UAVs[uav]; + MinSlot = IsNewUAV ? std::min(MinSlot, uav) : MinSlot; + MaxSlot = IsNewUAV ? uav : MaxSlot; + + CommittedD3D11UAVRes[uav] = UAVRes.pd3d11Resource; + CommittedD3D11UAVs[uav] = d3d11UAVs[uav]; + } + } + + if(CommitResources) + { + if(MinSlot != UINT_MAX) + { + auto SetUAVMethod = SetUAVMethods[ShaderTypeInd]; + (m_pd3d11DeviceContext->*SetUAVMethod)(MinSlot, MaxSlot-MinSlot+1, CommittedD3D11UAVs+MinSlot, nullptr); + m_NumCommittedUAVs[ShaderTypeInd] = std::max(m_NumCommittedUAVs[ShaderTypeInd], static_cast(NumUAVs)); + } + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedUAVs(pShaderD3D11->GetDesc().ShaderType); + } + } + } + +#ifdef VERIFY_SHADER_BINDINGS + if( CommitResources && m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedShaderResources ) { - BoundD3D11Shader = nullptr; - (m_pd3d11DeviceContext->*BindShaderMethod)(nullptr, nullptr, 0); + // Use full resource layout to verify that all required resources are committed + pShaderD3D11->GetResources()->dbgVerifyCommittedResources( + m_CommittedD3D11CBs[ShaderTypeInd], + m_CommittedD3D11SRVs[ShaderTypeInd], + m_CommittedD3D11SRVResources[ShaderTypeInd], + m_CommittedD3D11Samplers[ShaderTypeInd], + m_CommittedD3D11UAVs[ShaderTypeInd], + m_CommittedD3D11UAVResources[ShaderTypeInd], + Cache); } +#endif } } - void DeviceContextD3D11Impl :: SetD3DShadersAndResources() + void DeviceContextD3D11Impl::TransitionShaderResources(IPipelineState *pPipelineState, IShaderResourceBinding *pShaderResourceBinding) { - Uint32 BoundShaderFlags = 0; - // Set shaders - ShaderD3D11Impl* NewShaders[NumShaderTypes] = {}; - for( auto it = m_pBoundShaders.begin(); it != m_pBoundShaders.end(); ++it ) - { - auto *pCurrShader = it->RawPtr(); - if( pCurrShader ) - { - auto ShaderType = pCurrShader->GetDesc().ShaderType; - auto *pShaderD3D11 = static_cast(pCurrShader); - auto ShaderTypeInd = GetShaderTypeIndex(ShaderType); - NewShaders[ShaderTypeInd] = pShaderD3D11; + TransitionAndCommitShaderResources(pPipelineState, pShaderResourceBinding); + } - if( BoundShaderFlags & ShaderType ) - LOG_ERROR_MESSAGE( "More than one shader of type ", GetShaderTypeLiteralName(ShaderType), " is bound to the context" ) - BoundShaderFlags |= ShaderType; + void DeviceContextD3D11Impl::CommitShaderResources(IShaderResourceBinding *pShaderResourceBinding, Uint32 Flags) + { + if( !DeviceContextBase::CommitShaderResources(pShaderResourceBinding, Flags, 0 /*Dummy*/) ) + return; -#ifdef VERIFY_SHADER_BINDINGS - pShaderD3D11->dbgVerifyBindings(); -#endif + if(Flags & COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES) + TransitionAndCommitShaderResources(m_pPipelineState, pShaderResourceBinding); + else + TransitionAndCommitShaderResources(m_pPipelineState, pShaderResourceBinding); + } - // Set D3D11 shader resources - SetD3DConstantBuffers ( pShaderD3D11 ); - SetD3DSRVs ( pShaderD3D11 ); - SetD3DSamplers ( pShaderD3D11 ); - SetD3DUAVs ( pShaderD3D11 ); - } + void DeviceContextD3D11Impl::SetStencilRef(Uint32 StencilRef) + { + if (TDeviceContextBase::SetStencilRef(StencilRef, 0)) + { + ID3D11DepthStencilState *pd3d11DSS = m_pPipelineState ? ValidatedCast(m_pPipelineState.RawPtr())->GetD3D11DepthStencilState() : nullptr; + m_pd3d11DeviceContext->OMSetDepthStencilState( pd3d11DSS, m_StencilRef ); } - - // There is no need to unbind the compute shader from the context - //if( BoundShaderFlags & SHADER_TYPE_COMPUTE ) - //{ - // LOG_ERROR_MESSAGE( "Bound compute shader will be ignored by the draw command" ) - // BoundShaderFlags &= ~SHADER_TYPE_COMPUTE; - //} + } -#define SET_SHADER(NAME, Name, N) SetD3D11ShaderHelper(BoundShaderFlags, NewShaders, SHADER_TYPE_##NAME, &ID3D11DeviceContext::N##SSetShader ) - // These shaders which are not set will be unbound from the D3D11 device context - SET_SHADER( VERTEX, Vertex, V ); - SET_SHADER( PIXEL, Pixel, P ); - SET_SHADER( GEOMETRY, Geometry, G ); - SET_SHADER( DOMAIN, Domain, D ); - SET_SHADER( HULL, Hull, H ); - // There is no need to unbind the compute shader from the context - //SET_SHADER( COMPUTE, Compute, C ); + void DeviceContextD3D11Impl::SetBlendFactors(const float* pBlendFactors) + { + if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0)) + { + Uint32 SampleMask = 0xFFFFFFFF; + ID3D11BlendState *pd3d11BS = nullptr; + if(m_pPipelineState) + { + SampleMask = m_pPipelineState->GetDesc().GraphicsPipeline.SampleMask; + pd3d11BS = ValidatedCast(m_pPipelineState.RawPtr())->GetD3D11BlendState(); + } + m_pd3d11DeviceContext->OMSetBlendState(pd3d11BS, m_BlendFactors, SampleMask); + } } - void DeviceContextD3D11Impl::SetD3DIndexBuffer(VALUE_TYPE IndexType) + void DeviceContextD3D11Impl::CommitD3D11IndexBuffer(VALUE_TYPE IndexType) { if( !m_pIndexBuffer ) { LOG_ERROR_MESSAGE( "Index buffer is not set up for indexed draw command" ); return; } + BufferD3D11Impl *pBuffD3D11 = static_cast(m_pIndexBuffer.RawPtr()); - DXGI_FORMAT D3D11IndexFmt = DXGI_FORMAT_UNKNOWN; - if( IndexType == VT_UINT32 ) - D3D11IndexFmt = DXGI_FORMAT_R32_UINT; - else if( IndexType == VT_UINT16 ) - D3D11IndexFmt = DXGI_FORMAT_R16_UINT; - else + if( pBuffD3D11->CheckState( D3D11BufferState::UnorderedAccess ) ) { - LOG_ERROR_MESSAGE( "Unsupported index format. Only R16_UINT and R32_UINT are allowed." ); - return; + UnbindResourceFromUAV(pBuffD3D11, pBuffD3D11->m_pd3d11Buffer); + pBuffD3D11->ClearState( D3D11BufferState::UnorderedAccess ); } - if( m_pIndexBuffer->GetDesc().BindFlags & BIND_UNORDERED_ACCESS ) - UnbindResourceFromUAV(m_pIndexBuffer); - if( m_BoundD3D11IndexBuffer != pBuffD3D11->m_pd3d11Buffer || - m_BoundD3D11IndexFmt != D3D11IndexFmt || - m_BoundD3D11IndexDataStartOffset != m_IndexDataStartOffset ) + if( m_CommittedD3D11IndexBuffer != pBuffD3D11->m_pd3d11Buffer || + m_CommittedIBFormat != IndexType || + m_CommittedD3D11IndexDataStartOffset != m_IndexDataStartOffset ) { - m_BoundD3D11IndexBuffer = pBuffD3D11->m_pd3d11Buffer; - m_BoundD3D11IndexFmt = D3D11IndexFmt; - m_BoundD3D11IndexDataStartOffset = m_IndexDataStartOffset; + DXGI_FORMAT D3D11IndexFmt = DXGI_FORMAT_UNKNOWN; + if( IndexType == VT_UINT32 ) + D3D11IndexFmt = DXGI_FORMAT_R32_UINT; + else if( IndexType == VT_UINT16 ) + D3D11IndexFmt = DXGI_FORMAT_R16_UINT; + else + { + LOG_ERROR_MESSAGE( "Unsupported index format. Only R16_UINT and R32_UINT are allowed." ); + return; + } + + m_CommittedD3D11IndexBuffer = pBuffD3D11->m_pd3d11Buffer; + m_CommittedIBFormat = IndexType; + m_CommittedD3D11IndexDataStartOffset = m_IndexDataStartOffset; m_pd3d11DeviceContext->IASetIndexBuffer( pBuffD3D11->m_pd3d11Buffer, D3D11IndexFmt, m_IndexDataStartOffset ); } + + pBuffD3D11->AddState(D3D11BufferState::IndexBuffer); + m_bCommittedD3D11IBUpToDate = true; } - void DeviceContextD3D11Impl::SetD3DVertexBuffers() + void DeviceContextD3D11Impl::CommitD3D11VertexBuffers(PipelineStateD3D11Impl *pPipelineStateD3D11) { - auto &VertexDescSP = m_pVertexDesc; - if( !VertexDescSP ) - { - // There might be no vertex description if, for instance, full screen quad - // is rendered - m_pd3d11DeviceContext->IASetInputLayout( nullptr ); - return; - } - auto* pVertexDescD3D11 = static_cast(VertexDescSP.RawPtr()); - m_pd3d11DeviceContext->IASetInputLayout( pVertexDescD3D11->m_pd3d11InputLayout ); - - ID3D11Buffer *ppD3D11Buffers[MaxBufferSlots] = { nullptr }; - UINT Strides[MaxBufferSlots] = { 0 }; - UINT Offsets[MaxBufferSlots] = { 0 }; - UINT NumBoundBuffers = static_cast(m_VertexStreams.size()); - VERIFY( NumBoundBuffers <= MaxBufferSlots, "Too many buffers are being set" ); - NumBoundBuffers = std::min( NumBoundBuffers, static_cast(MaxBufferSlots) ); - const auto *TightStrides = VertexDescSP->GetTightStrides(); - for( UINT Buff = 0; Buff < NumBoundBuffers; ++Buff ) + VERIFY( m_NumVertexStreams <= MaxBufferSlots, "Too many buffers are being set" ); + UINT NumBuffersToSet = std::max(m_NumVertexStreams, m_NumCommittedD3D11VBs ); + + bool BindVBs = m_NumVertexStreams != m_NumCommittedD3D11VBs; + + const auto *TightStrides = pPipelineStateD3D11->GetTightStrides(); + for( UINT Slot = 0; Slot < m_NumVertexStreams; ++Slot ) { - auto &CurrStream = m_VertexStreams[Buff]; + auto &CurrStream = m_VertexStreams[Slot]; VERIFY( CurrStream.pBuffer, "Attempting to bind a null buffer for rendering" ); - ppD3D11Buffers[Buff] = static_cast(CurrStream.pBuffer.RawPtr())->m_pd3d11Buffer; - Strides[Buff] = CurrStream.Stride ? CurrStream.Stride : TightStrides[Buff]; - Offsets[Buff] = CurrStream.Offset; - if(CurrStream.pBuffer->GetDesc().BindFlags & BIND_UNORDERED_ACCESS) - UnbindResourceFromUAV(CurrStream.pBuffer); - } + auto *pBuffD3D11Impl = ValidatedCast(CurrStream.pBuffer.RawPtr()); + ID3D11Buffer *pd3d11Buffer = pBuffD3D11Impl->m_pd3d11Buffer; + auto Stride = CurrStream.Stride ? CurrStream.Stride : TightStrides[Slot]; + auto Offset = CurrStream.Offset; - UINT NumBuffersToSet = NumBoundBuffers; - bool BindVBs = false; - if( NumBoundBuffers != m_BoundD3D11VertexBuffers.size() ) - { - // If number of currently bound d3d11 buffers is larger than NumBuffersToSet, the - // unused buffers will be unbound - NumBuffersToSet = std::max(NumBuffersToSet, static_cast(m_BoundD3D11VertexBuffers.size()) ); - m_BoundD3D11VertexBuffers.resize(NumBoundBuffers); - m_BoundD3D11VBStrides.resize(NumBoundBuffers); - m_BoundD3D11VBOffsets.resize( NumBoundBuffers ); - BindVBs = true; - } + if(pBuffD3D11Impl->CheckState( D3D11BufferState::UnorderedAccess )) + { + UnbindResourceFromUAV(pBuffD3D11Impl, pd3d11Buffer); + pBuffD3D11Impl->ClearState( D3D11BufferState::UnorderedAccess ); + } - for( UINT Slot = 0; Slot < NumBoundBuffers; ++Slot ) - { - if( m_BoundD3D11VertexBuffers[Slot] != ppD3D11Buffers[Slot] || - m_BoundD3D11VBStrides[Slot] != Strides[Slot] || - m_BoundD3D11VBOffsets[Slot] != Offsets[Slot] ) + // It is safe to perform raw pointer check because device context keeps + // all buffers alive. + if (m_CommittedD3D11VertexBuffers[Slot] != pd3d11Buffer || + m_CommittedD3D11VBStrides[Slot] != Stride || + m_CommittedD3D11VBOffsets[Slot] != Offset) { BindVBs = true; - m_BoundD3D11VertexBuffers[Slot] = ppD3D11Buffers[Slot]; - m_BoundD3D11VBStrides[Slot] = Strides[Slot]; - m_BoundD3D11VBOffsets[Slot] = Offsets[Slot]; + m_CommittedD3D11VertexBuffers[Slot] = pd3d11Buffer; + m_CommittedD3D11VBStrides[Slot] = Stride; + m_CommittedD3D11VBOffsets[Slot] = Offset; + + pBuffD3D11Impl->AddState( D3D11BufferState::VertexBuffer ); } } + // Unbind all buffers at the end + for (Uint32 Slot = m_NumVertexStreams; Slot < m_NumCommittedD3D11VBs; ++Slot) + { + m_CommittedD3D11VertexBuffers[Slot] = nullptr; + m_CommittedD3D11VBStrides[Slot] = 0; + m_CommittedD3D11VBOffsets[Slot] = 0; + } + + m_NumCommittedD3D11VBs = m_NumVertexStreams; + if( BindVBs ) { - m_pd3d11DeviceContext->IASetVertexBuffers( 0, NumBuffersToSet, ppD3D11Buffers, Strides, Offsets ); + m_pd3d11DeviceContext->IASetVertexBuffers( 0, NumBuffersToSet, m_CommittedD3D11VertexBuffers, m_CommittedD3D11VBStrides, m_CommittedD3D11VBOffsets ); } + + m_bCommittedD3D11VBsUpToDate = true; } void DeviceContextD3D11Impl::Draw( DrawAttribs &DrawAttribs ) { - m_LastDrawAttribs = DrawAttribs; +#ifdef _DEBUG + if (!m_pPipelineState) + { + LOG_ERROR("No pipeline state is bound"); + return; + } +#endif - SetD3DShadersAndResources(); - - SetD3DVertexBuffers(); + auto *pPipelineStateD3D11 = ValidatedCast(m_pPipelineState.RawPtr()); +#ifdef _DEBUG + if (pPipelineStateD3D11->GetDesc().IsComputePipeline) + { + LOG_ERROR("No graphics pipeline state is bound"); + return; + } +#endif + + auto *pd3d11InputLayout = pPipelineStateD3D11->GetD3D11InputLayout(); + // It is safe to perform raw pointer comparison as the device context + // keeps bound input layout alive + if( m_CommittedD3D11InputLayout != pd3d11InputLayout ) + { + m_pd3d11DeviceContext->IASetInputLayout( pd3d11InputLayout ); + m_CommittedD3D11InputLayout = pd3d11InputLayout; + } + + if( pd3d11InputLayout != nullptr && !m_bCommittedD3D11VBsUpToDate ) + { + CommitD3D11VertexBuffers(pPipelineStateD3D11); + } if( DrawAttribs.IsIndexed ) { - SetD3DIndexBuffer(DrawAttribs.IndexType); + if( m_CommittedIBFormat != DrawAttribs.IndexType ) + m_bCommittedD3D11IBUpToDate = false; + if(!m_bCommittedD3D11IBUpToDate) + { + CommitD3D11IndexBuffer(DrawAttribs.IndexType); + } } - // Verify bindings after all resources are set - dbgVerifyContextSRVs(); - dbgVerifyContextUAVs(); - dbgVerifyContextSamplers(); - dbgVerifyContextCBs(); - dbgVerifyVertexBuffers(); - dbgVerifyIndexBuffer(); - dbgVerifyShaders(); - - auto D3D11Topology = TopologyToDX11Topology( DrawAttribs.Topology ); - m_pd3d11DeviceContext->IASetPrimitiveTopology( D3D11Topology ); +#ifdef _DEBUG + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + // Verify bindings after all resources are set + dbgVerifyRenderTargetFormats(); + dbgVerifyCommittedSRVs(); + dbgVerifyCommittedUAVs(); + dbgVerifyCommittedSamplers(); + dbgVerifyCommittedCBs(); + dbgVerifyCommittedVertexBuffers(); + dbgVerifyCommittedIndexBuffer(); + dbgVerifyCommittedShaders(); + } +#endif + + if(m_CommittedPrimitiveTopology != DrawAttribs.Topology) + { + m_CommittedPrimitiveTopology = DrawAttribs.Topology; + m_CommittedD3D11PrimTopology = TopologyToD3D11Topology( DrawAttribs.Topology ); + m_pd3d11DeviceContext->IASetPrimitiveTopology( m_CommittedD3D11PrimTopology ); + } if( DrawAttribs.IsIndirect ) { VERIFY( DrawAttribs.pIndirectDrawAttribs, "Indirect draw command attributes buffer is not set" ); auto *pBufferD3D11 = static_cast(DrawAttribs.pIndirectDrawAttribs); - ID3D11Buffer *pd3d11ArgsBuff = pBufferD3D11 ? pBufferD3D11->m_pd3d11Buffer.RawPtr() : nullptr; + ID3D11Buffer *pd3d11ArgsBuff = pBufferD3D11 ? pBufferD3D11->m_pd3d11Buffer : nullptr; if( DrawAttribs.IsIndexed ) m_pd3d11DeviceContext->DrawIndexedInstancedIndirect( pd3d11ArgsBuff, DrawAttribs.IndirectDrawArgsOffset ); else @@ -633,44 +745,26 @@ namespace Diligent void DeviceContextD3D11Impl::DispatchCompute( const DispatchComputeAttribs &DispatchAttrs ) { - bool bCSBound = false; - ShaderD3D11Impl* NewShaders[NumShaderTypes] = {}; - for( auto it = m_pBoundShaders.begin(); it != m_pBoundShaders.end() && !bCSBound; ++it ) + if (!m_pPipelineState) { - auto *pCurrShader = it->RawPtr(); - if( pCurrShader && pCurrShader->GetDesc().ShaderType == SHADER_TYPE_COMPUTE ) - { - bCSBound = true; - auto *pShaderD3D11 = ValidatedCast(pCurrShader); - NewShaders[GetShaderTypeIndex(SHADER_TYPE_COMPUTE)] = pShaderD3D11; - SetD3D11ShaderHelper( SHADER_TYPE_COMPUTE, NewShaders, SHADER_TYPE_COMPUTE, &ID3D11DeviceContext::CSSetShader ); - -#ifdef VERIFY_SHADER_BINDINGS - pShaderD3D11->dbgVerifyBindings(); -#endif - - // Set requried shader resources - SetD3DConstantBuffers ( pShaderD3D11 ); - SetD3DSRVs ( pShaderD3D11 ); - SetD3DSamplers ( pShaderD3D11 ); - SetD3DUAVs ( pShaderD3D11 ); - - break; - } + LOG_ERROR("No pipeline state is bound"); + return; } - - if( !bCSBound ) + if (!m_pPipelineState->GetDesc().IsComputePipeline) { - LOG_ERROR_MESSAGE( "Compute shader is not bound to the pipeline" ); + LOG_ERROR("No compute pipeline state is bound"); return; } - // Verify bindings - dbgVerifyContextSRVs(); - dbgVerifyContextUAVs(); - dbgVerifyContextSamplers(); - dbgVerifyContextCBs(); - dbgVerifyShaders(); + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + // Verify bindings + dbgVerifyCommittedSRVs(); + dbgVerifyCommittedUAVs(); + dbgVerifyCommittedSamplers(); + dbgVerifyCommittedCBs(); + dbgVerifyCommittedShaders(); + } if( DispatchAttrs.pIndirectDispatchAttribs ) { @@ -687,10 +781,11 @@ namespace Diligent ID3D11DepthStencilView *pd3d11DSV = nullptr; if( pView != nullptr ) { +#ifdef _DEBUG const auto& ViewDesc = pView->GetDesc(); VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); - CHECK_DYNAMIC_TYPE( TextureViewD3D11Impl, pView ); - auto *pViewD3D11 = static_cast(pView); +#endif + auto *pViewD3D11 = ValidatedCast(pView); pd3d11DSV = static_cast(pViewD3D11->GetD3D11View()); } else @@ -710,10 +805,11 @@ namespace Diligent ID3D11RenderTargetView *pd3d11RTV = nullptr; if( pView != nullptr ) { +#ifdef _DEBUG const auto& ViewDesc = pView->GetDesc(); VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); - CHECK_DYNAMIC_TYPE( TextureViewD3D11Impl, pView ); - auto *pViewD3D11 = static_cast(pView); +#endif + auto *pViewD3D11 = ValidatedCast(pView); pd3d11RTV = static_cast(pViewD3D11->GetD3D11View()); } else @@ -738,6 +834,7 @@ namespace Diligent void DeviceContextD3D11Impl::SetVertexBuffers( Uint32 StartSlot, Uint32 NumBuffersSet, IBuffer **ppBuffers, Uint32 *pStrides, Uint32 *pOffsets, Uint32 Flags ) { TDeviceContextBase::SetVertexBuffers( StartSlot, NumBuffersSet, ppBuffers, pStrides, pOffsets, Flags ); + m_bCommittedD3D11VBsUpToDate = false; } void DeviceContextD3D11Impl::ClearState() @@ -746,47 +843,10 @@ namespace Diligent } - void DeviceContextD3D11Impl::SetVertexDescription( IVertexDescription *pVertexDesc ) - { - TDeviceContextBase::SetVertexDescription( pVertexDesc ); - } - void DeviceContextD3D11Impl::SetIndexBuffer( IBuffer *pIndexBuffer, Uint32 ByteOffset ) { TDeviceContextBase::SetIndexBuffer( pIndexBuffer, ByteOffset ); - } - - void DeviceContextD3D11Impl::SetDepthStencilState( IDepthStencilState *pDepthStencilState, Uint32 StencilRef ) - { - if( TDeviceContextBase::SetDepthStencilState( pDepthStencilState, StencilRef ) ) - { - CHECK_DYNAMIC_TYPE( DSStateD3D11Impl, pDepthStencilState ); - auto *pDSSD3D11 = static_cast(pDepthStencilState); - auto *pd3d11DSS = pDSSD3D11->GetD3D11DepthStencilState(); - m_pd3d11DeviceContext->OMSetDepthStencilState( pd3d11DSS, StencilRef ); - } - } - - void DeviceContextD3D11Impl::SetRasterizerState( IRasterizerState *pRasterizerState ) - { - if( TDeviceContextBase::SetRasterizerState( pRasterizerState ) ) - { - CHECK_DYNAMIC_TYPE( RasterizerStateD3D11Impl, pRasterizerState ); - auto *pRSD3D11 = static_cast(pRasterizerState); - auto *pd3d11RS = pRSD3D11->GetD3D11RasterizerState(); - m_pd3d11DeviceContext->RSSetState( pd3d11RS ); - } - } - - void DeviceContextD3D11Impl::SetBlendState( IBlendState *pBS, const float* pBlendFactors, Uint32 SampleMask ) - { - if( TDeviceContextBase::SetBlendState( pBS, pBlendFactors, SampleMask ) ) - { - CHECK_DYNAMIC_TYPE( BlendStateD3D11Impl, pBS ); - auto *pBSD3D11 = static_cast(pBS); - auto *pd3d11BS = pBSD3D11->GetD3D11BlendState(); - m_pd3d11DeviceContext->OMSetBlendState( pd3d11BS, m_BlendFactors, SampleMask ); - } + m_bCommittedD3D11IBUpToDate = false; } void DeviceContextD3D11Impl::SetViewports( Uint32 NumViewports, const Viewport *pViewports, Uint32 RTWidth, Uint32 RTHeight ) @@ -798,8 +858,8 @@ namespace Diligent TDeviceContextBase::SetViewports( NumViewports, pViewports, RTWidth, RTHeight ); D3D11_VIEWPORT d3d11Viewports[MaxViewports]; - VERIFY( NumViewports == m_Viewports.size(), "Unexpected number of viewports" ); - for( Uint32 vp = 0; vp < NumViewports; ++vp ) + VERIFY( NumViewports == m_NumViewports, "Unexpected number of viewports" ); + for( Uint32 vp = 0; vp < m_NumViewports; ++vp ) { d3d11Viewports[vp].TopLeftX = m_Viewports[vp].TopLeftX; d3d11Viewports[vp].TopLeftY = m_Viewports[vp].TopLeftY; @@ -822,7 +882,7 @@ namespace Diligent TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight); D3D11_RECT d3d11ScissorRects[MaxScissorRects]; - VERIFY( NumRects == m_ScissorRects.size(), "Unexpected number of scissor rects" ); + VERIFY( NumRects == m_NumScissorRects, "Unexpected number of scissor rects" ); for( Uint32 sr = 0; sr < NumRects; ++sr ) { d3d11ScissorRects[sr].left = m_ScissorRects[sr].left; @@ -839,7 +899,7 @@ namespace Diligent void DeviceContextD3D11Impl::RebindRenderTargets() { const Uint32 MaxD3D11RTs = D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; - Uint32 NumRenderTargets = static_cast( m_pBoundRenderTargets.size() ); + Uint32 NumRenderTargets = m_NumBoundRenderTargets; VERIFY( NumRenderTargets <= MaxD3D11RTs, "D3D11 only allows 8 simultaneous render targets" ); NumRenderTargets = std::min( MaxD3D11RTs, NumRenderTargets ); @@ -878,6 +938,7 @@ namespace Diligent m_pd3d11DeviceContext->OMSetRenderTargets(NumRenderTargets, pd3d11RTs, pd3d11DSV); } + void UnbindView( ID3D11DeviceContext *pContext, TSetShaderResourcesType SetSRVMethod, UINT Slot ) { ID3D11ShaderResourceView *ppNullView[] = { nullptr }; @@ -890,36 +951,37 @@ namespace Diligent (pContext->*SetUAVMethod)(Slot, 1, ppNullView, nullptr); } - /// \tparam TBoundResourceType - Type of the struct describing resources associated with the - /// bound entity (ShaderD3D11Impl::BoundCB, ShaderD3D11Impl::BoundSRV, etc.) - /// \tparam TD3D11ResourceType - Type of the D3D11 resource (ID3D11ShaderResourceView or ID3D11UnorderedAccessView) + /// \tparam TD3D11ResourceViewType - Type of the D3D11 resource view (ID3D11ShaderResourceView or ID3D11UnorderedAccessView) /// \tparam TSetD3D11View - Type of the D3D11 device context method used to set the D3D11 view - /// \param BoundResourcesArr - Pointer to the array of strong references to currently bound + /// \param CommittedResourcesArr - Pointer to the array of strong references to currently bound /// shader resources, for each shader stage - /// \param BoundD3D11ResourcesArr - Pointer to the array of currently bound D3D11 + /// \param CommittedD3D11ResourcesArr - Pointer to the array of currently bound D3D11 /// shader resources, for each shader stage /// \param pResToUnbind - Resource to unbind /// \param SetD3D11ViewMethods - Array of pointers to device context methods used to set the view, /// for every shader stage - template - void DeviceContextD3D11Impl::UnbindResourceView(std::vector BoundResourcesArr[], - std::vector BoundD3D11ResourcesArr[], + template + void DeviceContextD3D11Impl::UnbindResourceView( TD3D11ResourceViewType CommittedD3D11ViewsArr[][NumSlots], + ID3D11Resource* CommittedD3D11ResourcesArr[][NumSlots], + Uint8 NumCommittedResourcesArr[], IDeviceObject *pResToUnbind, + ID3D11Resource *pd3d11ResToUndind, TSetD3D11View SetD3D11ViewMethods[]) { for( Int32 ShaderTypeInd = 0; ShaderTypeInd < NumShaderTypes; ++ShaderTypeInd ) { - auto &BoundResources = BoundResourcesArr[ShaderTypeInd]; - auto &BoundD3D11Views = BoundD3D11ResourcesArr[ShaderTypeInd]; - VERIFY( BoundResources.size() == BoundD3D11Views.size(), "Inconsistent shader resource view array sizes" ); - for( Uint32 Slot = 0; Slot < BoundResources.size(); ++Slot ) + auto *CommittedD3D11Views = CommittedD3D11ViewsArr[ShaderTypeInd]; + auto *CommittedD3D11Resources = CommittedD3D11ResourcesArr[ShaderTypeInd]; + auto &NumCommittedSlots = NumCommittedResourcesArr[ShaderTypeInd]; + + for( Uint32 Slot = 0; Slot < NumCommittedSlots; ++Slot ) { - if( BoundResources[Slot].pResource == pResToUnbind ) + if( CommittedD3D11Resources[Slot] == pd3d11ResToUndind ) { - BoundResources[Slot] = TBoundResourceType(); - BoundD3D11Views[Slot] = nullptr; + CommittedD3D11Resources[Slot] = nullptr; + CommittedD3D11Views[Slot] = nullptr; auto SetViewMethod = SetD3D11ViewMethods[ShaderTypeInd]; UnbindView( m_pd3d11DeviceContext, SetViewMethod, Slot ); @@ -927,118 +989,126 @@ namespace Diligent } // Pop null resources from the end of arrays - while( BoundD3D11Views.size() > 0 && BoundD3D11Views.back() == nullptr ) + while( NumCommittedSlots > 0 && CommittedD3D11Resources[NumCommittedSlots-1] == nullptr ) { - BoundD3D11Views.pop_back(); - VERIFY( BoundResources.back().pResource == nullptr, "Unexpected non-null resource detected" ) - VERIFY( BoundResources.back().pView == nullptr, "Unexpected non-null resource view detected" ) - VERIFY( BoundResources.back().pd3d11View == nullptr, "Unexpected non-null D3D11 resource view detected" ) - BoundResources.pop_back(); + VERIFY( CommittedD3D11Views[NumSlots-1] == nullptr, "Unexpected non-null resource view" ) + --NumCommittedSlots; } - VERIFY(BoundResources.size() == BoundD3D11Views.size(), "Inconsistent array size") } } - void DeviceContextD3D11Impl::UnbindTextureFromInput( ITexture *pTexture ) + void DeviceContextD3D11Impl::UnbindTextureFromInput( TextureBaseD3D11 *pTexture, ID3D11Resource *pd3d11Resource ) { VERIFY( pTexture, "Null texture provided" ) if( !pTexture )return; - UnbindResourceView( m_BoundSRVs, m_BoundD3D11SRVs, pTexture, SetSRVMethods ); + UnbindResourceView( m_CommittedD3D11SRVs, m_CommittedD3D11SRVResources, m_NumCommittedSRVs, pTexture, pd3d11Resource, SetSRVMethods ); + pTexture->ClearState(D3D11TextureState::ShaderResource); } - void DeviceContextD3D11Impl::UnbindBufferFromInput( IBuffer *pBuffer ) + void DeviceContextD3D11Impl::UnbindBufferFromInput( BufferD3D11Impl *pBuffer, ID3D11Resource *pd3d11Buffer ) { VERIFY( pBuffer, "Null buffer provided" ) if( !pBuffer )return; - UnbindResourceView( m_BoundSRVs, m_BoundD3D11SRVs, pBuffer, SetSRVMethods ); + if( pBuffer->CheckState(D3D11BufferState::ShaderResource) ) + { + UnbindResourceView( m_CommittedD3D11SRVs, m_CommittedD3D11SRVResources, m_NumCommittedSRVs, pBuffer, pd3d11Buffer, SetSRVMethods ); + pBuffer->ClearState( D3D11BufferState::ShaderResource ); + } - auto BuffBindFlags = pBuffer->GetDesc().BindFlags; - - if( (BuffBindFlags & BIND_INDEX_BUFFER) && m_BoundD3D11IndexBuffer ) + if( pBuffer->CheckState(D3D11BufferState::IndexBuffer) ) { auto pd3d11IndBuffer = ValidatedCast( pBuffer )->GetD3D11Buffer(); - if( pd3d11IndBuffer == m_BoundD3D11IndexBuffer ) + if( pd3d11IndBuffer == m_CommittedD3D11IndexBuffer ) { // Only unbind D3D11 buffer from the context! // m_pIndexBuffer.Release(); - m_BoundD3D11IndexBuffer.Release(); - m_BoundD3D11IndexFmt = DXGI_FORMAT_UNKNOWN; - m_BoundD3D11IndexDataStartOffset = 0; - m_pd3d11DeviceContext->IASetIndexBuffer( nullptr, m_BoundD3D11IndexFmt, m_BoundD3D11IndexDataStartOffset ); + m_CommittedD3D11IndexBuffer.Release(); + m_CommittedIBFormat = VT_UNDEFINED; + m_CommittedD3D11IndexDataStartOffset = 0; + m_bCommittedD3D11IBUpToDate = false; + m_pd3d11DeviceContext->IASetIndexBuffer( nullptr, DXGI_FORMAT_R32_UINT, m_CommittedD3D11IndexDataStartOffset ); + } + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedIndexBuffer(); } - dbgVerifyIndexBuffer(); + pBuffer->ClearState( D3D11BufferState::IndexBuffer ); } - if( BuffBindFlags & BIND_VERTEX_BUFFER ) + if( pBuffer->CheckState( D3D11BufferState::VertexBuffer ) ) { auto pd3d11VB = ValidatedCast( pBuffer )->GetD3D11Buffer(); - for( Uint32 Slot = 0; Slot < m_BoundD3D11VertexBuffers.size(); ++Slot ) + for( Uint32 Slot = 0; Slot < m_NumCommittedD3D11VBs; ++Slot ) { - auto &BoundD3D11VB = m_BoundD3D11VertexBuffers[Slot]; - if(BoundD3D11VB == pd3d11VB) + auto &CommittedD3D11VB = m_CommittedD3D11VertexBuffers[Slot]; + if(CommittedD3D11VB == pd3d11VB) { // Unbind only D3D11 buffer //*VertStream = VertexStreamInfo(); ID3D11Buffer *ppNullBuffer[] = { nullptr }; const UINT Zero[] = { 0 }; - m_BoundD3D11VertexBuffers[Slot].Release(); - m_BoundD3D11VBStrides[Slot] = 0; - m_BoundD3D11VBOffsets[Slot] = 0; + m_CommittedD3D11VertexBuffers[Slot] = nullptr; + m_CommittedD3D11VBStrides[Slot] = 0; + m_CommittedD3D11VBOffsets[Slot] = 0; + m_bCommittedD3D11VBsUpToDate = false; m_pd3d11DeviceContext->IASetVertexBuffers( Slot, _countof( ppNullBuffer ), ppNullBuffer, Zero, Zero ); } } - dbgVerifyVertexBuffers(); + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedVertexBuffers(); + } + pBuffer->ClearState( D3D11BufferState::VertexBuffer ); } - if( BuffBindFlags & BIND_UNIFORM_BUFFER ) + if( pBuffer->CheckState( D3D11BufferState::ConstantBuffer ) ) { for( Int32 ShaderTypeInd = 0; ShaderTypeInd < NumShaderTypes; ++ShaderTypeInd ) { - auto &BoundCBs = m_BoundCBs[ShaderTypeInd]; - auto &BoundD3D11CBs = m_BoundD3D11CBs[ShaderTypeInd]; - VERIFY( BoundCBs.size() == BoundD3D11CBs.size(), "Inconsistent constant buffer array sizes" ); - auto NumSlots = std::min( BoundCBs.size(), BoundD3D11CBs.size() ); + auto *CommittedD3D11CBs = m_CommittedD3D11CBs[ShaderTypeInd]; + auto NumSlots = m_NumCommittedCBs[ShaderTypeInd]; for( Uint32 Slot = 0; Slot < NumSlots; ++Slot ) { - if( BoundCBs[Slot].pBuff == pBuffer ) + if( CommittedD3D11CBs[Slot] == pd3d11Buffer ) { - BoundCBs[Slot] = ShaderD3D11Impl::BoundCB(); - BoundD3D11CBs[Slot] = nullptr; + CommittedD3D11CBs[Slot] = nullptr; auto SetCBMethod = SetCBMethods[ShaderTypeInd]; ID3D11Buffer *ppNullBuffer[] = { nullptr }; (m_pd3d11DeviceContext->*SetCBMethod)(Slot, 1, ppNullBuffer); } } } - - dbgVerifyContextCBs(); + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedCBs(); + } + pBuffer->ClearState( D3D11BufferState::ConstantBuffer ); } } - void DeviceContextD3D11Impl::UnbindResourceFromUAV( IDeviceObject *pResource ) + void DeviceContextD3D11Impl::UnbindResourceFromUAV( IDeviceObject *pResource, ID3D11Resource *pd3d11Resource ) { VERIFY( pResource, "Null resource provided" ) if( !pResource )return; - UnbindResourceView( m_BoundUAVs, m_BoundD3D11UAVs, pResource, SetUAVMethods ); + UnbindResourceView( m_CommittedD3D11UAVs, m_CommittedD3D11UAVResources, m_NumCommittedUAVs, pResource, pd3d11Resource, SetUAVMethods ); } - void DeviceContextD3D11Impl::UnbindTextureFromRenderTarget( IDeviceObject *pResource ) + void DeviceContextD3D11Impl::UnbindTextureFromRenderTarget( TextureBaseD3D11 *pTexture ) { - VERIFY( pResource, "Null resource provided" ) - if( !pResource )return; - VERIFY(ValidatedCast( pResource ), "Resource is not a texture") + VERIFY( pTexture, "Null resource provided" ) + if( !pTexture )return; bool bRebindRenderTargets = false; - for( auto rt = m_pBoundRenderTargets.begin(); rt != m_pBoundRenderTargets.end(); ++rt ) + for( Uint32 rt = 0; rt < m_NumBoundRenderTargets; ++rt ) { - if( auto pTexView = *rt ) + if( auto pTexView = m_pBoundRenderTargets[rt] ) { - if( pTexView->GetTexture() == pResource ) + if( pTexView->GetTexture() == pTexture ) { - (*rt).Release(); + m_pBoundRenderTargets[rt].Release(); bRebindRenderTargets = true; } } @@ -1046,19 +1116,21 @@ namespace Diligent if( bRebindRenderTargets ) RebindRenderTargets(); + + pTexture->ClearState(D3D11TextureState::RenderTarget); } - void DeviceContextD3D11Impl::UnbindTextureFromDepthStencil(IDeviceObject *pResource) + void DeviceContextD3D11Impl::UnbindTextureFromDepthStencil(TextureBaseD3D11 *pTexD3D11) { - VERIFY( pResource, "Null resource provided" ) - if( !pResource )return; - VERIFY(ValidatedCast( pResource ), "Resource is not a texture") - - if( m_pBoundDepthStencil && m_pBoundDepthStencil->GetTexture() == pResource ) + VERIFY( pTexD3D11, "Null resource provided" ) + if( !pTexD3D11 )return; + + if( m_pBoundDepthStencil && m_pBoundDepthStencil->GetTexture() == pTexD3D11 ) { m_pBoundDepthStencil.Release(); RebindRenderTargets(); } + pTexD3D11->ClearState(D3D11TextureState::DepthStencil); } void DeviceContextD3D11Impl::SetRenderTargets( Uint32 NumRenderTargets, ITextureView *ppRenderTargets[], ITextureView *pDepthStencil ) @@ -1068,10 +1140,16 @@ namespace Diligent for( Uint32 RT = 0; RT < NumRenderTargets; ++RT ) if( ppRenderTargets[RT] ) { - UnbindTextureFromInput( ppRenderTargets[RT]->GetTexture() ); + auto *pTex = ValidatedCast(ppRenderTargets[RT]->GetTexture()); + UnbindTextureFromInput( pTex, pTex->GetD3D11Texture() ); + pTex->ResetState(D3D11TextureState::RenderTarget); } if( pDepthStencil ) - UnbindTextureFromInput( pDepthStencil->GetTexture() ); + { + auto *pTex = ValidatedCast(pDepthStencil->GetTexture()); + UnbindTextureFromInput( pTex, pTex->GetD3D11Texture() ); + pTex->ResetState(D3D11TextureState::DepthStencil); + } RebindRenderTargets(); @@ -1079,7 +1157,7 @@ namespace Diligent SetViewports(1, nullptr, 0, 0); } } - + template void SetD3D11ResourcesHelper(ID3D11DeviceContext *pDeviceCtx, TSetD3D11ResMethodType SetD3D11ResMethod, @@ -1098,18 +1176,16 @@ namespace Diligent (pDeviceCtx->*SetD3D11UAVMethod)(StartSlot, NumSlots, ppUAVs, nullptr); } - template - void ClearStateCacheInternal(std::vector &BoundD3D11Res, - std::vector &BoundRes, + template + void ClearStateCacheInternal(TD3D11ResourceType CommittedD3D11Res[], + Uint8 &NumCommittedResources, TSetD3D11ResMethodType SetD3D11ResMethod, ID3D11DeviceContext *pDeviceCtx) { - if( BoundD3D11Res.size() ) + if( NumCommittedResources > 0) { - memset( BoundD3D11Res.data(), 0, BoundD3D11Res.size() * sizeof( BoundD3D11Res[0] ) ); - SetD3D11ResourcesHelper( pDeviceCtx, SetD3D11ResMethod, 0, static_cast(BoundD3D11Res.size()), BoundD3D11Res.data() ); - BoundD3D11Res.clear(); - BoundRes.clear(); + memset( CommittedD3D11Res, 0, NumCommittedResources * sizeof( CommittedD3D11Res[0] ) ); + SetD3D11ResourcesHelper( pDeviceCtx, SetD3D11ResMethod, 0, NumCommittedResources, CommittedD3D11Res ); } } @@ -1117,26 +1193,197 @@ namespace Diligent { for( int ShaderType = 0; ShaderType < NumShaderTypes; ++ShaderType ) { - ClearStateCacheInternal( m_BoundD3D11CBs [ShaderType], m_BoundCBs [ShaderType], SetCBMethods[ShaderType], m_pd3d11DeviceContext ); - ClearStateCacheInternal( m_BoundD3D11SRVs [ShaderType], m_BoundSRVs [ShaderType], SetSRVMethods[ShaderType], m_pd3d11DeviceContext ); - ClearStateCacheInternal( m_BoundD3D11Samplers[ShaderType], m_BoundSamplers[ShaderType], SetSamplerMethods[ShaderType], m_pd3d11DeviceContext ); - ClearStateCacheInternal( m_BoundD3D11UAVs [ShaderType], m_BoundUAVs [ShaderType], SetUAVMethods[ShaderType], m_pd3d11DeviceContext ); + ClearStateCacheInternal( m_CommittedD3D11CBs [ShaderType], m_NumCommittedCBs [ShaderType], SetCBMethods[ShaderType], m_pd3d11DeviceContext ); + ClearStateCacheInternal( m_CommittedD3D11SRVs [ShaderType], m_NumCommittedSRVs [ShaderType], SetSRVMethods[ShaderType], m_pd3d11DeviceContext ); + ClearStateCacheInternal( m_CommittedD3D11Samplers[ShaderType], m_NumCommittedSamplers[ShaderType], SetSamplerMethods[ShaderType], m_pd3d11DeviceContext ); + ClearStateCacheInternal( m_CommittedD3D11UAVs [ShaderType], m_NumCommittedUAVs [ShaderType], SetUAVMethods[ShaderType], m_pd3d11DeviceContext ); + memset(m_CommittedD3D11SRVResources[ShaderType], 0, sizeof(m_CommittedD3D11SRVResources[ShaderType][0])*m_NumCommittedSRVs[ShaderType] ); + memset(m_CommittedD3D11UAVResources[ShaderType], 0, sizeof(m_CommittedD3D11UAVResources[ShaderType][0])*m_NumCommittedUAVs[ShaderType] ); + m_NumCommittedCBs[ShaderType] = 0; + m_NumCommittedSRVs[ShaderType] = 0; + m_NumCommittedSamplers[ShaderType] = 0; + m_NumCommittedUAVs[ShaderType] = 0; + } + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + dbgVerifyCommittedSRVs(); + dbgVerifyCommittedUAVs(); + dbgVerifyCommittedSamplers(); + dbgVerifyCommittedCBs(); } - dbgVerifyContextSRVs(); - dbgVerifyContextUAVs(); - dbgVerifyContextSamplers(); - dbgVerifyContextCBs(); - // We do not unbind vertex buffers and index buffer as this can explicitly // be done by the user } + + void DeviceContextD3D11Impl::FinishCommandList(ICommandList **ppCommandList) + { + CComPtr pd3d11CmdList; + m_pd3d11DeviceContext->FinishCommandList( + FALSE, // A Boolean flag that determines whether the runtime saves deferred context state before it + // executes FinishCommandList and restores it afterwards. + // * TRUE indicates that the runtime needs to save and restore the state. + // * FALSE indicates that the runtime will not save or restore any state. + // In this case, the deferred context will return to its default state + // after the call to FinishCommandList() completes as if + // ID3D11DeviceContext::ClearState() was called. + &pd3d11CmdList); + + CommandListD3D11Impl *pCmdListD3D11( NEW(m_CmdListAllocator, "CommandListD3D11Impl instance", CommandListD3D11Impl, m_pDevice, pd3d11CmdList) ); + pCmdListD3D11->QueryInterface( IID_CommandList, reinterpret_cast(ppCommandList) ); + + // Device context is now in default state + ClearStateCache(); + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + // Verify bindings + dbgVerifyCommittedSRVs(); + dbgVerifyCommittedUAVs(); + dbgVerifyCommittedSamplers(); + dbgVerifyCommittedCBs(); + dbgVerifyCommittedVertexBuffers(); + dbgVerifyCommittedIndexBuffer(); + dbgVerifyCommittedShaders(); + } + } + + void DeviceContextD3D11Impl::ExecuteCommandList(ICommandList *pCommandList) + { + if (m_bIsDeferred) + { + LOG_ERROR("Only immediate context can execute command list"); + return; + } + + CommandListD3D11Impl* pCmdListD3D11 = ValidatedCast(pCommandList); + auto *pd3d11CmdList = pCmdListD3D11->GetD3D11CommandList(); + m_pd3d11DeviceContext->ExecuteCommandList(pd3d11CmdList, + FALSE // A Boolean flag that determines whether the target context state is + // saved prior to and restored after the execution of a command list. + // * TRUE indicates that the runtime needs to save and restore the state. + // * FALSE indicate that no state shall be saved or restored, which causes the + // target context to return to its default state after the command list executes as if + // ID3D11DeviceContext::ClearState() was called. + ); + + // Device context is now in default state + ClearStateCache(); + + if(m_DebugFlags & (Uint32)EngineD3D11DebugFlags::VerifyCommittedResourceRelevance) + { + // Verify bindings + dbgVerifyCommittedSRVs(); + dbgVerifyCommittedUAVs(); + dbgVerifyCommittedSamplers(); + dbgVerifyCommittedCBs(); + dbgVerifyCommittedVertexBuffers(); + dbgVerifyCommittedIndexBuffer(); + dbgVerifyCommittedShaders(); + } + } + + void DeviceContextD3D11Impl::ClearStateCache() + { + TDeviceContextBase::ClearStateCache(); + + for( int ShaderType = 0; ShaderType < NumShaderTypes; ++ShaderType ) + { + memset(m_CommittedD3D11CBs [ShaderType], 0, sizeof(m_CommittedD3D11CBs [ShaderType][0])*m_NumCommittedCBs [ShaderType] ); + memset(m_CommittedD3D11SRVs [ShaderType], 0, sizeof(m_CommittedD3D11SRVs [ShaderType][0])*m_NumCommittedSRVs [ShaderType] ); + memset(m_CommittedD3D11Samplers[ShaderType], 0, sizeof(m_CommittedD3D11Samplers[ShaderType][0])*m_NumCommittedSamplers[ShaderType] ); + memset(m_CommittedD3D11UAVs [ShaderType], 0, sizeof(m_CommittedD3D11UAVs [ShaderType][0])*m_NumCommittedUAVs [ShaderType] ); + memset(m_CommittedD3D11SRVResources[ShaderType], 0, sizeof(m_CommittedD3D11SRVResources[ShaderType][0])*m_NumCommittedSRVs[ShaderType] ); + memset(m_CommittedD3D11UAVResources[ShaderType], 0, sizeof(m_CommittedD3D11UAVResources[ShaderType][0])*m_NumCommittedUAVs[ShaderType] ); + + m_NumCommittedCBs [ShaderType] = 0; + m_NumCommittedSRVs [ShaderType] = 0; + m_NumCommittedSamplers[ShaderType] = 0; + m_NumCommittedUAVs [ShaderType] = 0; + + m_CommittedD3DShaders[ShaderType].Release(); + } + + for(Uint32 vb=0; vb < m_NumCommittedD3D11VBs; ++vb) + { + m_CommittedD3D11VertexBuffers[vb] = nullptr; + m_CommittedD3D11VBStrides [vb] = 0; + m_CommittedD3D11VBOffsets [vb] = 0; + } + m_NumCommittedD3D11VBs = 0; + m_bCommittedD3D11VBsUpToDate = false; + + m_CommittedD3D11InputLayout = nullptr; + + m_CommittedD3D11IndexBuffer.Release(); + m_CommittedIBFormat = VT_UNDEFINED; + m_CommittedD3D11IndexDataStartOffset = 0; + m_bCommittedD3D11IBUpToDate = false; + + m_CommittedD3D11PrimTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; + m_CommittedPrimitiveTopology = PRIMITIVE_TOPOLOGY_UNDEFINED; + } + #ifdef VERIFY_CONTEXT_BINDINGS + void DeviceContextD3D11Impl::dbgVerifyRenderTargetFormats() + { + if (!m_pPipelineState) + { + LOG_ERROR("No pipeline state is bound"); + return; + } + + TEXTURE_FORMAT BoundRTVFormats[8] = {TEX_FORMAT_UNKNOWN}; + TEXTURE_FORMAT BoundDSVFormat = TEX_FORMAT_UNKNOWN; + Uint32 NumBoundRTVs = 0; + if (m_NumBoundRenderTargets == 0 && m_pBoundDepthStencil == nullptr) + { + BoundRTVFormats[0] = m_pSwapChain->GetDesc().ColorBufferFormat; + BoundDSVFormat = m_pSwapChain->GetDesc().DepthBufferFormat; + NumBoundRTVs = 1; + } + else + { + NumBoundRTVs = m_NumBoundRenderTargets; + for (Uint32 rt = 0; rt < NumBoundRTVs; ++rt) + { + if (auto pRT = m_pBoundRenderTargets[rt]) + BoundRTVFormats[rt] = pRT->GetDesc().Format; + else + BoundRTVFormats[rt] = TEX_FORMAT_UNKNOWN; + } + + BoundDSVFormat = m_pBoundDepthStencil ? m_pBoundDepthStencil->GetDesc().Format : TEX_FORMAT_UNKNOWN; + } + + const auto &PSODesc = m_pPipelineState->GetDesc(); + const auto &GraphicsPipeline = PSODesc.GraphicsPipeline; + if (/*GraphicsPipeline.NumRenderTargets != 0 && */GraphicsPipeline.NumRenderTargets != NumBoundRTVs) + { + LOG_WARNING_MESSAGE("Number of currently bound render targets (", NumBoundRTVs, ") does not match the number of outputs specified by the PSO \"", PSODesc.Name, "\" (", GraphicsPipeline.NumRenderTargets, "). This is OK on D3D11 device, but will most likely be an issue on D3D12." ); + } + + if (GraphicsPipeline.DepthStencilDesc.DepthEnable && BoundDSVFormat != GraphicsPipeline.DSVFormat) + { + LOG_WARNING_MESSAGE("Currently bound depth-stencil buffer format (", GetTextureFormatAttribs(BoundDSVFormat).Name, ") does not match the DSV format specified by the PSO \"", PSODesc.Name, "\" (", GetTextureFormatAttribs(GraphicsPipeline.DSVFormat).Name, "). This is OK on D3D11 device, but will most likely be an issue on D3D12." ); + } + + for (Uint32 rt = 0; rt < NumBoundRTVs; ++rt) + { + auto BoundFmt = BoundRTVFormats[rt]; + auto PSOFmt = GraphicsPipeline.RTVFormats[rt]; + if (BoundFmt != PSOFmt) + { + LOG_WARNING_MESSAGE("Render target bound to slot ", rt, " (", GetTextureFormatAttribs(BoundFmt).Name, ") does not match the RTV format specified by the PSO \"", PSODesc.Name, "\" (", GetTextureFormatAttribs(PSOFmt).Name, "). This is OK on D3D11 device, but will most likely be an issue on D3D12." ); + } + } + } - DEFINE_D3D11CTX_FUNC_POINTERS(GetCBMethods, GetConstantBuffers) - DEFINE_D3D11CTX_FUNC_POINTERS(GetSRVMethods, GetShaderResources) - DEFINE_D3D11CTX_FUNC_POINTERS(GetSamplerMethods, GetSamplers) + DEFINE_D3D11CTX_FUNC_POINTERS(GetCBMethods, GetConstantBuffers) + DEFINE_D3D11CTX_FUNC_POINTERS(GetSRVMethods, GetShaderResources) + DEFINE_D3D11CTX_FUNC_POINTERS(GetSamplerMethods, GetSamplers) typedef decltype (&ID3D11DeviceContext::CSGetUnorderedAccessViews) TGetUnorderedAccessViewsType; static const TGetUnorderedAccessViewsType GetUAVMethods[] = @@ -1154,7 +1401,7 @@ namespace Diligent /// ID3D11UnorderedAccessView, ID3D11Buffer or ID3D11SamplerState). /// \tparam TGetD3D11ResourcesType - Type of the device context method used to get the bound /// resources - /// \param BoundD3D11ResourcesArr - Pointer to the array of currently bound D3D11 + /// \param CommittedD3D11ResourcesArr - Pointer to the array of currently bound D3D11 /// resources, for each shader stage /// \param GetD3D11ResMethods - Pointer to the array of device context methods to get the bound /// resources, for each shader stage @@ -1164,10 +1411,11 @@ namespace Diligent template - void DeviceContextD3D11Impl::dbgVerifyContextResources(std::vector BoundD3D11ResourcesArr[], - TGetD3D11ResourcesType GetD3D11ResMethods[], - const Char *ResourceName, - SHADER_TYPE ShaderType) + void DeviceContextD3D11Impl::dbgVerifyCommittedResources(TD3D11ResourceType CommittedD3D11ResourcesArr[][MaxResources], + Uint8 NumCommittedResourcesArr[], + TGetD3D11ResourcesType GetD3D11ResMethods[], + const Char *ResourceName, + SHADER_TYPE ShaderType) { int iStartInd = 0, iEndInd = NumShaderTypes; if( ShaderType != SHADER_TYPE_UNKNOWN ) @@ -1184,17 +1432,18 @@ namespace Diligent { (m_pd3d11DeviceContext->*GetResMethod)(0, _countof( pctxResources ), pctxResources); } - const auto& BoundResources = BoundD3D11ResourcesArr[iShaderTypeInd]; - auto NumBoundResources = BoundResources.size(); + const auto* CommittedResources = CommittedD3D11ResourcesArr[iShaderTypeInd]; + auto NumCommittedResources = NumCommittedResourcesArr[iShaderTypeInd]; for( Uint32 Slot = 0; Slot < _countof( pctxResources ); ++Slot ) { - if( Slot < NumBoundResources ) + if( Slot < NumCommittedResources ) { - VERIFY( BoundResources[Slot] == pctxResources[Slot], ResourceName, " binding mismatch found for ", ShaderName, " shader type at slot ", Slot ) + VERIFY( CommittedResources[Slot] == pctxResources[Slot], ResourceName, " binding mismatch found for ", ShaderName, " shader type at slot ", Slot ) } else { VERIFY( pctxResources[Slot] == nullptr, ResourceName, " binding mismatch found for ", ShaderName, " shader type at slot ", Slot ) + VERIFY( CommittedResources[Slot] == nullptr, ResourceName, " unexpected non-null resource found for ", ShaderName, " shader type at slot ", Slot ) } if( pctxResources[Slot] ) @@ -1203,62 +1452,104 @@ namespace Diligent } } - void DeviceContextD3D11Impl::dbgVerifyContextSRVs(SHADER_TYPE ShaderType) + template + void DeviceContextD3D11Impl::dbgVerifyViewConsistency(TD3D11ViewType CommittedD3D11ViewArr[][MaxResources], + ID3D11Resource* CommittedD3D11ResourcesArr[][MaxResources], + Uint8 NumCommittedResourcesArr[], + const Char *ResourceName, + SHADER_TYPE ShaderType) + { + int iStartInd = 0, iEndInd = NumShaderTypes; + if( ShaderType != SHADER_TYPE_UNKNOWN ) + { + iStartInd = GetShaderTypeIndex(ShaderType); + iEndInd = iStartInd + 1; + } + for( int iShaderTypeInd = iStartInd; iShaderTypeInd < iEndInd; ++iShaderTypeInd ) + { + const auto ShaderName = GetShaderTypeLiteralName( GetShaderTypeFromIndex(iShaderTypeInd) ); + auto* Views = CommittedD3D11ViewArr[iShaderTypeInd]; + auto* Resources = CommittedD3D11ResourcesArr[iShaderTypeInd]; + auto NumCommittedResources = NumCommittedResourcesArr[iShaderTypeInd]; + for( Uint32 Slot = 0; Slot < NumCommittedResources; ++Slot ) + { + if(Views[Slot] != nullptr) + { + CComPtr pRefRes; + Views[Slot]->GetResource(&pRefRes); + VERIFY( pRefRes == Resources[Slot], "Inconsistent ", ResourceName, " detected at slot ", Slot, " in shader ", ShaderName, ". The resource in the view does not match cached D3D11 resource" ) + } + } + } + } + + void DeviceContextD3D11Impl::dbgVerifyCommittedSRVs(SHADER_TYPE ShaderType) { - dbgVerifyContextResources( m_BoundD3D11SRVs, GetSRVMethods, "SRV", ShaderType ); + dbgVerifyCommittedResources( m_CommittedD3D11SRVs, m_NumCommittedSRVs, GetSRVMethods, "SRV", ShaderType ); + dbgVerifyViewConsistency( m_CommittedD3D11SRVs, m_CommittedD3D11SRVResources, m_NumCommittedSRVs, "SRV", ShaderType ); } - void DeviceContextD3D11Impl::dbgVerifyContextUAVs(SHADER_TYPE ShaderType) + void DeviceContextD3D11Impl::dbgVerifyCommittedUAVs(SHADER_TYPE ShaderType) { - dbgVerifyContextResources( m_BoundD3D11UAVs, GetUAVMethods, "UAV", ShaderType ); + dbgVerifyCommittedResources( m_CommittedD3D11UAVs, m_NumCommittedUAVs, GetUAVMethods, "UAV", ShaderType ); + dbgVerifyViewConsistency( m_CommittedD3D11UAVs, m_CommittedD3D11UAVResources, m_NumCommittedUAVs, "UAV", ShaderType ); } - void DeviceContextD3D11Impl::dbgVerifyContextSamplers(SHADER_TYPE ShaderType) + void DeviceContextD3D11Impl::dbgVerifyCommittedSamplers(SHADER_TYPE ShaderType) { - dbgVerifyContextResources( m_BoundD3D11Samplers, GetSamplerMethods, "Sampler", ShaderType ); + dbgVerifyCommittedResources( m_CommittedD3D11Samplers, m_NumCommittedSamplers, GetSamplerMethods, "Sampler", ShaderType ); } - void DeviceContextD3D11Impl::dbgVerifyContextCBs(SHADER_TYPE ShaderType) + void DeviceContextD3D11Impl::dbgVerifyCommittedCBs(SHADER_TYPE ShaderType) { - dbgVerifyContextResources( m_BoundD3D11CBs, GetCBMethods, "Constant buffer", ShaderType ); + dbgVerifyCommittedResources( m_CommittedD3D11CBs, m_NumCommittedCBs, GetCBMethods, "Constant buffer", ShaderType ); } - void DeviceContextD3D11Impl::dbgVerifyIndexBuffer() + void DeviceContextD3D11Impl::dbgVerifyCommittedIndexBuffer() { RefCntAutoPtr pctxIndexBuffer; DXGI_FORMAT Fmt = DXGI_FORMAT_UNKNOWN; UINT Offset = 0; m_pd3d11DeviceContext->IAGetIndexBuffer( &pctxIndexBuffer, &Fmt, &Offset ); - if( m_BoundD3D11IndexBuffer && !pctxIndexBuffer ) + if( m_CommittedD3D11IndexBuffer && !pctxIndexBuffer ) UNEXPECTED( "D3D11 index buffer is not bound to the context" ); - if( !m_BoundD3D11IndexBuffer && pctxIndexBuffer ) + if( !m_CommittedD3D11IndexBuffer && pctxIndexBuffer ) UNEXPECTED( "Unexpected D3D11 index buffer is bound to the context" ); - if( m_BoundD3D11IndexBuffer && pctxIndexBuffer ) + if( m_CommittedD3D11IndexBuffer && pctxIndexBuffer ) { - VERIFY(m_BoundD3D11IndexBuffer == pctxIndexBuffer, "Index buffer binding mismatch detected"); - VERIFY(m_BoundD3D11IndexFmt == Fmt, "Index buffer format mismatch detected"); - VERIFY(m_BoundD3D11IndexDataStartOffset == Offset, "Index buffer offset mismatch detected"); + VERIFY(m_CommittedD3D11IndexBuffer == pctxIndexBuffer, "Index buffer binding mismatch detected"); + if( Fmt==DXGI_FORMAT_R32_UINT ) + { + VERIFY(m_CommittedIBFormat == VT_UINT32, "Index buffer format mismatch detected") + } + else if( Fmt==DXGI_FORMAT_R16_UINT ) + { + VERIFY(m_CommittedIBFormat == VT_UINT16, "Index buffer format mismatch detected"); + } + VERIFY(m_CommittedD3D11IndexDataStartOffset == Offset, "Index buffer offset mismatch detected"); } } - void DeviceContextD3D11Impl::dbgVerifyVertexBuffers() + void DeviceContextD3D11Impl::dbgVerifyCommittedVertexBuffers() { + CComPtr pInputLayout; + m_pd3d11DeviceContext->IAGetInputLayout(&pInputLayout); + VERIFY( pInputLayout == m_CommittedD3D11InputLayout, "Inconsistent input layout" ); + const Uint32 MaxVBs = D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT; ID3D11Buffer *pVBs[MaxVBs]; UINT Strides[MaxVBs]; UINT Offsets[MaxVBs]; m_pd3d11DeviceContext->IAGetVertexBuffers( 0, MaxVBs, pVBs, Strides, Offsets ); - auto NumBoundVBs = m_BoundD3D11VertexBuffers.size(); - VERIFY(m_BoundD3D11VBStrides.size() == NumBoundVBs, "Unexpected bound D3D11 VB stride array size"); - VERIFY(m_BoundD3D11VBOffsets.size() == NumBoundVBs, "Unexpected bound D3D11 VB offset array size"); + auto NumBoundVBs = m_NumCommittedD3D11VBs; for( Uint32 Slot = 0; Slot < MaxVBs; ++Slot ) { if( Slot < NumBoundVBs ) { - const auto &BoundD3D11VB = m_BoundD3D11VertexBuffers[Slot]; - auto BoundVBStride = m_BoundD3D11VBStrides[Slot]; - auto BoundVBOffset = m_BoundD3D11VBOffsets[Slot]; + const auto &BoundD3D11VB = m_CommittedD3D11VertexBuffers[Slot]; + auto BoundVBStride = m_CommittedD3D11VBStrides[Slot]; + auto BoundVBOffset = m_CommittedD3D11VBOffsets[Slot]; if(BoundD3D11VB && !pVBs[Slot] ) VERIFY( pVBs[Slot] == nullptr, "Missing D3D11 buffer detected at slot ", Slot ); if(!BoundD3D11VB && pVBs[Slot] ) @@ -1281,7 +1572,7 @@ namespace Diligent } template - void dbgVerifyShadersHelper(SHADER_TYPE ShaderType, + void dbgVerifyCommittedShadersHelper(SHADER_TYPE ShaderType, const CComPtr BoundD3DShaders[], ID3D11DeviceContext *pCtx, TGetShaderMethodType GetShaderMethod) @@ -1291,9 +1582,9 @@ namespace Diligent const auto &BoundShader = BoundD3DShaders[GetShaderTypeIndex( ShaderType )]; VERIFY( BoundShader == pctxShader, GetShaderTypeLiteralName(ShaderType), " binding mismatch detected" ); } - void DeviceContextD3D11Impl::dbgVerifyShaders() + void DeviceContextD3D11Impl::dbgVerifyCommittedShaders() { -#define VERIFY_SHADER(NAME, Name, N) dbgVerifyShadersHelper(SHADER_TYPE_##NAME, m_BoundD3DShaders, m_pd3d11DeviceContext, &ID3D11DeviceContext::N##SGetShader ) +#define VERIFY_SHADER(NAME, Name, N) dbgVerifyCommittedShadersHelper(SHADER_TYPE_##NAME, m_CommittedD3DShaders, m_pd3d11DeviceContext, &ID3D11DeviceContext::N##SGetShader ) // These shaders which are not set will be unbound from the D3D11 device context VERIFY_SHADER( VERTEX, Vertex, V ); VERIFY_SHADER( PIXEL, Pixel, P ); @@ -1304,5 +1595,4 @@ namespace Diligent } #endif - } diff --git a/Graphics/GraphicsEngineD3D11/src/GraphicsEngineD3D11.def b/Graphics/GraphicsEngineD3D11/src/GraphicsEngineD3D11.def index 9414b724..11ba3cd0 100644 --- a/Graphics/GraphicsEngineD3D11/src/GraphicsEngineD3D11.def +++ b/Graphics/GraphicsEngineD3D11/src/GraphicsEngineD3D11.def @@ -1,3 +1,3 @@ EXPORTS - CreateDeviceAndImmediateContextD3D11 + CreateDeviceAndContextsD3D11 CreateSwapChainD3D11 \ No newline at end of file diff --git a/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp new file mode 100644 index 00000000..d6d75f41 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp @@ -0,0 +1,222 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" +#include "PipelineStateD3D11Impl.h" +#include "RenderDeviceD3D11Impl.h" +#include "ShaderResourceBindingD3D11Impl.h" +#include "EngineMemory.h" + +namespace Diligent +{ + +PipelineStateD3D11Impl::PipelineStateD3D11Impl(FixedBlockMemoryAllocator &PSOAllocator, RenderDeviceD3D11Impl *pRenderDeviceD3D11, const PipelineStateDesc& PipelineDesc) : + TPipelineStateBase(PSOAllocator, pRenderDeviceD3D11, PipelineDesc), + m_pDefaultShaderResBinding( nullptr, STDDeleter(pRenderDeviceD3D11->GetSRBAllocator()) ), + m_ResourceCacheDataAllocators + { + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity} + }, + m_ShaderResLayoutDataAllocators + { + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity}, + {GetRawAllocator(), PipelineDesc.SRBAllocationGranularity} + }, + m_DummyShaderVar(*this) +{ + if (PipelineDesc.IsComputePipeline) + { + m_pCS = ValidatedCast( PipelineDesc.ComputePipeline.pCS ); + if (m_pCS == nullptr) + { + LOG_ERROR_AND_THROW("Compute shader is null"); + } + + if (m_pCS && m_pCS->GetDesc().ShaderType != SHADER_TYPE_COMPUTE) + { + LOG_ERROR_AND_THROW( GetShaderTypeLiteralName(SHADER_TYPE_COMPUTE), " shader is expeceted while ", GetShaderTypeLiteralName(m_pCS->GetDesc().ShaderType)," provided" ); + } + } + else + { + +#define INIT_SHADER(ShortName, ExpectedType)\ + { \ + m_p##ShortName = ValidatedCast( PipelineDesc.GraphicsPipeline.p##ShortName ); \ + if (m_p##ShortName && m_p##ShortName->GetDesc().ShaderType != ExpectedType) \ + { \ + LOG_ERROR_AND_THROW( GetShaderTypeLiteralName(ExpectedType), " shader is expeceted while ", GetShaderTypeLiteralName(m_p##ShortName->GetDesc().ShaderType)," provided" ); \ + } \ + } + + INIT_SHADER(VS, SHADER_TYPE_VERTEX); + INIT_SHADER(PS, SHADER_TYPE_PIXEL); + INIT_SHADER(GS, SHADER_TYPE_GEOMETRY); + INIT_SHADER(DS, SHADER_TYPE_DOMAIN); + INIT_SHADER(HS, SHADER_TYPE_HULL); +#undef INIT_SHADER + + if (m_pVS == nullptr) + { + LOG_ERROR_AND_THROW("Vertex shader is null"); + } + + auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); + D3D11_BLEND_DESC D3D11BSDesc = {}; + BlendStateDesc_To_D3D11_BLEND_DESC(PipelineDesc.GraphicsPipeline.BlendDesc, D3D11BSDesc); + CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateBlendState( &D3D11BSDesc, &m_pd3d11BlendState ), + "Failed to create D3D11 blend state object" ); + + D3D11_RASTERIZER_DESC D3D11RSDesc = {}; + RasterizerStateDesc_To_D3D11_RASTERIZER_DESC(PipelineDesc.GraphicsPipeline.RasterizerDesc, D3D11RSDesc); + CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateRasterizerState( &D3D11RSDesc, &m_pd3d11RasterizerState ), + "Failed to create D3D11 rasterizer state" ); + + D3D11_DEPTH_STENCIL_DESC D3D11DSSDesc = {}; + DepthStencilStateDesc_To_D3D11_DEPTH_STENCIL_DESC(PipelineDesc.GraphicsPipeline.DepthStencilDesc, D3D11DSSDesc); + CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateDepthStencilState( &D3D11DSSDesc, &m_pd3d11DepthStencilState ), + "Failed to create D3D11 depth stencil state" ); + + + // Create input layout + if( m_LayoutElements.size() > 0 ) + { + std::vector > d311InputElements(STD_ALLOCATOR_RAW_MEM(D3D11_INPUT_ELEMENT_DESC, GetRawAllocator(), "Allocator for vector") ); + LayoutElements_To_D3D11_INPUT_ELEMENT_DESCs(m_LayoutElements, d311InputElements); + + ID3DBlob *pVSByteCode = ValidatedCast(m_pVS.RawPtr())->GetBytecode(); + if( !pVSByteCode ) + LOG_ERROR_AND_THROW( "Vertex Shader byte code does not exist" ); + + CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateInputLayout(d311InputElements.data(), static_cast(d311InputElements.size()), pVSByteCode->GetBufferPointer(), pVSByteCode->GetBufferSize(), &m_pd3d11InputLayout ), + "Failed to create the Direct3D11 input layout"); + } + } + + auto &SRBAllocator = pRenderDeviceD3D11->GetSRBAllocator(); + m_pDefaultShaderResBinding.reset( NEW(SRBAllocator, "ShaderResourceBindingD3D11Impl instance", ShaderResourceBindingD3D11Impl, this, true) ); +} + +PipelineStateD3D11Impl::~PipelineStateD3D11Impl() +{ + +} + +IMPLEMENT_QUERY_INTERFACE( PipelineStateD3D11Impl, IID_PipelineStateD3D11, TPipelineStateBase ) + + +ID3D11BlendState* PipelineStateD3D11Impl::GetD3D11BlendState() +{ + return m_pd3d11BlendState; +} + +ID3D11RasterizerState* PipelineStateD3D11Impl::GetD3D11RasterizerState() +{ + return m_pd3d11RasterizerState; +} + +ID3D11DepthStencilState* PipelineStateD3D11Impl::GetD3D11DepthStencilState() +{ + return m_pd3d11DepthStencilState; +} + +ID3D11InputLayout* PipelineStateD3D11Impl::GetD3D11InputLayout() +{ + return m_pd3d11InputLayout; +} + +void PipelineStateD3D11Impl::BindShaderResources(IResourceMapping *pResourceMapping, Uint32 Flags) +{ + if( m_Desc.IsComputePipeline ) + { + if(m_pCS)m_pCS->BindResources(pResourceMapping, Flags); + } + else + { + if(m_pVS)m_pVS->BindResources(pResourceMapping, Flags); + if(m_pPS)m_pPS->BindResources(pResourceMapping, Flags); + if(m_pGS)m_pGS->BindResources(pResourceMapping, Flags); + if(m_pDS)m_pDS->BindResources(pResourceMapping, Flags); + if(m_pHS)m_pHS->BindResources(pResourceMapping, Flags); + } +} + +void PipelineStateD3D11Impl::CreateShaderResourceBinding(IShaderResourceBinding **ppShaderResourceBinding) +{ + auto *pRenderDeviceD3D11 = ValidatedCast( GetDevice() ); + auto &SRBAllocator = pRenderDeviceD3D11->GetSRBAllocator(); + auto pShaderResBinding = NEW(SRBAllocator, "ShaderResourceBindingD3D11Impl instance", ShaderResourceBindingD3D11Impl, this, false); + pShaderResBinding->QueryInterface(IID_ShaderResourceBinding, reinterpret_cast(static_cast(ppShaderResourceBinding))); +} + + +ID3D11VertexShader* PipelineStateD3D11Impl::GetD3D11VertexShader() +{ + if(!m_pVS)return nullptr; + auto *pVSD3D11 = ValidatedCast(m_pVS.RawPtr()); + return static_cast(pVSD3D11->GetD3D11Shader()); +} + +ID3D11PixelShader* PipelineStateD3D11Impl::GetD3D11PixelShader() +{ + if(!m_pPS)return nullptr; + auto *pPSD3D11 = ValidatedCast(m_pPS.RawPtr()); + return static_cast(pPSD3D11->GetD3D11Shader()); +} + +ID3D11GeometryShader* PipelineStateD3D11Impl::GetD3D11GeometryShader() +{ + if(!m_pGS)return nullptr; + auto *pGSD3D11 = ValidatedCast(m_pGS.RawPtr()); + return static_cast(pGSD3D11->GetD3D11Shader()); +} + +ID3D11DomainShader* PipelineStateD3D11Impl::GetD3D11DomainShader() +{ + if(!m_pDS)return nullptr; + auto *pDSD3D11 = ValidatedCast(m_pDS.RawPtr()); + return static_cast(pDSD3D11->GetD3D11Shader()); +} + +ID3D11HullShader* PipelineStateD3D11Impl::GetD3D11HullShader() +{ + if(!m_pHS)return nullptr; + auto *pHSD3D11 = ValidatedCast(m_pHS.RawPtr()); + return static_cast(pHSD3D11->GetD3D11Shader()); +} + +ID3D11ComputeShader* PipelineStateD3D11Impl::GetD3D11ComputeShader() +{ + if(!m_pCS)return nullptr; + auto *pCSD3D11 = ValidatedCast(m_pCS.RawPtr()); + return static_cast(pCSD3D11->GetD3D11Shader()); +} + +} diff --git a/Graphics/GraphicsEngineD3D11/src/RasterizerStateD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/RasterizerStateD3D11Impl.cpp deleted file mode 100644 index 90bd9092..00000000 --- a/Graphics/GraphicsEngineD3D11/src/RasterizerStateD3D11Impl.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#include "pch.h" -#include "RasterizerStateD3D11Impl.h" -#include "RenderDeviceD3D11Impl.h" - -namespace Diligent -{ - -D3D11_FILL_MODE FillMode2D3D11FillMode(FILL_MODE FillMode) -{ - static bool bIsInit = false; - static D3D11_FILL_MODE D3D11FillModes[FILL_MODE_NUM_MODES] = {}; - if( !bIsInit ) - { - D3D11FillModes[ FILL_MODE_WIREFRAME ] = D3D11_FILL_WIREFRAME; - D3D11FillModes[ FILL_MODE_SOLID ] = D3D11_FILL_SOLID; - - bIsInit = true; - } - if( FILL_MODE_UNDEFINED < FillMode && FillMode < FILL_MODE_NUM_MODES ) - { - auto D3D11FillMode = D3D11FillModes[FillMode]; - VERIFY( D3D11FillMode != 0, "Incorrect fill mode" ); - return D3D11FillModes[FillMode]; - } - else - { - UNEXPECTED( "Incorrect fill mode (", FillMode, ")" ) - return static_cast(0); - } -} - -D3D11_CULL_MODE CullMode2D3D11CullMode( CULL_MODE CullMode ) -{ - static bool bIsInit = false; - static D3D11_CULL_MODE D3D11CullModes[CULL_MODE_NUM_MODES] = {}; - if( !bIsInit ) - { - D3D11CullModes[ CULL_MODE_NONE ] = D3D11_CULL_NONE; - D3D11CullModes[ CULL_MODE_FRONT ] = D3D11_CULL_FRONT; - D3D11CullModes[ CULL_MODE_BACK ] = D3D11_CULL_BACK; - - bIsInit = true; - } - - if( CULL_MODE_UNDEFINED < CullMode && CullMode < CULL_MODE_NUM_MODES ) - { - auto D3D11CullMode = D3D11CullModes[CullMode]; - VERIFY( D3D11CullMode != 0, "Incorrect cull mode" ); - return D3D11CullMode; - } - else - { - UNEXPECTED( "Incorrect cull mode (", CullMode, ")" ) - return static_cast(0); - } -} - -RasterizerStateD3D11Impl::RasterizerStateD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, - const RasterizerStateDesc& RasterizerStateDesc) : - TRasterizerStateBase(pRenderDeviceD3D11, RasterizerStateDesc) -{ - D3D11_RASTERIZER_DESC D3D11RSDesc; - - D3D11RSDesc.FillMode = FillMode2D3D11FillMode(RasterizerStateDesc.FillMode); - D3D11RSDesc.CullMode = CullMode2D3D11CullMode(RasterizerStateDesc.CullMode); - D3D11RSDesc.FrontCounterClockwise = RasterizerStateDesc.FrontCounterClockwise ? TRUE : FALSE; - D3D11RSDesc.DepthBias = RasterizerStateDesc.DepthBias; - D3D11RSDesc.DepthBiasClamp = RasterizerStateDesc.DepthBiasClamp; - D3D11RSDesc.SlopeScaledDepthBias = RasterizerStateDesc.SlopeScaledDepthBias; - D3D11RSDesc.DepthClipEnable = RasterizerStateDesc.DepthClipEnable ? TRUE : FALSE; - D3D11RSDesc.ScissorEnable = RasterizerStateDesc.ScissorEnable ? TRUE : FALSE; - D3D11RSDesc.AntialiasedLineEnable = RasterizerStateDesc.AntialiasedLineEnable ? TRUE : FALSE; - D3D11RSDesc.MultisampleEnable = D3D11RSDesc.AntialiasedLineEnable; - - auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); - CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateRasterizerState( &D3D11RSDesc, &m_pd3d11RasterizerState ), - "Failed to create D3D11 rasterizer state" ); -} - -RasterizerStateD3D11Impl::~RasterizerStateD3D11Impl() -{ - -} - -IMPLEMENT_QUERY_INTERFACE( RasterizerStateD3D11Impl, IID_RasterizerStateD3D11, TRasterizerStateBase ) - -} diff --git a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp index c828493e..867d71d7 100644 --- a/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/RenderDeviceD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ #include "RenderDeviceD3D11Impl.h" #include "DeviceContextD3D11Impl.h" #include "BufferD3D11Impl.h" -#include "VertexDescD3D11Impl.h" #include "ShaderD3D11Impl.h" #include "Texture1D_D3D11.h" #include "Texture2D_D3D11.h" @@ -33,129 +32,25 @@ #include "SamplerD3D11Impl.h" #include "D3D11TypeConversions.h" #include "TextureViewD3D11Impl.h" -#include "DSStateD3D11Impl.h" -#include "RasterizerStateD3D11Impl.h" -#include "BlendStateD3D11Impl.h" +#include "PipelineStateD3D11Impl.h" +#include "ShaderResourceBindingD3D11Impl.h" +#include "EngineMemory.h" namespace Diligent { -RenderDeviceD3D11Impl :: RenderDeviceD3D11Impl(ID3D11Device *pd3d11Device) : +RenderDeviceD3D11Impl :: RenderDeviceD3D11Impl(IMemoryAllocator &RawMemAllocator, const EngineD3D11Attribs& EngineAttribs, ID3D11Device *pd3d11Device, Uint32 NumDeferredContexts) : + TRenderDeviceBase(RawMemAllocator, NumDeferredContexts, sizeof(TextureBaseD3D11), sizeof(TextureViewD3D11Impl), sizeof(BufferD3D11Impl), sizeof(BufferViewD3D11Impl), sizeof(ShaderD3D11Impl), sizeof(SamplerD3D11Impl), sizeof(PipelineStateD3D11Impl), sizeof(ShaderResourceBindingD3D11Impl)), + m_EngineAttribs(EngineAttribs), m_pd3d11Device(pd3d11Device) { - m_DeviceCaps.DevType = DeviceType::DirectX; + m_DeviceCaps.DevType = DeviceType::D3D11; m_DeviceCaps.MajorVersion = 11; m_DeviceCaps.MinorVersion = 0; - m_DeviceCaps.bSeparableProgramSupported = true; - - FlagSupportedTexFormats(); + m_DeviceCaps.bSeparableProgramSupported = True; + m_DeviceCaps.bMultithreadedResourceCreationSupported = True; } -void RenderDeviceD3D11Impl::FlagSupportedTexFormats() -{ -#define FLAG_FORMAT(Fmt, IsSupported)\ - m_TextureFormatsInfo[Fmt].Supported = IsSupported; - - FLAG_FORMAT(TEX_FORMAT_RGBA32_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RGBA32_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA32_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA32_SINT, true); - FLAG_FORMAT(TEX_FORMAT_RGB32_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RGB32_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RGB32_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RGB32_SINT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGBA16_SINT, true); - FLAG_FORMAT(TEX_FORMAT_RG32_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RG32_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RG32_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RG32_SINT, true); - FLAG_FORMAT(TEX_FORMAT_R32G8X24_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_D32_FLOAT_S8X24_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R32_FLOAT_X8X24_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_X32_TYPELESS_G8X24_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RGB10A2_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RGB10A2_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGB10A2_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R11G11B10_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGBA8_SINT, true); - FLAG_FORMAT(TEX_FORMAT_RG16_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RG16_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_RG16_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RG16_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RG16_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_RG16_SINT, true); - FLAG_FORMAT(TEX_FORMAT_R32_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_D32_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_R32_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_R32_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R32_SINT, true); - FLAG_FORMAT(TEX_FORMAT_R24G8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_D24_UNORM_S8_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R24_UNORM_X8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_X24_TYPELESS_G8_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RG8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_RG8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RG8_UINT, true); - FLAG_FORMAT(TEX_FORMAT_RG8_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_RG8_SINT, true); - FLAG_FORMAT(TEX_FORMAT_R16_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_R16_FLOAT, true); - FLAG_FORMAT(TEX_FORMAT_D16_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_R16_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_R16_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R16_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_R16_SINT, true); - FLAG_FORMAT(TEX_FORMAT_R8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_R8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_R8_UINT, true); - FLAG_FORMAT(TEX_FORMAT_R8_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_R8_SINT, true); - FLAG_FORMAT(TEX_FORMAT_A8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_R1_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_RGB9E5_SHAREDEXP, true); - FLAG_FORMAT(TEX_FORMAT_RG8_B8G8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_G8R8_G8B8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC1_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC1_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC1_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_BC2_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC2_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC2_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_BC3_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC3_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC3_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_BC4_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC4_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC4_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC5_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC5_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC5_SNORM, true); - FLAG_FORMAT(TEX_FORMAT_B5G6R5_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_B5G5R5A1_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BGRA8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BGRX8_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BGRA8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BGRA8_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_BGRX8_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BGRX8_UNORM_SRGB, true); - FLAG_FORMAT(TEX_FORMAT_BC6H_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC6H_UF16, true); - FLAG_FORMAT(TEX_FORMAT_BC6H_SF16, true); - FLAG_FORMAT(TEX_FORMAT_BC7_TYPELESS, true); - FLAG_FORMAT(TEX_FORMAT_BC7_UNORM, true); - FLAG_FORMAT(TEX_FORMAT_BC7_UNORM_SRGB, true); -} bool CreateTestTexture1D(ID3D11Device *pDevice, const D3D11_TEXTURE1D_DESC &TexDesc) { @@ -261,7 +156,8 @@ void RenderDeviceD3D11Impl::TestTextureFormat( TEXTURE_FORMAT TexFormat ) TexFormatInfo.SupportsMS = CreateTestTexture2D( m_pd3d11Device, Tex2DDesc ); } } - else if( TexFormatInfo.ComponentType != COMPONENT_TYPE_COMPRESSED ) + else if( TexFormatInfo.ComponentType != COMPONENT_TYPE_COMPRESSED && + TexFormatInfo.Format != DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { Tex2DDesc.BindFlags = D3D11_BIND_RENDER_TARGET; TexFormatInfo.ColorRenderable = CreateTestTexture2D( m_pd3d11Device, Tex2DDesc ); @@ -303,7 +199,7 @@ void RenderDeviceD3D11Impl :: CreateBuffer(const BufferDesc& BuffDesc, const Buf CreateDeviceObject("buffer", BuffDesc, ppBuffer, [&]() { - BufferD3D11Impl *pBufferD3D11( new BufferD3D11Impl( this, BuffDesc, BuffData ) ); + BufferD3D11Impl *pBufferD3D11( NEW(m_BufObjAllocator, "BufferD3D11Impl instance", BufferD3D11Impl, m_BuffViewObjAllocator, this, BuffDesc, BuffData ) ); pBufferD3D11->QueryInterface( IID_Buffer, reinterpret_cast(ppBuffer) ); pBufferD3D11->CreateDefaultViews(); OnCreateDeviceObject( pBufferD3D11 ); @@ -311,25 +207,12 @@ void RenderDeviceD3D11Impl :: CreateBuffer(const BufferDesc& BuffDesc, const Buf ); } -void RenderDeviceD3D11Impl :: CreateVertexDescription(const LayoutDesc& LayoutDesc, IShader *pVertexShader, IVertexDescription **ppVertexDesc) -{ - CreateDeviceObject( "vertex description", LayoutDesc, ppVertexDesc, - [&]() - { - VertexDescD3D11Impl *pDescD3D11( new VertexDescD3D11Impl( this, LayoutDesc, pVertexShader ) ); - pDescD3D11->QueryInterface( IID_VertexDescription, reinterpret_cast(ppVertexDesc) ); - - OnCreateDeviceObject( pDescD3D11 ); - } - ); -} - void RenderDeviceD3D11Impl :: CreateShader(const ShaderCreationAttribs &ShaderCreationAttribs, IShader **ppShader) { CreateDeviceObject( "shader", ShaderCreationAttribs.Desc, ppShader, [&]() { - ShaderD3D11Impl *pShaderD3D11( new ShaderD3D11Impl( this, ShaderCreationAttribs ) ); + ShaderD3D11Impl *pShaderD3D11( NEW(m_ShaderObjAllocator, "ShaderD3D11Impl instance", ShaderD3D11Impl, this, ShaderCreationAttribs ) ); pShaderD3D11->QueryInterface( IID_Shader, reinterpret_cast(ppShader) ); OnCreateDeviceObject( pShaderD3D11 ); @@ -345,18 +228,20 @@ void RenderDeviceD3D11Impl :: CreateTexture(const TextureDesc& TexDesc, const Te TextureBaseD3D11 *pTextureD3D11 = nullptr; switch( TexDesc.Type ) { - case TEXTURE_TYPE_1D: - case TEXTURE_TYPE_1D_ARRAY: - pTextureD3D11 = new Texture1D_D3D11( this, TexDesc, Data ); + case RESOURCE_DIM_TEX_1D: + case RESOURCE_DIM_TEX_1D_ARRAY: + pTextureD3D11 = NEW(m_TexObjAllocator, "Texture1D_D3D11 instance", Texture1D_D3D11, m_TexViewObjAllocator, this, TexDesc, Data ); break; - case TEXTURE_TYPE_2D: - case TEXTURE_TYPE_2D_ARRAY: - pTextureD3D11 = new Texture2D_D3D11( this, TexDesc, Data ); + case RESOURCE_DIM_TEX_2D: + case RESOURCE_DIM_TEX_2D_ARRAY: + case RESOURCE_DIM_TEX_CUBE: + case RESOURCE_DIM_TEX_CUBE_ARRAY: + pTextureD3D11 = NEW(m_TexObjAllocator, "Texture2D_D3D11 instance", Texture2D_D3D11, m_TexViewObjAllocator, this, TexDesc, Data ); break; - case TEXTURE_TYPE_3D: - pTextureD3D11 = new Texture3D_D3D11( this, TexDesc, Data ); + case RESOURCE_DIM_TEX_3D: + pTextureD3D11 = NEW(m_TexObjAllocator, "Texture3D_D3D11 instance", Texture3D_D3D11, m_TexViewObjAllocator, this, TexDesc, Data ); break; default: LOG_ERROR_AND_THROW( "Unknown texture type. (Did you forget to initialize the Type member of TextureDesc structure?)" ); @@ -376,7 +261,7 @@ void RenderDeviceD3D11Impl :: CreateSampler(const SamplerDesc& SamplerDesc, ISam m_SamplersRegistry.Find( SamplerDesc, reinterpret_cast(ppSampler) ); if( *ppSampler == nullptr ) { - SamplerD3D11Impl *pSamplerD3D11( new SamplerD3D11Impl( this, SamplerDesc ) ); + SamplerD3D11Impl *pSamplerD3D11( NEW(m_SamplerObjAllocator, "SamplerD3D11Impl instance", SamplerD3D11Impl, this, SamplerDesc ) ); pSamplerD3D11->QueryInterface( IID_Sampler, reinterpret_cast(ppSampler) ); OnCreateDeviceObject( pSamplerD3D11 ); m_SamplersRegistry.Add( SamplerDesc, *ppSampler ); @@ -385,54 +270,14 @@ void RenderDeviceD3D11Impl :: CreateSampler(const SamplerDesc& SamplerDesc, ISam ); } -void RenderDeviceD3D11Impl::CreateDepthStencilState( const DepthStencilStateDesc &DSSDesc, IDepthStencilState **ppDepthStencilState ) +void RenderDeviceD3D11Impl::CreatePipelineState(const PipelineStateDesc &PipelineDesc, IPipelineState **ppPipelineState) { - CreateDeviceObject( "depth-stencil state", DSSDesc, ppDepthStencilState, + CreateDeviceObject( "Pipeline state", PipelineDesc, ppPipelineState, [&]() { - m_DSSRegistry.Find( DSSDesc, reinterpret_cast(ppDepthStencilState) ); - if( *ppDepthStencilState == nullptr ) - { - DSStateD3D11Impl *pDepthStencilStateD3D11( new DSStateD3D11Impl( this, DSSDesc ) ); - pDepthStencilStateD3D11->QueryInterface( IID_DepthStencilState, reinterpret_cast(ppDepthStencilState) ); - OnCreateDeviceObject( pDepthStencilStateD3D11 ); - m_DSSRegistry.Add( DSSDesc, *ppDepthStencilState ); - } - } - ); -} - -void RenderDeviceD3D11Impl::CreateRasterizerState( const RasterizerStateDesc &RSDesc, IRasterizerState **ppRasterizerState ) -{ - CreateDeviceObject( "rasterizer state", RSDesc, ppRasterizerState, - [&]() - { - m_RSRegistry.Find( RSDesc, reinterpret_cast(ppRasterizerState) ); - if( *ppRasterizerState == nullptr ) - { - RasterizerStateD3D11Impl *pRasterizerStateD3D11( new RasterizerStateD3D11Impl( this, RSDesc ) ); - pRasterizerStateD3D11->QueryInterface( IID_RasterizerState, reinterpret_cast(ppRasterizerState) ); - OnCreateDeviceObject( pRasterizerStateD3D11 ); - m_RSRegistry.Add( RSDesc, *ppRasterizerState ); - } - } - ); -} - - -void RenderDeviceD3D11Impl::CreateBlendState( const BlendStateDesc &BSDesc, IBlendState **ppBlendState ) -{ - CreateDeviceObject( "blend state", BSDesc, ppBlendState, - [&]() - { - m_BSRegistry.Find( BSDesc, reinterpret_cast(ppBlendState) ); - if( *ppBlendState == nullptr ) - { - BlendStateD3D11Impl *pBlendStateD3D11( new BlendStateD3D11Impl( this, BSDesc ) ); - pBlendStateD3D11->QueryInterface( IID_BlendState, reinterpret_cast(ppBlendState) ); - OnCreateDeviceObject( pBlendStateD3D11 ); - m_BSRegistry.Add( BSDesc, *ppBlendState ); - } + PipelineStateD3D11Impl *pPipelineStateD3D11( NEW(m_PSOAllocator, "PipelineStateD3D11Impl instance", PipelineStateD3D11Impl, this, PipelineDesc ) ); + pPipelineStateD3D11->QueryInterface( IID_PipelineState, reinterpret_cast(ppPipelineState) ); + OnCreateDeviceObject( pPipelineStateD3D11 ); } ); } diff --git a/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp index ee040562..a6f990c2 100644 --- a/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/RenderDeviceFactoryD3D11.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,19 @@ * of the possibility of such damages. */ +/// \file +/// Routines that initialize D3D11-based engine implementation + #include "pch.h" #include "RenderDeviceFactoryD3D11.h" #include "RenderDeviceD3D11Impl.h" #include "DeviceContextD3D11Impl.h" #include "SwapChainD3D11Impl.h" #include "D3D11TypeConversions.h" +#include "EngineMemory.h" #include -using namespace Diligent; -using namespace Diligent; - -extern "C" +namespace Diligent { #if defined(_DEBUG) @@ -56,14 +57,29 @@ inline bool SdkLayersAvailable() } #endif -void CreateDeviceAndImmediateContextD3D11( const EngineCreationAttribs& CreationAttribs, IRenderDevice **ppDevice, Diligent::IDeviceContext **ppContext ) +/// Creates render device and device contexts for Direct3D11-based engine implementation + +/// \param [in] EngineAttribs - Engine creation attributes. +/// \param [out] ppDevice - Address of the memory location where pointer to +/// the created device will be written +/// \param [out] ppContexts - Address of the memory location where pointers to +/// the contexts will be written. Pointer to the immediate +/// context goes at position 0. If NumDeferredContexts > 0, +/// pointers to the deferred contexts go afterwards. +/// \param [in] NumDeferredContexts - Number of deferred contexts. If non-zero number +/// of deferred contexts is requested, pointers to the +/// contexts are written to ppContexts array starting +/// at position 1 +void CreateDeviceAndContextsD3D11( const EngineD3D11Attribs& EngineAttribs, IRenderDevice **ppDevice, IDeviceContext **ppContexts, Uint32 NumDeferredContexts ) { - VERIFY( ppDevice && ppContext, "Null pointer is provided" ); - if( !ppDevice || !ppContext ) + VERIFY( ppDevice && ppContexts, "Null pointer is provided" ); + if( !ppDevice || !ppContexts ) return; + SetRawAllocator(EngineAttribs.pRawMemAllocator); + *ppDevice = nullptr; - *ppContext = nullptr; + memset(ppContexts, 0, sizeof(*ppContexts) * (1+NumDeferredContexts)); try { @@ -86,7 +102,7 @@ void CreateDeviceAndImmediateContextD3D11( const EngineCreationAttribs& Creation // description. All applications are assumed to support 9.1 unless otherwise stated. D3D_FEATURE_LEVEL featureLevels[] = { -#ifdef PLATFORM_WINDOWS_STORE +#ifdef PLATFORM_UNIVERSAL_WINDOWS D3D_FEATURE_LEVEL_11_1, #endif D3D_FEATURE_LEVEL_11_0, @@ -98,8 +114,8 @@ void CreateDeviceAndImmediateContextD3D11( const EngineCreationAttribs& Creation }; // Create the Direct3D 11 API device object and a corresponding context. - RefCntAutoPtr pd3d11Device; - RefCntAutoPtr pd3d11Context; + CComPtr pd3d11Device; + CComPtr pd3d11Context; D3D_FEATURE_LEVEL d3dFeatureLevel = D3D_FEATURE_LEVEL_11_0; HRESULT hr = D3D11CreateDevice( @@ -135,15 +151,28 @@ void CreateDeviceAndImmediateContextD3D11( const EngineCreationAttribs& Creation CHECK_D3D_RESULT_THROW( hr, "Failed to create D3D11 Device and swap chain" ); } - RenderDeviceD3D11Impl *pRenderDeviceD3D11( new RenderDeviceD3D11Impl( pd3d11Device ) ); + auto &RawAlloctor = GetRawAllocator(); + RenderDeviceD3D11Impl *pRenderDeviceD3D11( NEW(RawAlloctor, "RenderDeviceD3D11Impl instance", RenderDeviceD3D11Impl, EngineAttribs, pd3d11Device, NumDeferredContexts ) ); pRenderDeviceD3D11->QueryInterface(IID_RenderDevice, reinterpret_cast(ppDevice) ); - RefCntAutoPtr pDeviceContextD3D11( new DeviceContextD3D11Impl( pRenderDeviceD3D11, pd3d11Context) ); + RefCntAutoPtr pDeviceContextD3D11( NEW(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl, pRenderDeviceD3D11, pd3d11Context, EngineAttribs, false) ); // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D11 will // keep a weak reference to the context - pDeviceContextD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContext) ); + pDeviceContextD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts) ); pRenderDeviceD3D11->SetImmediateContext(pDeviceContextD3D11); - pDeviceContextD3D11->CreateDefaultStates(); + + for (Uint32 DeferredCtx = 0; DeferredCtx < NumDeferredContexts; ++DeferredCtx) + { + CComPtr pd3d11DeferredCtx; + hr = pd3d11Device->CreateDeferredContext(0, &pd3d11DeferredCtx); + CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D11 deferred context") + + RefCntAutoPtr pDeferredCtxD3D11( NEW(RawAlloctor, "DeviceContextD3D11Impl instance", DeviceContextD3D11Impl, pRenderDeviceD3D11, pd3d11DeferredCtx, EngineAttribs, true) ); + // We must call AddRef() (implicitly through QueryInterface()) because pRenderDeviceD3D12 will + // keep a weak reference to the context + pDeferredCtxD3D11->QueryInterface(IID_DeviceContext, reinterpret_cast(ppContexts + 1 + DeferredCtx) ); + pRenderDeviceD3D11->SetDeferredContext(DeferredCtx, pDeferredCtxD3D11); + } } catch( const std::runtime_error & ) { @@ -152,17 +181,34 @@ void CreateDeviceAndImmediateContextD3D11( const EngineCreationAttribs& Creation (*ppDevice)->Release(); *ppDevice = nullptr; } - if( *ppContext ) + for(Uint32 ctx=0; ctx < 1 + NumDeferredContexts; ++ctx) { - (*ppContext)->Release(); - *ppContext = nullptr; + if( ppContexts[ctx] != nullptr ) + { + ppContexts[ctx]->Release(); + ppContexts[ctx] = nullptr; + } } LOG_ERROR( "Failed to create device and immediate context" ); } } -void CreateSwapChainD3D11( IRenderDevice *pDevice, Diligent::IDeviceContext *pImmediateContext, const SwapChainDesc& SwapChainDesc, void* pNativeWndHandle, ISwapChain **ppSwapChain ) + +/// Creates a swap chain for Direct3D11-based engine implementation + +/// \param [in] pDevice - Pointer to the render device +/// \param [in] pImmediateContext - Pointer to the immediate device context +/// \param [in] SCDesc - Swap chain description +/// \param [in] pNativeWndHandle - Platform-specific native handle of the window +/// the swap chain will be associated with: +/// * On Win32 platform, this should be window handle (HWND) +/// * On Universal Windows Platform, this should be reference to the +/// core window (Windows::UI::Core::CoreWindow) +/// +/// \param [out] ppSwapChain - Address of the memory location where pointer to the new +/// swap chain will be written +void CreateSwapChainD3D11( IRenderDevice *pDevice, Diligent::IDeviceContext *pImmediateContext, const SwapChainDesc& SCDesc, void* pNativeWndHandle, ISwapChain **ppSwapChain ) { VERIFY( ppSwapChain, "Null pointer is provided" ); if( !ppSwapChain ) @@ -174,7 +220,9 @@ void CreateSwapChainD3D11( IRenderDevice *pDevice, Diligent::IDeviceContext *pIm { auto *pDeviceD3D11 = ValidatedCast( pDevice ); auto *pDeviceContextD3D11 = ValidatedCast(pImmediateContext); - auto *pSwapChainD3D11 = new SwapChainD3D11Impl(SwapChainDesc, pDeviceD3D11, pDeviceContextD3D11, pNativeWndHandle); + auto &RawMemAllocator = GetRawAllocator(); + + auto *pSwapChainD3D11 = NEW(RawMemAllocator, "SwapChainD3D11Impl instance", SwapChainD3D11Impl, SCDesc, pDeviceD3D11, pDeviceContextD3D11, pNativeWndHandle); pSwapChainD3D11->QueryInterface( IID_SwapChain, reinterpret_cast(ppSwapChain) ); pDeviceContextD3D11->SetSwapChain(pSwapChainD3D11); @@ -182,6 +230,20 @@ void CreateSwapChainD3D11( IRenderDevice *pDevice, Diligent::IDeviceContext *pIm pDeviceContextD3D11->SetRenderTargets( 0, nullptr, nullptr ); // Set default viewport pDeviceContextD3D11->SetViewports( 1, nullptr, 0, 0 ); + + auto NumDeferredCtx = pDeviceD3D11->GetNumDeferredContexts(); + for (size_t ctx = 0; ctx < NumDeferredCtx; ++ctx) + { + if (auto pDeferredCtx = pDeviceD3D11->GetDeferredContext(ctx)) + { + auto *pDeferredCtxD3D11 = ValidatedCast(pDeferredCtx.RawPtr()); + pDeferredCtxD3D11->SetSwapChain(pSwapChainD3D11); + // Bind default render target + pDeferredCtxD3D11->SetRenderTargets( 0, nullptr, nullptr ); + // Set default viewport + pDeferredCtxD3D11->SetViewports( 1, nullptr, 0, 0 ); + } + } } catch( const std::runtime_error & ) { @@ -195,4 +257,39 @@ void CreateSwapChainD3D11( IRenderDevice *pDevice, Diligent::IDeviceContext *pIm } } +#ifdef DOXYGEN +/// Loads Direct3D11-based engine implementation and exports factory functions +/// \param [out] CreateDeviceFunc - Pointer to the function that creates render device and device contexts. +/// See CreateDeviceAndContextsD3D11(). +/// \param [out] CreateSwapChainFunc - Pointer to the function that creates swap chain. +/// See CreateSwapChainD3D11(). +/// \remarks Depending on the configuration and platform, the function loads different dll: +/// Platform\\Configuration | Debug | Release +/// --------------------------|-------------------------------|---------------------------- +/// x86 | GraphicsEngineD3D11_32d.dll | GraphicsEngineD3D11_32r.dll +/// x64 | GraphicsEngineD3D11_64d.dll | GraphicsEngineD3D11_64r.dll +/// +void LoadGraphicsEngineD3D11(CreateDeviceAndContextsD3D11Type &CreateDeviceFunc, CreateSwapChainD3D11Type &CreateSwapChainFunc) +{ + // This function is only required because DoxyGen refuses to generate documentation for a static function when SHOW_FILES==NO + #error This function must never be compiled; +} +#endif + +} + + +using namespace Diligent; +extern "C" +{ + void CreateDeviceAndContextsD3D11(const EngineD3D11Attribs& EngineAttribs, IRenderDevice **ppDevice, IDeviceContext **ppContexts, Uint32 NumDeferredContexts) + { + Diligent::CreateDeviceAndContextsD3D11(EngineAttribs, ppDevice, ppContexts, NumDeferredContexts); + } + + + void CreateSwapChainD3D11(IRenderDevice *pDevice, IDeviceContext *pImmediateContext, const SwapChainDesc& SwapChainDesc, void* pNativeWndHandle, ISwapChain **ppSwapChain) + { + Diligent::CreateSwapChainD3D11(pDevice, pImmediateContext, SwapChainDesc, pNativeWndHandle, ppSwapChain); + } } diff --git a/Graphics/GraphicsEngineD3D11/src/SamplerD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/SamplerD3D11Impl.cpp index 3aa13c74..29c316a6 100644 --- a/Graphics/GraphicsEngineD3D11/src/SamplerD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/SamplerD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ namespace Diligent { -SamplerD3D11Impl::SamplerD3D11Impl(class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const SamplerDesc& SamplerDesc) : - TSamplerBase(pRenderDeviceD3D11, SamplerDesc) +SamplerD3D11Impl::SamplerD3D11Impl(FixedBlockMemoryAllocator &SamplerObjAllocator, class RenderDeviceD3D11Impl *pRenderDeviceD3D11, const SamplerDesc& SamplerDesc) : + TSamplerBase(SamplerObjAllocator, pRenderDeviceD3D11, SamplerDesc) { auto *pd3d11Device = pRenderDeviceD3D11->GetD3D11Device(); D3D11_SAMPLER_DESC D3D11SamplerDesc = diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp index 651261ac..83a8c33b 100644 --- a/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/ShaderD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,354 +23,22 @@ #include "pch.h" -#include - #include "ShaderD3D11Impl.h" #include "RenderDeviceD3D11Impl.h" -#include "StringTools.h" #include "ResourceMapping.h" -#include "BufferD3D11Impl.h" -#include "GraphicsUtilities.h" -#include "TextureViewD3D11Impl.h" -#include "SamplerD3D11Impl.h" -#include "BufferViewD3D11Impl.h" -#include "D3D11DebugUtilities.h" -#include "DataBlobImpl.h" - -using namespace Diligent; namespace Diligent { -const String ShaderD3D11Impl::m_SamplerSuffix = "_sampler"; -const UINT InvalidBindPoint = std::numeric_limits::max(); - -static const Char* g_HLSLDefinitions = -{ - #include "HLSLDefinitions_inc.fxh" -}; - - -class D3DIncludeImpl : public ID3DInclude -{ -public: - D3DIncludeImpl(IShaderSourceInputStreamFactory *pStreamFactory) : - m_pStreamFactory(pStreamFactory) - { - - } - - STDMETHOD( Open )(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) - { - RefCntAutoPtr pSourceStream; - m_pStreamFactory->CreateInputStream( pFileName, &pSourceStream ); - if( pSourceStream == nullptr ) - { - LOG_ERROR( "Failed to open shader include file ", pFileName, ". Check that the file exists" ); - return E_FAIL; - } - - RefCntAutoPtr pFileData( new Diligent::DataBlobImpl ); - pSourceStream->Read( pFileData ); - *ppData = pFileData->GetDataPtr(); - *pBytes = static_cast( pFileData->GetSize() ); - - m_DataBlobs.insert( std::make_pair(*ppData, pFileData) ); - - return S_OK; - } - - STDMETHOD( Close )(THIS_ LPCVOID pData) - { - m_DataBlobs.erase( pData ); - return S_OK; - } - -private: - IShaderSourceInputStreamFactory *m_pStreamFactory; - std::unordered_map< LPCVOID, RefCntAutoPtr > m_DataBlobs; -}; - -static -HRESULT CompileShader( const char* Source, - LPCSTR strFunctionName, - const D3D_SHADER_MACRO* pDefines, - IShaderSourceInputStreamFactory *pIncludeStreamFactory, - LPCSTR profile, - ID3DBlob **ppBlobOut ) -{ - DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; -#if defined( DEBUG ) || defined( _DEBUG ) - // Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders. - // Setting this flag improves the shader debugging experience, but still allows - // the shaders to be optimized and to run exactly the way they will run in - // the release configuration of this program. - dwShaderFlags |= D3DCOMPILE_DEBUG; -#else - // Warning: do not use this flag as it causes shader compiler to fail the compilation and - // report strange errors: - // dwShaderFlags |= D3D10_SHADER_OPTIMIZATION_LEVEL3; -#endif - HRESULT hr; - do - { - CComPtr errors; - auto SourceLen = strlen(Source); - - D3DIncludeImpl IncludeImpl(pIncludeStreamFactory); - hr = D3DCompile( Source, SourceLen, NULL, pDefines, &IncludeImpl, strFunctionName, profile, dwShaderFlags, 0, ppBlobOut, &errors ); - - if( FAILED(hr) || errors ) - { - std::wstringstream errorss; - ComErrorDesc ErrDesc(hr); - if( FAILED(hr) ) - Diligent::FormatMsg( errorss, "Failed to compile shader\n" ); - else - Diligent::FormatMsg( errorss, "Shader compiler output:\n" ); - Diligent::FormatMsg( errorss, ErrDesc.Get(), "\n" ); - if( errors ) - Diligent::FormatMsg( errorss, (char*)errors->GetBufferPointer() ); - auto ErrorDesc = errorss.str(); - OutputDebugString( ErrorDesc.c_str() ); - if( FAILED(hr) -#ifdef PLATFORM_WINDOWS - && IDRETRY != MessageBox( NULL, ErrorDesc.c_str() , L"FX Error", MB_ICONERROR | (Source == nullptr ? MB_ABORTRETRYIGNORE : 0) ) -#endif - ) - { - break; - } - } - } while( FAILED(hr) ); - return hr; -} - -const char* DXShaderProfileToString(SHADER_PROFILE DXProfile) -{ - return "5_0"; - //switch(DXProfile) - //{ - // case DX_SHADER_PROFILE_4_0: return "4_0"; - // case DX_SHADER_PROFILE_5_0: return "5_0"; - // default: UNEXPECTED("Unknown DirectX shader profile" ); return ""; - //} -} - -void ShaderD3D11Impl::LoadShaderResources() -{ - CComPtr pShaderReflection; - CHECK_D3D_RESULT_THROW( D3DReflect( m_pShaderByteCode->GetBufferPointer(), m_pShaderByteCode->GetBufferSize(), __uuidof(pShaderReflection), reinterpret_cast(static_cast(&pShaderReflection)) ), - "Failed to get the shader reflection" ); - - struct ResourceBindInfo - { - String Name; - UINT BindPoint; - }; - - std::vector Textures; - std::unordered_map Samplers; - - D3D11_SHADER_DESC shaderDesc; - memset( &shaderDesc, 0, sizeof(shaderDesc) ); - pShaderReflection->GetDesc( &shaderDesc ); - for( UINT Res = 0; Res < shaderDesc.BoundResources; ++Res ) - { - D3D11_SHADER_INPUT_BIND_DESC BindingDesc; - memset( &BindingDesc, 0, sizeof( BindingDesc ) ); - pShaderReflection->GetResourceBindingDesc( Res, &BindingDesc ); - - switch( BindingDesc.Type ) - { - case D3D_SIT_CBUFFER: - { - ConstBuffBindInfo NewCBInfo(this, BindingDesc.Name, BindingDesc.BindPoint); -#ifdef _DEBUG - std::for_each( m_ConstanBuffers.begin(), m_ConstanBuffers.end(), - [&]( const ConstBuffBindInfo &CBInfo ) - { - VERIFY( CBInfo.Name != BindingDesc.Name, "Constant buffer with the same name already exists" ); - } - ); -#endif - m_ConstanBuffers.emplace_back( NewCBInfo ); - break; - } - - case D3D_SIT_TBUFFER: - { - UNSUPPORTED( "TBuffers are not supported" ); - break; - } - - case D3D_SIT_TEXTURE: - { - - if( BindingDesc.Dimension == D3D_SRV_DIMENSION_BUFFER ) - { - m_BuffSRVs.emplace_back( BuffSRVBindInfo(this, BindingDesc.Name, BindingDesc.BindPoint) ); - } - else - { - ResourceBindInfo NewTextureInfo = { BindingDesc.Name, BindingDesc.BindPoint }; - Textures.emplace_back( NewTextureInfo ); - } - break; - } - - case D3D_SIT_SAMPLER: - { - ResourceBindInfo NewSamplerInfo = { BindingDesc.Name, BindingDesc.BindPoint }; - Samplers.emplace( std::make_pair( BindingDesc.Name, NewSamplerInfo ) ); - break; - } - - case D3D_SIT_UAV_RWTYPED: - { - if( BindingDesc.Dimension == D3D_SRV_DIMENSION_BUFFER ) - { - m_BuffUAVs.push_back( BuffUAVBindInfo( this, BindingDesc.Name, BindingDesc.BindPoint, BindingDesc.Type ) ); - } - else - { - m_TexUAVs.push_back( TexUAVBindInfo( this, BindingDesc.Name, BindingDesc.BindPoint, BindingDesc.Type ) ); - } - break; - } - - case D3D_SIT_STRUCTURED: - { - UNSUPPORTED( "Structured buffers are not supported" ); - break; - } - - case D3D_SIT_UAV_RWSTRUCTURED: - { - m_BuffUAVs.push_back( BuffUAVBindInfo( this, BindingDesc.Name, BindingDesc.BindPoint, BindingDesc.Type ) ); - break; - } - - case D3D_SIT_BYTEADDRESS: - { - UNSUPPORTED( "Byte address buffers are not supported" ); - break; - } - - case D3D_SIT_UAV_RWBYTEADDRESS: - { - m_BuffUAVs.push_back( BuffUAVBindInfo(this, BindingDesc.Name, BindingDesc.BindPoint, BindingDesc.Type) ); - break; - } - - case D3D_SIT_UAV_APPEND_STRUCTURED: - { - UNSUPPORTED( "Append structured buffers are not supported" ); - break; - } - - case D3D_SIT_UAV_CONSUME_STRUCTURED: - { - UNSUPPORTED( "Consume structured buffers are not supported" ); - break; - } - - case D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: - { - UNSUPPORTED( "RW structured buffers with counter are not supported" ); - break; - } - } - } - - // Merge texture and sampler list - for( auto it = Textures.begin(); it != Textures.end(); ++it ) - { - auto SamplerName = it->Name + m_SamplerSuffix; - auto SamplerIt = Samplers.find(SamplerName); - UINT SamplerBindPoint = InvalidBindPoint; - if( SamplerIt != Samplers.end() ) - { - VERIFY( SamplerIt->second.Name == SamplerName, "Unexpected sampler name" ); - SamplerBindPoint = SamplerIt->second.BindPoint; - } - else - { - SamplerName = ""; - } - TexAndSamplerBindInfo TexAndSamplerInfo(this, it->Name, it->BindPoint, SamplerName, SamplerBindPoint); - m_TexAndSamplers.emplace_back( TexAndSamplerInfo ); - } - // After all resources are loaded, we can populate shader variable hash map. - // The map contains raw pointers, but none of the arrays will ever change. -#define STORE_SHADER_VARIABLES(ResArr)\ - { \ - for( auto it = ResArr.begin(); it != ResArr.end(); ++it ) \ - /* HashMapStringKey will make a copy of the string*/ \ - m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(it->GetName()), &*it ) ); \ - } - - STORE_SHADER_VARIABLES(m_ConstanBuffers) - STORE_SHADER_VARIABLES(m_TexAndSamplers) - STORE_SHADER_VARIABLES(m_TexUAVs) - STORE_SHADER_VARIABLES(m_BuffUAVs) - STORE_SHADER_VARIABLES(m_BuffSRVs) - -#undef STORE_SHADER_VARIABLES -} - -ShaderD3D11Impl::ShaderD3D11Impl(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const ShaderCreationAttribs &ShaderCreationAttribs) : - TShaderBase(pRenderDeviceD3D11, ShaderCreationAttribs.Desc) +ShaderD3D11Impl::ShaderD3D11Impl(FixedBlockMemoryAllocator &ShaderObjAllocator, RenderDeviceD3D11Impl *pRenderDeviceD3D11, const ShaderCreationAttribs &CreationAttribs) : + TShaderBase(ShaderObjAllocator, pRenderDeviceD3D11, CreationAttribs.Desc), + ShaderD3DBase(CreationAttribs), + m_StaticResLayout(*this, GetRawAllocator()), + m_ShaderTypeIndex(Diligent::GetShaderTypeIndex(CreationAttribs.Desc.ShaderType)), + m_DummyShaderVar(*this) { - std::string strShaderProfile; - switch(ShaderCreationAttribs.Desc.ShaderType) - { - case SHADER_TYPE_VERTEX: strShaderProfile="vs"; break; - case SHADER_TYPE_PIXEL: strShaderProfile="ps"; break; - case SHADER_TYPE_GEOMETRY:strShaderProfile="gs"; break; - case SHADER_TYPE_HULL: strShaderProfile="hs"; break; - case SHADER_TYPE_DOMAIN: strShaderProfile="ds"; break; - case SHADER_TYPE_COMPUTE: strShaderProfile="cs"; break; - - default: UNEXPECTED( "Unknown shader type" ); - } - strShaderProfile += "_"; - auto *pProfileSuffix = DXShaderProfileToString(ShaderCreationAttribs.Desc.TargetProfile); - strShaderProfile += pProfileSuffix; - - String ShaderSource(g_HLSLDefinitions); - if( ShaderCreationAttribs.Source ) - ShaderSource.append( ShaderCreationAttribs.Source ); - else - { - VERIFY(ShaderCreationAttribs.pShaderSourceStreamFactory, "Input stream factory is null"); - RefCntAutoPtr pSourceStream; - ShaderCreationAttribs.pShaderSourceStreamFactory->CreateInputStream( ShaderCreationAttribs.FilePath, &pSourceStream ); - RefCntAutoPtr pFileData( new Diligent::DataBlobImpl ); - pSourceStream->Read( pFileData ); - // Null terminator is not read from the stream! - auto* FileDataPtr = reinterpret_cast( pFileData->GetDataPtr() ); - auto Size = pFileData->GetSize(); - ShaderSource.append( FileDataPtr, FileDataPtr + Size/sizeof(*FileDataPtr) ); - } - - const D3D_SHADER_MACRO *pDefines = nullptr; - std::vector D3DMacros; - if( ShaderCreationAttribs.Macros ) - { - for( auto* pCurrMacro = ShaderCreationAttribs.Macros; pCurrMacro->Name && pCurrMacro->Definition; ++pCurrMacro ) - { - D3DMacros.push_back( {pCurrMacro->Name, pCurrMacro->Definition} ); - } - D3DMacros.push_back( {nullptr, nullptr} ); - pDefines = D3DMacros.data(); - } - - CHECK_D3D_RESULT_THROW( CompileShader( ShaderSource.c_str(), ShaderCreationAttribs.EntryPoint, pDefines, ShaderCreationAttribs.pShaderSourceStreamFactory, strShaderProfile.c_str(), &m_pShaderByteCode ), - "Failed to compile the shader"); - auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); - switch(ShaderCreationAttribs.Desc.ShaderType) + switch(CreationAttribs.Desc.ShaderType) { #define CREATE_SHADER(SHADER_NAME, ShaderName)\ @@ -400,439 +68,43 @@ ShaderD3D11Impl::ShaderD3D11Impl(RenderDeviceD3D11Impl *pRenderDeviceD3D11, cons if(!m_pShader) LOG_ERROR_AND_THROW("Failed to create the shader from the byte code"); - LoadShaderResources(); + // Load shader resources + auto &Allocator = GetRawAllocator(); + auto *pRawMem = ALLOCATE(Allocator, "Allocator for ShaderResources", sizeof(ShaderResourcesD3D11)); + auto *pResources = new (pRawMem) ShaderResourcesD3D11(pRenderDeviceD3D11, m_pShaderByteCode, m_Desc); + m_pShaderResources.reset(pResources, STDDeleterRawMem(Allocator)); + + // Clone only static resources that will be set directly in the shader + SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_STATIC}; + // The method will also initialize resource cache to have enough space to hold static variables only! + m_StaticResLayout.Initialize(m_pShaderResources, VarTypes, _countof(VarTypes), m_StaticResCache, GetRawAllocator(), GetRawAllocator()); + + // This is not required, but still... + m_pShaderResources->InitStaticSamplers(m_StaticResCache); // Byte code is only required for the vertex shader to create input layout - if( ShaderCreationAttribs.Desc.ShaderType != SHADER_TYPE_VERTEX ) + if( CreationAttribs.Desc.ShaderType != SHADER_TYPE_VERTEX ) m_pShaderByteCode.Release(); } ShaderD3D11Impl::~ShaderD3D11Impl() { + m_StaticResCache.Destroy(GetRawAllocator()); } -#define LOG_RESORUCE_BINDING_ERROR(ResType, pResource, VarName, ShaderName, ...)\ -{ \ - const auto &ResName = pResource->GetDesc().Name; \ - LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " \"", ResName, "\" to variable \"", VarName, \ - "\" in shader \"", ShaderName, "\". ", __VA_ARGS__ ); \ -} - -void ShaderD3D11Impl::BindConstantBuffers( IResourceMapping* pResourceMapping, Uint32 Flags ) -{ - if( !pResourceMapping ) - { - LOG_ERROR_MESSAGE( "Failed to bind constant buffers in shader \"", m_Desc.Name ? m_Desc.Name : "", "\": resource mapping is null" ); - return; - } - // Bind constant buffers - if( Flags & BIND_SHADER_RESOURCES_RESET_BINDINGS ) - { - m_BoundCBs.clear(); - } - for( auto it = m_ConstanBuffers.begin(); it != m_ConstanBuffers.end(); ++it ) - { - if( (Flags & BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED) && it->IsBound() ) - continue; - - RefCntAutoPtr pBuffer; - if( pResourceMapping ) - pResourceMapping->GetResource( it->Name.c_str(), &pBuffer ); - if( pBuffer ) - { - it->Set( pBuffer ); - } - else - { - if( (Flags & BIND_SHADER_RESOURCES_ALL_RESOLVED) && !it->IsBound() ) - LOG_ERROR_MESSAGE("Cannot bind resource to shader variable \"", it->Name, "\": resource not found in the resource mapping") - continue; - } - } -} - - -void ShaderD3D11Impl::ConstBuffBindInfo::Set( IDeviceObject *pBuffer ) -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - auto &BoundCBs = pShaderD3D11->m_BoundCBs; - if( BoundCBs.size() <= BindPoint ) - BoundCBs.resize( BindPoint + 1 ); - - if( pBuffer ) - { - RefCntAutoPtr pBuffD3D11; - pBuffer->QueryInterface( IID_BufferD3D11, reinterpret_cast(static_cast(&pBuffD3D11)) ); - if( pBuffD3D11 ) - { - if( pBuffD3D11->GetDesc().BindFlags & BIND_UNIFORM_BUFFER ) - { - BoundCBs[BindPoint].pd3d11Buff = pBuffD3D11->GetD3D11Buffer(); - VERIFY(BoundCBs[BindPoint].pd3d11Buff, "No relevant D3D11 buffer") - BoundCBs[BindPoint].pBuff = pBuffD3D11; - } - else - { - LOG_RESORUCE_BINDING_ERROR("buffer", pBuffer, Name, pShaderD3D11->m_Desc.Name, "Buffer was not created with BIND_UNIFORM_BUFFER flag.") - } - } - else - { - LOG_RESORUCE_BINDING_ERROR("buffer", pBuffer, Name, pShaderD3D11->m_Desc.Name, "Incorrect resource type: buffer is expected.") - } - } - else - { - BoundCBs[BindPoint] = BoundCB(); - } -} - -bool ShaderD3D11Impl::ConstBuffBindInfo::IsBound() -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - auto &BoundCBs = pShaderD3D11->m_BoundCBs; - if( BindPoint < BoundCBs.size() && BoundCBs[BindPoint].pd3d11Buff != nullptr ) - { - VERIFY(BoundCBs[BindPoint].pBuff != nullptr, "No relevant buffer resource") - return true; - } - - return false; -} - -template -struct ResourceViewTraits{}; - -template<> -struct ResourceViewTraits -{ - static const Char *Name; -}; -const Char *ResourceViewTraits::Name = "texture view"; - -template<> -struct ResourceViewTraits -{ - static const Char *Name; -}; -const Char *ResourceViewTraits::Name = "buffer view"; - -// Helper template class that facilitates binding SRVs and UAVs -class BindViewHelper -{ -public: - BindViewHelper(IResourceMapping *pRM, Uint32 Fl) : - pResourceMapping(pRM), - Flags(Fl) - {} - - template - void Bind( IterType &pShaderVar) - { - if( (Flags & BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED) && pShaderVar->IsBound() ) - return; - - const auto& VarName = pShaderVar->GetName(); - RefCntAutoPtr pView; - if( pResourceMapping ) - pResourceMapping->GetResource( VarName.c_str(), &pView ); - if( pView ) - { - pShaderVar->Set(pView); - } - else - { - if( (Flags & BIND_SHADER_RESOURCES_ALL_RESOLVED) && !pShaderVar->IsBound() ) - LOG_ERROR_MESSAGE( "Cannot bind resource to shader variable \"", VarName, "\": resource view not found in the resource mapping" ) - return; - } - } - -private: - IResourceMapping* const pResourceMapping; - const Uint32 Flags; -}; - -// Helper template function to facilitate setting shader variables -// of different types -template ///< Type of the expected view enum -void SetShaderVariableHelper(IDeviceObject *pView, - std::vector &ViewArray, - UINT BindPoint, - const String& VarName, - TGetResourceMethodType GetResourceMethod, - const Diligent::INTERFACE_ID ViewID, - typename TViewTypeEnum ExpectedViewType, - const String& ShaderName, - TBindSamplerProcType BindSamplerProc) -{ - if( ViewArray.size() <= BindPoint ) - ViewArray.resize( BindPoint + 1 ); - if( pView ) - { - RefCntAutoPtr pViewD3D11; - pView->QueryInterface( ViewID, reinterpret_cast(static_cast(&pViewD3D11)) ); - if( pViewD3D11 ) - { - auto ViewType = pViewD3D11->GetDesc().ViewType; - if( ViewType == ExpectedViewType ) - { - auto &BoundView = ViewArray[BindPoint]; - BoundView.pd3d11View = static_cast( pViewD3D11->GetD3D11View() ); - VERIFY(BoundView.pd3d11View, "No relevant D3D11 view") - BoundView.pView = pViewD3D11; - BoundView.pResource = (pViewD3D11->*GetResourceMethod)(); - VERIFY(BoundView.pResource, "No relevant resource") - BindSamplerProc(pViewD3D11); - } - else - { - const auto *ExpectedViewTypeName = GetViewTypeLiteralName( ExpectedViewType ); - const auto *ActualViewTypeName = GetViewTypeLiteralName( ViewType ); - LOG_RESORUCE_BINDING_ERROR(ResourceViewTraits::Name, pViewD3D11, VarName, ShaderName, - "Incorrect view type: ", ExpectedViewTypeName, " is expected, ", ActualViewTypeName, " provided." ); - } - } - else - { - LOG_RESORUCE_BINDING_ERROR("resource", pView, VarName, ShaderName, "Incorect resource type: ", ResourceViewTraits::Name, " is expected.") - } - } - else - { - ViewArray[BindPoint] = TBoundViewType(); - BindSamplerProc(nullptr); - } -} - -void ShaderD3D11Impl::TexAndSamplerBindInfo::Set( IDeviceObject *pView ) -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - SetShaderVariableHelper(pView, pShaderD3D11->m_BoundSRVs, BindPoint, Name, - &ITextureViewD3D11::GetTexture, IID_TextureViewD3D11, TEXTURE_VIEW_SHADER_RESOURCE, - pShaderD3D11->m_Desc.Name, - [&]( ITextureViewD3D11 *pTexViewD3D11 ) - { - if( SamplerBindPoint != InvalidBindPoint ) - { - auto &BoundSamplers = pShaderD3D11->m_BoundSamplers; - if( BoundSamplers.size() <= SamplerBindPoint ) - BoundSamplers.resize( SamplerBindPoint + 1 ); - auto &BndSam = BoundSamplers[SamplerBindPoint]; - if( pTexViewD3D11 ) - { - auto pSampler = pTexViewD3D11->GetSampler(); - if( pSampler ) - { - BndSam.pd3d11Sampler = ValidatedCast(pSampler)->m_pd3dSampler; - VERIFY(BndSam.pd3d11Sampler, "No relevant D3D11 sampler") - BndSam.pSampler = pSampler; - } - else - { - LOG_ERROR_MESSAGE( "Failed to bind sampler to variable \"", SamplerName, ". Sampler is not set in the texture view \"", pTexViewD3D11->GetDesc().Name, "\"" ); - } - } - else - { - BndSam = BoundSampler(); - } - } - } - ); - -} - -void ShaderD3D11Impl::BuffSRVBindInfo::Set( IDeviceObject *pView ) -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - SetShaderVariableHelper(pView, pShaderD3D11->m_BoundSRVs, BindPoint, Name, - &IBufferViewD3D11::GetBuffer, IID_BufferViewD3D11, BUFFER_VIEW_SHADER_RESOURCE, - pShaderD3D11->m_Desc.Name, - []( IBufferViewD3D11 * ){} - ); -} - -void ShaderD3D11Impl::TexUAVBindInfo::Set( IDeviceObject *pView ) -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - SetShaderVariableHelper( - pView, pShaderD3D11->m_BoundUAVs, BindPoint, Name, - &ITextureViewD3D11::GetTexture, IID_TextureViewD3D11, TEXTURE_VIEW_UNORDERED_ACCESS, - pShaderD3D11->m_Desc.Name, - []( ITextureViewD3D11 * ){} - ); -} - -void ShaderD3D11Impl::BuffUAVBindInfo::Set( IDeviceObject *pView ) -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - SetShaderVariableHelper(pView, pShaderD3D11->m_BoundUAVs, BindPoint, Name, - &IBufferViewD3D11::GetBuffer, IID_BufferViewD3D11, BUFFER_VIEW_UNORDERED_ACCESS, - pShaderD3D11->m_Desc.Name, - []( IBufferViewD3D11 * ){} - ); -} - -template -bool CheckBoundResource(const std::vector &ViewArray, UINT BindPoint) -{ - if( BindPoint < ViewArray.size() && ViewArray[BindPoint].pd3d11View != nullptr ) - { - VERIFY(ViewArray[BindPoint].pResource != nullptr, "No relevant resource") - VERIFY(ViewArray[BindPoint].pView != nullptr, "No relevant resource view") - return true; - } - return false; -} - -bool ShaderD3D11Impl::TexAndSamplerBindInfo::IsBound() -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - return CheckBoundResource( pShaderD3D11->m_BoundSRVs, BindPoint ); -} - -bool ShaderD3D11Impl::BuffSRVBindInfo::IsBound() -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - return CheckBoundResource( pShaderD3D11->m_BoundSRVs, BindPoint ); -} - -bool ShaderD3D11Impl::UAVBindInfoBase::IsBound() -{ - auto *pShaderD3D11 = ValidatedCast( m_pShader ); - return CheckBoundResource( pShaderD3D11->m_BoundUAVs, BindPoint ); -} - -void ShaderD3D11Impl::BindSRVsAndSamplers(IResourceMapping* pResourceMapping, Uint32 Flags ) -{ - if( !pResourceMapping ) - { - LOG_ERROR_MESSAGE( "Failed to bind SRVs and samplers in shader \"", m_Desc.Name ? m_Desc.Name : "", "\": resource mapping is null" ); - return; - } - - if( Flags & BIND_SHADER_RESOURCES_RESET_BINDINGS ) - { - m_BoundSRVs.clear(); - m_BoundSamplers.clear(); - } - - BindViewHelper BindSRVHelper(pResourceMapping, Flags); - - for( auto it = m_TexAndSamplers.begin(); it != m_TexAndSamplers.end(); ++it ) - { - BindSRVHelper.Bind(it); - } - - for( auto it = m_BuffSRVs.begin(); it != m_BuffSRVs.end(); ++it ) - { - BindSRVHelper.Bind(it); - } -} - -void ShaderD3D11Impl::BindUAVs( IResourceMapping* pResourceMapping, Uint32 Flags ) -{ - if( !pResourceMapping ) - { - LOG_ERROR_MESSAGE( "Failed to bind UAVs in shader \"", m_Desc.Name ? m_Desc.Name : "", "\": resource mapping is null" ); - return; - } - - // Bind constant buffers - if( Flags & BIND_SHADER_RESOURCES_RESET_BINDINGS ) - { - m_BoundUAVs.clear(); - } - - BindViewHelper BindUAVHelper(pResourceMapping, Flags); - - for( auto it = m_TexUAVs.begin(); it != m_TexUAVs.end(); ++it ) - { - BindUAVHelper.Bind(it); - } - - for( auto it = m_BuffUAVs.begin(); it != m_BuffUAVs.end(); ++it ) - { - BindUAVHelper.Bind(it); - } -} - -void ShaderD3D11Impl::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags ) -{ - if( !pResourceMapping ) - { - LOG_ERROR_MESSAGE( "Failed to bind resources in shader \"", m_Desc.Name ? m_Desc.Name : "", "\": resource mapping is null" ); - return; - } - - BindConstantBuffers( pResourceMapping, Flags ); - BindSRVsAndSamplers( pResourceMapping, Flags ); - BindUAVs(pResourceMapping, Flags ); -} +IMPLEMENT_QUERY_INTERFACE( ShaderD3D11Impl, IID_ShaderD3D11, TShaderBase ) IShaderVariable* ShaderD3D11Impl::GetShaderVariable( const Char* Name ) { - // Name will be implicitly converted to HashMapStringKey without making a copy - auto it = m_VariableHash.find( Name ); - if( it == m_VariableHash.end() ) - { - LOG_ERROR_MESSAGE( "Shader variable \"", Name, "\" is not found in shader \"", m_Desc.Name ? m_Desc.Name : "", "\". Attempts to set the variable will be silently ignored." ); - return &m_DummyShaderVar; - } - return it->second; + auto *pVar = m_StaticResLayout.GetShaderVariable(Name); + if(pVar == nullptr) + pVar = &m_DummyShaderVar; + return pVar; } - - -IMPLEMENT_QUERY_INTERFACE( ShaderD3D11Impl, IID_ShaderD3D11, TShaderBase ) - -#ifdef VERIFY_SHADER_BINDINGS -void ShaderD3D11Impl::dbgVerifyBindings() +void ShaderD3D11Impl::BindResources(IResourceMapping* pResourceMapping, Uint32 Flags) { - const auto *ShaderName = m_Desc.Name ? m_Desc.Name : ""; -#define LOG_MISSING_BINDING(VarType, Name)\ - LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable \"", Name, "\" in shader \"", ShaderName, "\"" ); - - for( auto cb = m_ConstanBuffers.begin(); cb != m_ConstanBuffers.end(); ++cb ) - { - if( m_BoundCBs.size() <= cb->BindPoint || m_BoundCBs[cb->BindPoint].pd3d11Buff == nullptr ) - LOG_MISSING_BINDING("constant buffer", cb->Name) - } - - for( auto tex = m_TexAndSamplers.begin(); tex != m_TexAndSamplers.end(); ++tex ) - { - if( m_BoundSRVs.size() <= tex->BindPoint || m_BoundSRVs[tex->BindPoint].pd3d11View == nullptr ) - LOG_MISSING_BINDING("texture", tex->Name) - - if( tex->SamplerBindPoint != InvalidBindPoint && - (m_BoundSamplers.size() <= tex->SamplerBindPoint || m_BoundSamplers[tex->SamplerBindPoint].pd3d11Sampler == nullptr) ) - LOG_MISSING_BINDING("sampler", tex->SamplerName) - } - - for( auto buf = m_BuffSRVs.begin(); buf != m_BuffSRVs.end(); ++buf ) - { - if( m_BoundSRVs.size() <= buf->BindPoint || m_BoundSRVs[buf->BindPoint].pd3d11View == nullptr ) - LOG_MISSING_BINDING("buffer", buf->Name) - } - - for( auto uav = m_TexUAVs.begin(); uav != m_TexUAVs.end(); ++uav ) - { - if( m_BoundUAVs.size() <= uav->BindPoint || m_BoundUAVs[uav->BindPoint].pd3d11View == nullptr ) - LOG_MISSING_BINDING("texture UAV", uav->Name) - } - - for( auto uav = m_BuffUAVs.begin(); uav != m_BuffUAVs.end(); ++uav ) - { - if( m_BoundUAVs.size() <= uav->BindPoint || m_BoundUAVs[uav->BindPoint].pd3d11View == nullptr ) - LOG_MISSING_BINDING("buffer UAV", uav->Name) - } + m_StaticResLayout.BindResources(pResourceMapping, Flags, m_StaticResCache); } -#endif } diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp new file mode 100644 index 00000000..37dd96f8 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceBindingD3D11Impl.cpp @@ -0,0 +1,168 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" +#include "ShaderResourceBindingD3D11Impl.h" +#include "PipelineStateD3D11Impl.h" +#include "DeviceContextD3D11Impl.h" +#include "RenderDeviceD3D11Impl.h" + +namespace Diligent +{ + + +ShaderResourceBindingD3D11Impl::ShaderResourceBindingD3D11Impl( FixedBlockMemoryAllocator &SRBAllocator, PipelineStateD3D11Impl *pPSO, bool IsInternal) : + TBase( SRBAllocator, pPSO, IsInternal ), + m_bIsStaticResourcesBound(false) +{ + for(size_t s=0; s < _countof(m_ResourceLayoutIndex); ++s) + m_ResourceLayoutIndex[s] = -1; + + auto ppShaders = pPSO->GetShaders(); + m_NumActiveShaders = static_cast( pPSO->GetNumShaders() ); + + auto *pResLayoutRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceLayoutD3D11", m_NumActiveShaders * sizeof(ShaderResourceLayoutD3D11)); + m_pResourceLayouts = reinterpret_cast(pResLayoutRawMem); + + auto *pResCacheRawMem = ALLOCATE(GetRawAllocator(), "Raw memory for ShaderResourceCacheD3D11", m_NumActiveShaders * sizeof(ShaderResourceCacheD3D11)); + m_pBoundResourceCaches = reinterpret_cast(pResCacheRawMem); + + // Reserve memory for resource layouts + for (Uint8 s = 0; s < m_NumActiveShaders; ++s) + { + auto *pShaderD3D11 = ValidatedCast(ppShaders[s]); + auto ShaderInd = pShaderD3D11->GetShaderTypeIndex(); + VERIFY_EXPR(static_cast(ShaderInd) == GetShaderTypeIndex(pShaderD3D11->GetDesc().ShaderType)); + + SHADER_VARIABLE_TYPE VarTypes[] = {SHADER_VARIABLE_TYPE_MUTABLE, SHADER_VARIABLE_TYPE_DYNAMIC}; + + auto &ResCacheDataAllocator = pPSO->GetResourceCacheDataAllocator(s); + auto &ResLayoutDataAllocator = pPSO->GetShaderResLayoutDataAllocators(s); + + // Initialize resource cache to have enough space to contain all shader resources, including static ones + // Static resources are copied before resources are committed + const auto &Resources = *pShaderD3D11->GetResources(); + auto CBCount = Resources.GetMaxCBBindPoint()+1; + auto SRVCount = Resources.GetMaxSRVBindPoint()+1; + auto SamplerCount = Resources.GetMaxSamplerBindPoint()+1; + auto UAVCount = Resources.GetMaxUAVBindPoint()+1; + new (m_pBoundResourceCaches+s) ShaderResourceCacheD3D11; + m_pBoundResourceCaches[s].Initialize(CBCount, SRVCount, SamplerCount, UAVCount, ResCacheDataAllocator); + + new (m_pResourceLayouts + s) ShaderResourceLayoutD3D11(*this, ResLayoutDataAllocator); + m_pResourceLayouts[s].Initialize(pShaderD3D11->GetResources(), VarTypes, _countof(VarTypes), m_pBoundResourceCaches[s], ResCacheDataAllocator, ResLayoutDataAllocator); + + Resources.InitStaticSamplers(m_pBoundResourceCaches[s]); + + m_ResourceLayoutIndex[ShaderInd] = s; + m_ShaderTypeIndex[s] = static_cast(ShaderInd); + } +} + +ShaderResourceBindingD3D11Impl::~ShaderResourceBindingD3D11Impl() +{ + auto *pPSOD3D11Impl = ValidatedCast(m_pPSO); + for (Uint32 s = 0; s < m_NumActiveShaders; ++s) + { + auto &Allocator = pPSOD3D11Impl->GetResourceCacheDataAllocator(s); + m_pBoundResourceCaches[s].Destroy(Allocator); + m_pBoundResourceCaches[s].~ShaderResourceCacheD3D11(); + } + GetRawAllocator().Free(m_pBoundResourceCaches); + + for(Int32 l = 0; l < m_NumActiveShaders; ++l) + { + m_pResourceLayouts[l].~ShaderResourceLayoutD3D11(); + } + GetRawAllocator().Free(m_pResourceLayouts); +} + +IMPLEMENT_QUERY_INTERFACE( ShaderResourceBindingD3D11Impl, IID_ShaderResourceBindingD3D11, TBase ) + +void ShaderResourceBindingD3D11Impl::BindResources(Uint32 ShaderFlags, IResourceMapping *pResMapping, Uint32 Flags) +{ + for(Uint32 ResLayoutInd = 0; ResLayoutInd < m_NumActiveShaders; ++ResLayoutInd) + { + auto &ResLayout = m_pResourceLayouts[ResLayoutInd]; + if(ShaderFlags & ResLayout.GetShaderType()) + { + ResLayout.BindResources(pResMapping, Flags, m_pBoundResourceCaches[ResLayoutInd]); + } + } +} + +void ShaderResourceBindingD3D11Impl::BindStaticShaderResources() +{ + if (m_bIsStaticResourcesBound) + { + LOG_ERROR("Static resources already bound"); + return; + } + + auto *pPSOD3D11 = ValidatedCast(GetPipelineState()); + auto ppShaders = pPSOD3D11->GetShaders(); + auto NumShaders = pPSOD3D11->GetNumShaders(); + VERIFY_EXPR(NumShaders == m_NumActiveShaders); + + for (Uint32 shader = 0; shader < NumShaders; ++shader) + { + auto *pShaderD3D11 = ValidatedCast( ppShaders[shader] ); +#ifdef VERIFY_SHADER_BINDINGS + pShaderD3D11->GetStaticResourceLayout().dbgVerifyBindings(); +#endif + +#ifdef _DEBUG + auto ShaderTypeInd = pShaderD3D11->GetShaderTypeIndex(); + auto ResourceLayoutInd = m_ResourceLayoutIndex[ShaderTypeInd]; + VERIFY_EXPR(ResourceLayoutInd == static_cast(shader) ); +#endif + pShaderD3D11->GetStaticResourceLayout().CopyResources( m_pBoundResourceCaches[shader] ); + } + + m_bIsStaticResourcesBound = true; +} + +IShaderVariable *ShaderResourceBindingD3D11Impl::GetVariable(SHADER_TYPE ShaderType, const char *Name) +{ + auto Ind = GetShaderTypeIndex(ShaderType); + VERIFY_EXPR(Ind >= 0 && Ind < _countof(m_ResourceLayoutIndex)); + auto ResLayoutIndex = m_ResourceLayoutIndex[Ind]; + if( Ind >= 0 ) + { + auto *pVar = m_pResourceLayouts[ResLayoutIndex].GetShaderVariable(Name); + if(pVar != nullptr) + return pVar; + else + { + auto *pPSOD3D11 = ValidatedCast(GetPipelineState()); + return pPSOD3D11->GetDummyShaderVariable(); + } + } + else + { + LOG_ERROR_MESSAGE("Shader type ", GetShaderTypeLiteralName(ShaderType)," is not active in the resource binding"); + return nullptr; + } +} + +} diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceCacheD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceCacheD3D11.cpp new file mode 100644 index 00000000..8054bb57 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceCacheD3D11.cpp @@ -0,0 +1,265 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" + +#include "ShaderResourceCacheD3D11.h" +#include "ShaderResourceLayoutD3D11.h" +#include "TextureBaseD3D11.h" +#include "BufferD3D11Impl.h" +#include "SamplerD3D11Impl.h" +#include "MemoryAllocator.h" + +namespace Diligent +{ + void ShaderResourceCacheD3D11::Initialize(Int32 CBCount, Int32 SRVCount, Int32 SamplerCount, Int32 UAVCount, IMemoryAllocator &MemAllocator) + { + if (IsInitialized()) + { + LOG_ERROR_MESSAGE("Resource cache is already intialized") + return; + } + + + VERIFY(CBCount <= D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT, "Constant buffer count ", CBCount, " exceeds D3D11 limit ", D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ); + VERIFY(SRVCount <= D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT, "SRV count ", SRVCount, " exceeds D3D11 limit ", D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT ); + VERIFY(SamplerCount <= D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT, "Sampler count ", SamplerCount, " exceeds D3D11 limit ", D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT ); + VERIFY(UAVCount <= D3D11_PS_CS_UAV_REGISTER_COUNT, "UAV count ", UAVCount, " exceeds D3D11 limit ", D3D11_PS_CS_UAV_REGISTER_COUNT ); + + m_ResourceCounts = PackResourceCounts(CBCount, SRVCount, SamplerCount, UAVCount); + VERIFY_EXPR(GetCBCount() == static_cast(CBCount)); + VERIFY_EXPR(GetSRVCount() == static_cast(SRVCount)); + VERIFY_EXPR(GetSamplerCount() == static_cast(SamplerCount)); + VERIFY_EXPR(GetUAVCount() == static_cast(UAVCount)); + + CachedCB* CBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + CachedResource* SRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + CachedSampler* Samplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + CachedResource* UAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + GetResourceArrays(CBs, d3d11CBs, SRVResources, d3d11SRVs, Samplers, d3d11Samplers, UAVResources, d3d11UAVs); + + VERIFY_EXPR(m_pResourceData == nullptr); + size_t BufferSize = reinterpret_cast(d3d11UAVs + UAVCount) - m_pResourceData; + + VERIFY_EXPR( BufferSize == + (sizeof(CBs[0]) + sizeof(d3d11CBs[0])) * CBCount + + (sizeof(SRVResources[0]) + sizeof(d3d11SRVs[0])) * SRVCount + + (sizeof(Samplers[0]) + sizeof(d3d11Samplers[0])) * SamplerCount + + (sizeof(UAVResources[0]) + sizeof(d3d11UAVs[0])) * UAVCount ); + +#ifdef _DEBUG + m_pdbgMemoryAllocator = &MemAllocator; +#endif + if( BufferSize > 0 ) + { + m_pResourceData = reinterpret_cast(MemAllocator.Allocate(BufferSize, "Shader resource cache data buffer", __FILE__, __LINE__ )); + memset(m_pResourceData, 0, BufferSize); + } + + + GetResourceArrays(CBs, d3d11CBs, SRVResources, d3d11SRVs, Samplers, d3d11Samplers, UAVResources, d3d11UAVs); +#ifdef _DEBUG + { + CachedCB* dbgCBs = nullptr; + ID3D11Buffer** dbgd3d11CBs = nullptr; + GetCBArrays(dbgCBs, dbgd3d11CBs); + VERIFY_EXPR(dbgCBs == CBs && dbgd3d11CBs == d3d11CBs); + } + { + CachedResource* dbgSRVResources = nullptr; + ID3D11ShaderResourceView** dbgd3d11SRVs = nullptr; + GetSRVArrays(dbgSRVResources, dbgd3d11SRVs); + VERIFY_EXPR(dbgSRVResources == SRVResources && dbgd3d11SRVs == d3d11SRVs); + } + { + CachedSampler* dbgSamplers = nullptr; + ID3D11SamplerState** dbgd3d11Samplers = nullptr; + GetSamplerArrays(dbgSamplers, dbgd3d11Samplers); + VERIFY_EXPR(dbgSamplers == Samplers && dbgd3d11Samplers == d3d11Samplers); + } + + { + CachedResource* dbgUAVResources = nullptr; + ID3D11UnorderedAccessView** dbgd3d11UAVs = nullptr; + GetUAVArrays(dbgUAVResources, dbgd3d11UAVs); + VERIFY_EXPR(dbgUAVResources == UAVResources && dbgd3d11UAVs == d3d11UAVs); + } +#endif + + // Explicitly construct all objects + for (Int32 cb = 0; cb < CBCount; ++cb) + new(CBs+cb)CachedCB; + + for (Int32 srv = 0; srv < SRVCount; ++srv) + new(SRVResources+srv)CachedResource; + + for (Int32 sam = 0; sam < SamplerCount; ++sam) + new(Samplers+sam)CachedSampler; + + for (Int32 uav = 0; uav < UAVCount; ++uav) + new(UAVResources+uav)CachedResource; + } + + void ShaderResourceCacheD3D11::Destroy(IMemoryAllocator &MemAllocator) + { + VERIFY( IsInitialized(), "Resource cache is not initialized") + VERIFY( m_pdbgMemoryAllocator == &MemAllocator, "The allocator does not match the one used to create resources") + + if( IsInitialized() ) + { + CachedCB* CBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + CachedResource* SRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + CachedSampler* Samplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + CachedResource* UAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + GetResourceArrays(CBs, d3d11CBs, SRVResources, d3d11SRVs, Samplers, d3d11Samplers, UAVResources, d3d11UAVs); + + // Explicitly destory all objects + auto CBCount = GetCBCount(); + for (size_t cb = 0; cb < CBCount; ++cb) + CBs[cb].~CachedCB(); + auto SRVCount = GetSRVCount(); + for (size_t srv = 0; srv < SRVCount; ++srv) + SRVResources[srv].~CachedResource(); + auto SamplerCount = GetSamplerCount(); + for (size_t sam = 0; sam < SamplerCount; ++sam) + Samplers[sam].~CachedSampler(); + auto UAVCount = GetUAVCount(); + for (size_t uav = 0; uav < UAVCount; ++uav) + UAVResources[uav].~CachedResource(); + m_ResourceCounts = InvalidResourceCounts; + + if(m_pResourceData != nullptr) + MemAllocator.Free(m_pResourceData); + } + } + + ShaderResourceCacheD3D11::~ShaderResourceCacheD3D11() + { + VERIFY( !IsInitialized(), "Shader resource cache memory must be released with ShaderResourceCacheD3D11::Destroy()" ) + } + + void dbgVerifyResource(ShaderResourceCacheD3D11::CachedResource &Res, ID3D11View *pd3d11View, const char *ViewType) + { + if (pd3d11View != nullptr) + { + VERIFY(Res.pView != nullptr, "Resource view is not initialized") + VERIFY(Res.pBuffer==nullptr && Res.pTexture!=nullptr || Res.pBuffer!=nullptr && Res.pTexture==nullptr, "Texture and buffer resources are mutually exclusive") + VERIFY(Res.pd3d11Resource!=nullptr, "D3D11 resource is missing") + + CComPtr pd3d11ActualResource; + pd3d11View->GetResource(&pd3d11ActualResource); + VERIFY(pd3d11ActualResource == Res.pd3d11Resource, "Inconsistent D3D11 resource") + if (Res.pBuffer) + { + VERIFY(pd3d11ActualResource == Res.pBuffer->GetD3D11Buffer(), "Inconsistent buffer ", ViewType) + if (Res.pView) + { + RefCntAutoPtr pBufView(Res.pView, IID_BufferViewD3D11); + VERIFY(pBufView != nullptr, "Provided resource view is not D3D11 buffer view") + if(pBufView) + VERIFY(pBufView->GetBuffer() == Res.pBuffer, "Provided resource view is not a view of the buffer") + } + } + else if(Res.pTexture) + { + VERIFY(pd3d11ActualResource == Res.pTexture->GetD3D11Texture(), "Inconsistent texture ", ViewType) + if (Res.pView) + { + RefCntAutoPtr pTexView(Res.pView, IID_TextureViewD3D11); + VERIFY(pTexView != nullptr, "Provided resource view is not D3D11 texture view") + if(pTexView) + VERIFY(pTexView->GetTexture() == Res.pTexture, "Provided resource view is not a view of the texture") + } + } + } + else + { + VERIFY(Res.pView==nullptr, "Resource view is unexpected") + VERIFY(Res.pBuffer==nullptr && Res.pTexture==nullptr, "Niether texture nor buffer resource is expected") + VERIFY(Res.pd3d11Resource==nullptr, "Unexepected D3D11 resource") + } + } + + void ShaderResourceCacheD3D11::dbgVerifyCacheConsistency() + { + VERIFY(IsInitialized(), "Cache is not initialized") + + CachedCB* CBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + CachedResource* SRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + CachedSampler* Samplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + CachedResource* UAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + GetResourceArrays(CBs, d3d11CBs, SRVResources, d3d11SRVs, Samplers, d3d11Samplers, UAVResources, d3d11UAVs); + + auto CBCount = GetCBCount(); + for (size_t cb = 0; cb < CBCount; ++cb) + { + auto &pBuff = CBs[cb].pBuff; + auto *pd3d11Buff = d3d11CBs[cb]; + VERIFY(pBuff==nullptr && pd3d11Buff==nullptr || pBuff!=nullptr && pd3d11Buff!=nullptr, "CB resource and d3d11 buffer must be set/unset atomically") + if(pBuff != nullptr && pd3d11Buff != nullptr ) + { + VERIFY(pd3d11Buff == pBuff->GetD3D11Buffer(), "Inconsistent D3D11 buffer") + } + } + + auto SRVCount = GetSRVCount(); + for (size_t srv = 0; srv < SRVCount; ++srv) + { + auto &Res = SRVResources[srv]; + auto *pd3d11SRV = d3d11SRVs[srv]; + dbgVerifyResource(Res, pd3d11SRV, "SRV"); + } + + auto UAVCount = GetUAVCount(); + for (size_t uav = 0; uav < UAVCount; ++uav) + { + auto &Res = UAVResources[uav]; + auto *pd3d11UAV = d3d11UAVs[uav]; + dbgVerifyResource(Res, pd3d11UAV, "UAV"); + } + + auto SamplerCount = GetSamplerCount(); + for (size_t sam = 0; sam < SamplerCount; ++sam) + { + auto &pSampler = Samplers[sam].pSampler; + auto *pd3d11Sampler = d3d11Samplers[sam]; + VERIFY(pSampler==nullptr && pd3d11Sampler==nullptr || pSampler!=nullptr && pd3d11Sampler!=nullptr, "CB resource and d3d11 buffer must be set/unset atomically") + if(pSampler!=nullptr && pd3d11Sampler!=nullptr) + { + VERIFY(pd3d11Sampler==pSampler->GetD3D11SamplerState(), "Inconsistent D3D11 sampler") + } + } + } +} diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp new file mode 100644 index 00000000..00fb3549 --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourceLayoutD3D11.cpp @@ -0,0 +1,783 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" + +#include + +#include "ShaderResourceLayoutD3D11.h" +#include "ShaderResourceCacheD3D11.h" +#include "BufferD3D11Impl.h" +#include "BufferViewD3D11Impl.h" +#include "TextureBaseD3D11.h" +#include "TextureViewD3D11.h" +#include "SamplerD3D11Impl.h" +#include "D3DShaderResourceLoader.h" +#include "ShaderD3D11Impl.h" + +namespace Diligent +{ + +ShaderResourceLayoutD3D11::ShaderResourceLayoutD3D11(IObject &Owner, IMemoryAllocator& ResLayoutDataAllocator) : + m_Owner(Owner), +#if USE_VARIABLE_HASH_MAP + m_VariableHash(STD_ALLOCATOR_RAW_MEM(VariableHashData, GetRawAllocator(), "Allocator for vector")), +#endif + m_ResourceBuffer(nullptr, STDDeleterRawMem(ResLayoutDataAllocator)) +{ +} + +ShaderResourceLayoutD3D11::~ShaderResourceLayoutD3D11() +{ + HandleResources( + [&](ConstBuffBindInfo&cb) + { + cb.~ConstBuffBindInfo(); + }, + + [&](TexAndSamplerBindInfo& ts) + { + ts.~TexAndSamplerBindInfo(); + }, + + [&](TexUAVBindInfo& uav) + { + uav.~TexUAVBindInfo(); + }, + + [&](BuffSRVBindInfo& srv) + { + srv.~BuffSRVBindInfo(); + }, + + [&](BuffUAVBindInfo& uav) + { + uav.~BuffUAVBindInfo(); + } + ); +} + +const D3DShaderResourceAttribs ShaderResourceLayoutD3D11::TexAndSamplerBindInfo::InvalidSamplerAttribs(String("Invalid sampler"), D3DShaderResourceAttribs::InvalidBindPoint, 0, D3D_SIT_SAMPLER, SHADER_VARIABLE_TYPE_NUM_TYPES, D3D_SRV_DIMENSION_UNKNOWN, D3DShaderResourceAttribs::InvalidSamplerId, false); + +void ShaderResourceLayoutD3D11::Initialize(const std::shared_ptr& pSrcResources, + const SHADER_VARIABLE_TYPE *VarTypes, + Uint32 NumVarTypes, + ShaderResourceCacheD3D11& ResourceCache, + IMemoryAllocator& ResCacheDataAllocator, + IMemoryAllocator& ResLayoutDataAllocator) +{ + VERIFY(&m_ResourceBuffer.get_deleter().m_Allocator == &ResLayoutDataAllocator, "Incosistent memory alloctor"); + + m_pResources = pSrcResources; + m_pResourceCache = &ResourceCache; + + Uint32 AllowedTypeBits = GetAllowedTypeBits(VarTypes, NumVarTypes); + + Uint32 NumCBs, NumTexSRVs, NumTexUAVs, NumBufSRVs, NumBufUAVs, NumSamplers; + pSrcResources->CountResources(VarTypes, NumVarTypes, NumCBs, NumTexSRVs, NumTexUAVs, NumBufSRVs, NumBufUAVs, NumSamplers); + + m_TexAndSamplersOffset = 0 + static_cast( NumCBs * sizeof(ConstBuffBindInfo) ); + m_TexUAVsOffset = m_TexAndSamplersOffset + static_cast( NumTexSRVs * sizeof(TexAndSamplerBindInfo) ); + m_BuffUAVsOffset = m_TexUAVsOffset + static_cast( NumTexUAVs * sizeof(TexUAVBindInfo) ); + m_BuffSRVsOffset = m_BuffUAVsOffset + static_cast( NumBufUAVs * sizeof(BuffUAVBindInfo) ); + auto MemorySize = m_BuffSRVsOffset + NumBufSRVs * sizeof(BuffSRVBindInfo); + + if( MemorySize ) + { + auto *pRawMem = ALLOCATE(ResLayoutDataAllocator, "Raw memory buffer for shader resource layout resources", MemorySize); + m_ResourceBuffer.reset(pRawMem); + } + + VERIFY_EXPR(NumCBs < 255); + VERIFY_EXPR(NumTexSRVs < 255); + VERIFY_EXPR(NumTexUAVs < 255); + VERIFY_EXPR(NumBufSRVs < 255); + VERIFY_EXPR(NumBufUAVs < 255); + m_NumCBs = static_cast(NumCBs); + m_NumTexSRVs = static_cast(NumTexSRVs); + m_NumTexUAVs = static_cast(NumTexUAVs); + m_NumBufSRVs = static_cast(NumBufSRVs); + m_NumBufUAVs = static_cast(NumBufUAVs); + + Uint32 cb = 0; + Uint32 texSrv = 0; + Uint32 texUav = 0; + Uint32 bufSrv = 0; + Uint32 bufUav = 0; + + Int32 MaxCBBindPoint = -1; + Int32 MaxSRVBindPoint = -1; + Int32 MaxSamplerBindPoint = -1; + Int32 MaxUAVBindPoint = -1; + pSrcResources->ProcessResources( + VarTypes, NumVarTypes, + + [&](const D3DShaderResourceAttribs &CB) + { + VERIFY_EXPR( IsAllowedType(CB.GetVariableType(), AllowedTypeBits) ); + new (&GetCB(cb++)) ConstBuffBindInfo( CB, *this ); + MaxCBBindPoint = std::max(MaxCBBindPoint, static_cast(CB.BindPoint + CB.BindCount-1)); + }, + + [&](const D3DShaderResourceAttribs& TexSRV) + { + VERIFY_EXPR( IsAllowedType(TexSRV.GetVariableType(), AllowedTypeBits) ); + + const D3DShaderResourceAttribs& SamplerAttribs = TexSRV.IsValidSampler() ? + pSrcResources->GetSampler(TexSRV.GetSamplerId()) : TexAndSamplerBindInfo::InvalidSamplerAttribs; + new (&GetTexSRV(texSrv++)) TexAndSamplerBindInfo( TexSRV, SamplerAttribs, *this ); + MaxSRVBindPoint = std::max(MaxSRVBindPoint, static_cast(TexSRV.BindPoint + TexSRV.BindCount-1)); + if( SamplerAttribs.IsValidBindPoint() ) + MaxSamplerBindPoint = std::max(MaxSamplerBindPoint, static_cast(SamplerAttribs.BindPoint + SamplerAttribs.BindCount-1)); + }, + + [&](const D3DShaderResourceAttribs &TexUAV) + { + VERIFY_EXPR( IsAllowedType(TexUAV.GetVariableType(), AllowedTypeBits) ); + + new (&GetTexUAV(texUav++)) TexUAVBindInfo( TexUAV, *this ); + MaxUAVBindPoint = std::max(MaxUAVBindPoint, static_cast(TexUAV.BindPoint + TexUAV.BindCount-1)); + }, + + [&](const D3DShaderResourceAttribs &BuffSRV) + { + VERIFY_EXPR(IsAllowedType(BuffSRV.GetVariableType(), AllowedTypeBits)); + + new (&GetBufSRV(bufSrv++)) BuffSRVBindInfo( BuffSRV, *this ); + MaxSRVBindPoint = std::max(MaxSRVBindPoint, static_cast(BuffSRV.BindPoint + BuffSRV.BindCount-1)); + }, + + [&](const D3DShaderResourceAttribs &BuffUAV) + { + VERIFY_EXPR(IsAllowedType(BuffUAV.GetVariableType(), AllowedTypeBits)); + + new (&GetBufUAV(bufUav++)) BuffUAVBindInfo( BuffUAV, *this ); + MaxUAVBindPoint = std::max(MaxUAVBindPoint, static_cast(BuffUAV.BindPoint + BuffUAV.BindCount-1)); + } + ); + + if (!m_pResourceCache->IsInitialized()) + { + // NOTE that here we are using max bind points required to cache only the shader variables of allowed types! + m_pResourceCache->Initialize(MaxCBBindPoint+1, MaxSRVBindPoint+1, MaxSamplerBindPoint+1, MaxUAVBindPoint+1, ResCacheDataAllocator); + } + + VERIFY(cb == m_NumCBs, "Not all CBs are initialized, which will result in a crash when dtor is called"); + VERIFY(texSrv == m_NumTexSRVs, "Not all Tex SRVs are initialized, which will result in a crash when dtor is called"); + VERIFY(texUav == m_NumTexUAVs, "Not all Tex UAVs are initialized, which will result in a crash when dtor is called"); + VERIFY(bufSrv == m_NumBufSRVs, "Not all Buf SRVs are initialized, which will result in a crash when dtor is called"); + VERIFY(bufUav == m_NumBufUAVs, "Not all Buf UAVs are initialized, which will result in a crash when dtor is called"); + + InitVariablesHashMap(); +} + +void ShaderResourceLayoutD3D11::CopyResources(ShaderResourceCacheD3D11 &DstCache) +{ + VERIFY(m_pResourceCache, "Resource cache must not be null"); + + VERIFY( DstCache.GetCBCount() >= m_pResourceCache->GetCBCount(), "Dst cache is not large enough to contain all CBs" ) + VERIFY( DstCache.GetSRVCount() >= m_pResourceCache->GetSRVCount(), "Dst cache is not large enough to contain all SRVs" ) + VERIFY( DstCache.GetSamplerCount() >= m_pResourceCache->GetSamplerCount(), "Dst cache is not large enough to contain all samplers" ) + VERIFY( DstCache.GetUAVCount() >= m_pResourceCache->GetUAVCount(), "Dst cache is not large enough to contain all UAVs" ) + + ShaderResourceCacheD3D11::CachedCB* CachedCBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + ShaderResourceCacheD3D11::CachedResource* CachedSRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + ShaderResourceCacheD3D11::CachedSampler* CachedSamplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + ShaderResourceCacheD3D11::CachedResource* CachedUAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + m_pResourceCache->GetResourceArrays(CachedCBs, d3d11CBs, CachedSRVResources, d3d11SRVs, CachedSamplers, d3d11Samplers, CachedUAVResources, d3d11UAVs); + + + ShaderResourceCacheD3D11::CachedCB* DstCBs = nullptr; + ID3D11Buffer** DstD3D11CBs = nullptr; + ShaderResourceCacheD3D11::CachedResource* DstSRVResources = nullptr; + ID3D11ShaderResourceView** DstD3D11SRVs = nullptr; + ShaderResourceCacheD3D11::CachedSampler* DstSamplers = nullptr; + ID3D11SamplerState** DstD3D11Samplers = nullptr; + ShaderResourceCacheD3D11::CachedResource* DstUAVResources = nullptr; + ID3D11UnorderedAccessView** DstD3D11UAVs = nullptr; + DstCache.GetResourceArrays(DstCBs, DstD3D11CBs, DstSRVResources, DstD3D11SRVs, DstSamplers, DstD3D11Samplers, DstUAVResources, DstD3D11UAVs); + + HandleResources( + [&](const ConstBuffBindInfo&cb) + { + for(auto CBSlot = cb.Attribs.BindPoint; CBSlot < cb.Attribs.BindPoint+cb.Attribs.BindCount; ++CBSlot) + { + VERIFY_EXPR(CBSlot < m_pResourceCache->GetCBCount() && CBSlot < DstCache.GetCBCount()); + DstCBs[CBSlot] = CachedCBs[CBSlot]; + DstD3D11CBs[CBSlot] = d3d11CBs[CBSlot]; + } + }, + + [&](const TexAndSamplerBindInfo& ts) + { + for(auto SRVSlot = ts.Attribs.BindPoint; SRVSlot < ts.Attribs.BindPoint + ts.Attribs.BindCount; ++SRVSlot) + { + VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); + DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; + DstD3D11SRVs[SRVSlot] = d3d11SRVs[SRVSlot]; + if( ts.SamplerAttribs.IsValidBindPoint() ) + { + VERIFY_EXPR(ts.SamplerAttribs.BindCount == ts.Attribs.BindCount || ts.SamplerAttribs.BindCount == 1); + Uint32 SamplerSlot = ts.SamplerAttribs.BindPoint + (ts.SamplerAttribs.BindCount == 1 ? 0 : (SRVSlot - ts.Attribs.BindPoint)); + if( !ts.SamplerAttribs.IsStaticSampler() ) + { + VERIFY_EXPR( SamplerSlot < m_pResourceCache->GetSamplerCount() && SamplerSlot < DstCache.GetSamplerCount() ); + DstSamplers[SamplerSlot] = CachedSamplers[SamplerSlot]; + DstD3D11Samplers[SamplerSlot] = d3d11Samplers[SamplerSlot]; + } + else + { + VERIFY(DstSamplers[SamplerSlot].pSampler != nullptr && DstD3D11Samplers[SamplerSlot] != nullptr, "Static samplers must be initialized when shader resource cache is created"); + } + } + } + }, + + [&](const TexUAVBindInfo& uav) + { + for(auto UAVSlot = uav.Attribs.BindPoint; UAVSlot < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++UAVSlot) + { + VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); + DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; + DstD3D11UAVs[UAVSlot] = d3d11UAVs[UAVSlot]; + } + }, + + [&](const BuffSRVBindInfo& srv) + { + for(auto SRVSlot = srv.Attribs.BindPoint; SRVSlot < srv.Attribs.BindPoint + srv.Attribs.BindCount; ++SRVSlot) + { + VERIFY_EXPR(SRVSlot < m_pResourceCache->GetSRVCount() && SRVSlot < DstCache.GetSRVCount()); + DstSRVResources[SRVSlot] = CachedSRVResources[SRVSlot]; + DstD3D11SRVs[SRVSlot] = d3d11SRVs[SRVSlot]; + } + }, + + [&](const BuffUAVBindInfo& uav) + { + for(auto UAVSlot = uav.Attribs.BindPoint; UAVSlot < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++UAVSlot) + { + VERIFY_EXPR(UAVSlot < m_pResourceCache->GetUAVCount() && UAVSlot < DstCache.GetUAVCount()); + DstUAVResources[UAVSlot] = CachedUAVResources[UAVSlot]; + DstD3D11UAVs[UAVSlot] = d3d11UAVs[UAVSlot]; + } + } + ); +} + +void ShaderResourceLayoutD3D11::InitVariablesHashMap() +{ +#if USE_VARIABLE_HASH_MAP + // After all resources are loaded, we can populate shader variable hash map. + // The map contains raw pointers, but none of the arrays will ever change. + HandleResources( + [&](ConstBuffBindInfo&cb) + { + m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(cb.Attribs.Name), &cb ) ); + }, + + [&](TexAndSamplerBindInfo& ts) + { + m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(ts.Attribs.Name), &ts ) ); + }, + + [&](TexUAVBindInfo& uav) + { + m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(uav.Attribs.Name), &uav ) ); + }, + + [&](BuffSRVBindInfo& srv) + { + m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(srv.Attribs.Name), &srv ) ); + }, + + [&](BuffUAVBindInfo& uav) + { + m_VariableHash.insert( std::make_pair( Diligent::HashMapStringKey(uav.Attribs.Name), &uav ) ); + } + ); +#endif +} + +#define LOG_RESOURCE_BINDING_ERROR(ResType, pResource, Attribs, ArrayInd, ShaderName, ...)\ +{ \ + const auto &ResName = pResource->GetDesc().Name; \ + if(Attribs.BindCount>1) \ + LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " \"", ResName, "\" to variable \"", Attribs.Name,\ + "[", ArrayInd, "]\" in shader \"", ShaderName, "\". ", __VA_ARGS__ ) \ + else \ + LOG_ERROR_MESSAGE( "Failed to bind ", ResType, " \"", ResName, "\" to variable \"", Attribs.Name,\ + "\" in shader \"", ShaderName, "\". ", __VA_ARGS__ ) \ +} + +void ShaderResourceLayoutD3D11::ConstBuffBindInfo::BindResource(IDeviceObject *pBuffer, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY(dbgResLayout == nullptr || pResourceCache == dbgResLayout->m_pResourceCache, "Invalid resource cache"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + RefCntAutoPtr pBuffD3D11Impl; + if( pBuffer ) + { + // We cannot use ValidatedCast<> here as the resource retrieved from the + // resource mapping can be of wrong type + IBufferD3D11 *pBuffD3D11 = nullptr; + pBuffer->QueryInterface(IID_BufferD3D11, reinterpret_cast(&pBuffD3D11)); + if( pBuffD3D11 ) + { + pBuffD3D11Impl.Attach(ValidatedCast(pBuffD3D11)); + if( !(pBuffD3D11Impl->GetDesc().BindFlags & BIND_UNIFORM_BUFFER) ) + { + pBuffD3D11Impl.Release(); + LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Buffer was not created with BIND_UNIFORM_BUFFER flag.") + } + } + else + { + LOG_RESOURCE_BINDING_ERROR("buffer", pBuffer, Attribs, ArrayIndex, m_ParentResLayout.GetShaderName(), "Incorrect resource type: buffer is expected.") + } + } + + pResourceCache->SetCB(Attribs.BindPoint + ArrayIndex, std::move(pBuffD3D11Impl) ); +} + + + +bool ShaderResourceLayoutD3D11::ConstBuffBindInfo::IsBound(Uint32 ArrayIndex) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + return pResourceCache->IsCBBound(Attribs.BindPoint + ArrayIndex); +} + + + +#ifdef VERIFY_SHADER_BINDINGS +template ///< Type of the expected view enum +bool dbgVerifyViewType( const char *ViewTypeName, + TResourceViewType pViewD3D11, + const D3DShaderResourceAttribs& Attribs, + Uint32 ArrayIndex, + TViewTypeEnum dbgExpectedViewType, + const String &ShaderName ) +{ + const auto& ViewDesc = pViewD3D11->GetDesc(); + auto ViewType = ViewDesc.ViewType; + if (ViewType == dbgExpectedViewType) + { + return true; + } + else + { + const auto *ExpectedViewTypeName = GetViewTypeLiteralName( dbgExpectedViewType ); + const auto *ActualViewTypeName = GetViewTypeLiteralName( ViewType ); + LOG_RESOURCE_BINDING_ERROR(ViewTypeName, pViewD3D11, Attribs, ArrayIndex, ShaderName, + "Incorrect view type: ", ExpectedViewTypeName, " is expected, ", ActualViewTypeName, " provided." ); + return false; + } +} +#endif + +void ShaderResourceLayoutD3D11::TexAndSamplerBindInfo::BindResource( IDeviceObject *pView, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout ) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY(dbgResLayout == nullptr || pResourceCache == dbgResLayout->m_pResourceCache, "Invalid resource cache"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + // We cannot use ValidatedCast<> here as the resource retrieved from the + // resource mapping can be of wrong type + RefCntAutoPtr pViewD3D11(pView, IID_TextureViewD3D11); +#ifdef VERIFY_SHADER_BINDINGS + if(pView && !pViewD3D11) + LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, "", "Incorect resource type: texture view is expected.") + if(pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, TEXTURE_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) + pViewD3D11.Release(); +#endif + + if( SamplerAttribs.IsValidBindPoint() ) + { + VERIFY_EXPR(SamplerAttribs.BindCount == Attribs.BindCount || SamplerAttribs.BindCount == 1); + auto SamplerBindPoint = SamplerAttribs.BindPoint + (SamplerAttribs.BindCount != 1 ? ArrayIndex : 0); + if( !SamplerAttribs.IsStaticSampler() ) + { + SamplerD3D11Impl *pSamplerD3D11Impl = nullptr; + if( pViewD3D11 ) + { + pSamplerD3D11Impl = ValidatedCast(pViewD3D11->GetSampler()); +#ifdef VERIFY_SHADER_BINDINGS + if(pSamplerD3D11Impl==nullptr) + { + if(SamplerAttribs.BindCount > 1) + LOG_ERROR_MESSAGE( "Failed to bind sampler to variable \"", SamplerAttribs.Name, "[", ArrayIndex,"]\". Sampler is not set in the texture view \"", pViewD3D11->GetDesc().Name, "\"" ) + else + LOG_ERROR_MESSAGE( "Failed to bind sampler to variable \"", SamplerAttribs.Name, "\". Sampler is not set in the texture view \"", pViewD3D11->GetDesc().Name, "\"" ) + } +#endif + } + + pResourceCache->SetSampler(SamplerBindPoint, pSamplerD3D11Impl); + } + else + { + VERIFY_EXPR(SamplerAttribs.BindCount == Attribs.BindCount || SamplerAttribs.BindCount == 1); + VERIFY( pResourceCache->IsSamplerBound(SamplerBindPoint), "Static samplers must be bound once when shader cache is created" ); + } + } + + pResourceCache->SetTexSRV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); +} + + +void ShaderResourceLayoutD3D11::BuffSRVBindInfo::BindResource( IDeviceObject *pView, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout ) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY(dbgResLayout == nullptr || pResourceCache == dbgResLayout->m_pResourceCache, "Invalid resource cache"); + VERIFY(ArrayIndex < Attribs.BindCount, "Array index is out of range"); + + // We cannot use ValidatedCast<> here as the resource retrieved from the + // resource mapping can be of wrong type + RefCntAutoPtr pViewD3D11(pView, IID_BufferViewD3D11); +#ifdef VERIFY_SHADER_BINDINGS + if(pView && !pViewD3D11) + LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, "", "Incorect resource type: buffer view is expected.") + if(pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, BUFFER_VIEW_SHADER_RESOURCE, m_ParentResLayout.GetShaderName())) + pViewD3D11.Release(); +#endif + + pResourceCache->SetBufSRV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); +} + + +void ShaderResourceLayoutD3D11::TexUAVBindInfo::BindResource( IDeviceObject *pView, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout ) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY(dbgResLayout == nullptr || pResourceCache == dbgResLayout->m_pResourceCache, "Invalid resource cache"); + VERIFY(ArrayIndex < Attribs.BindCount, "Array index is out of range"); + + // We cannot use ValidatedCast<> here as the resource retrieved from the + // resource mapping can be of wrong type + RefCntAutoPtr pViewD3D11(pView, IID_TextureViewD3D11); +#ifdef VERIFY_SHADER_BINDINGS + if(pView && !pViewD3D11) + LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, "", "Incorect resource type: texture view is expected.") + if(pViewD3D11 && !dbgVerifyViewType("texture view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, TEXTURE_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName())) + pViewD3D11.Release(); +#endif + + pResourceCache->SetTexUAV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); +} + + +void ShaderResourceLayoutD3D11::BuffUAVBindInfo::BindResource( IDeviceObject *pView, Uint32 ArrayIndex, const ShaderResourceLayoutD3D11 *dbgResLayout ) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY(dbgResLayout == nullptr || pResourceCache == dbgResLayout->m_pResourceCache, "Invalid resource cache"); + VERIFY(ArrayIndex < Attribs.BindCount, "Array index is out of range"); + + // We cannot use ValidatedCast<> here as the resource retrieved from the + // resource mapping can be of wrong type + RefCntAutoPtr pViewD3D11(pView, IID_BufferViewD3D11); +#ifdef VERIFY_SHADER_BINDINGS + if(pView && !pViewD3D11) + LOG_RESOURCE_BINDING_ERROR("resource", pView, Attribs, ArrayIndex, "", "Incorect resource type: buffer view is expected.") + if(pViewD3D11 && !dbgVerifyViewType("buffer view", pViewD3D11.RawPtr(), Attribs, ArrayIndex, BUFFER_VIEW_UNORDERED_ACCESS, m_ParentResLayout.GetShaderName()) ) + pViewD3D11.Release(); +#endif + + pResourceCache->SetBufUAV(Attribs.BindPoint + ArrayIndex, std::move(pViewD3D11)); +} + + +bool ShaderResourceLayoutD3D11::TexAndSamplerBindInfo::IsBound(Uint32 ArrayIndex) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + return pResourceCache->IsSRVBound(Attribs.BindPoint + ArrayIndex, true); +} + + +bool ShaderResourceLayoutD3D11::BuffSRVBindInfo::IsBound(Uint32 ArrayIndex) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + return pResourceCache->IsSRVBound(Attribs.BindPoint + ArrayIndex, false); +} + +bool ShaderResourceLayoutD3D11::TexUAVBindInfo::IsBound(Uint32 ArrayIndex) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + return pResourceCache->IsUAVBound(Attribs.BindPoint + ArrayIndex, true); +} + +bool ShaderResourceLayoutD3D11::BuffUAVBindInfo::IsBound(Uint32 ArrayIndex) +{ + auto &pResourceCache = m_ParentResLayout.m_pResourceCache; + VERIFY(pResourceCache, "Resource cache is null"); + VERIFY_EXPR(ArrayIndex < Attribs.BindCount); + + return pResourceCache->IsUAVBound(Attribs.BindPoint + ArrayIndex, false); +} + + + +// Helper template class that facilitates binding CBs, SRVs, and UAVs +class BindResourceHelper +{ +public: + BindResourceHelper(IResourceMapping *pRM, Uint32 Fl, const ShaderResourceLayoutD3D11 *pSRL) : + pResourceMapping(pRM), + Flags(Fl), + pShaderResLayout(pSRL) + { + VERIFY(pResourceMapping != nullptr, "Resource mapping is null"); + VERIFY(pSRL != nullptr, "Shader resource layout is null"); + } + + template + void Bind( ResourceType &Res) + { + for(Uint16 elem=0; elem < Res.Attribs.BindCount; ++elem) + { + if( Flags & BIND_SHADER_RESOURCES_RESET_BINDINGS ) + Res.BindResource(nullptr, elem, pShaderResLayout); + + if( (Flags & BIND_SHADER_RESOURCES_UPDATE_UNRESOLVED) && Res.IsBound(elem) ) + return; + + const auto& VarName = Res.Attribs.Name; + RefCntAutoPtr pRes; + VERIFY_EXPR(pResourceMapping != nullptr); + pResourceMapping->GetResource( VarName.c_str(), &pRes, elem ); + if( pRes ) + { + // Call non-virtual function + Res.BindResource(pRes, elem, pShaderResLayout); + } + else + { + if( (Flags & BIND_SHADER_RESOURCES_ALL_RESOLVED) && !Res.IsBound(elem) ) + LOG_ERROR_MESSAGE( "Cannot bind resource to shader variable \"", VarName, "\": resource view not found in the resource mapping" ) + } + } + } + +private: + IResourceMapping* const pResourceMapping; + const Uint32 Flags; + const ShaderResourceLayoutD3D11 *pShaderResLayout; +}; + +void ShaderResourceLayoutD3D11::BindResources( IResourceMapping* pResourceMapping, Uint32 Flags, const ShaderResourceCacheD3D11 &dbgResourceCache ) +{ + VERIFY(&dbgResourceCache == m_pResourceCache, "Resource cache does not match the cache provided at initialization"); + + if( !pResourceMapping ) + { + LOG_ERROR_MESSAGE( "Failed to bind resources in shader \"", GetShaderName(), "\": resource mapping is null" ); + return; + } + + BindResourceHelper BindResHelper(pResourceMapping, Flags, this); + + HandleResources( + [&](ConstBuffBindInfo&cb) + { + BindResHelper.Bind(cb); + }, + + [&](TexAndSamplerBindInfo& ts) + { + BindResHelper.Bind(ts); + }, + + [&](TexUAVBindInfo& uav) + { + BindResHelper.Bind(uav); + }, + + [&](BuffSRVBindInfo& srv) + { + BindResHelper.Bind(srv); + }, + + [&](BuffUAVBindInfo& uav) + { + BindResHelper.Bind(uav); + } + ); +} + +IShaderVariable* ShaderResourceLayoutD3D11::GetShaderVariable(const Char* Name) +{ + IShaderVariable *pVar = nullptr; +#if USE_VARIABLE_HASH_MAP + // Name will be implicitly converted to HashMapStringKey without making a copy + auto it = m_VariableHash.find( Name ); + if( it != m_VariableHash.end() ) + pVar = it->second; +#else + for (Uint32 cb = 0; cb < m_NumCBs; ++cb) + if(GetCB(cb).Attribs.Name.compare(Name) == 0) + return &GetCB(cb); + for (Uint32 t = 0; t < m_NumTexSRVs; ++t) + if(GetTexSRV(t).Attribs.Name.compare(Name) == 0 ) + return &GetTexSRV(t); + for (Uint32 u = 0; u < m_NumTexUAVs; ++u) + if(GetTexUAV(u).Attribs.Name.compare(Name) == 0 ) + return &GetTexUAV(u); + for (Uint32 s = 0; s < m_NumBufSRVs; ++s) + if(GetBufSRV(s).Attribs.Name.compare(Name) == 0 ) + return &GetBufSRV(s); + for (Uint32 u = 0; u < m_NumBufUAVs; ++u) + if(GetBufUAV(u).Attribs.Name.compare(Name) == 0 ) + return &GetBufUAV(u); +#endif + if(pVar == nullptr) + { + LOG_ERROR_MESSAGE( "Shader variable \"", Name, "\" is not found in shader \"", GetShaderName(), "\". Attempts to set the variable will be silently ignored." ); + } + return pVar; +} + +const Char* ShaderResourceLayoutD3D11::GetShaderName()const +{ + return m_pResources->GetShaderName(); +} + +#ifdef VERIFY_SHADER_BINDINGS +void ShaderResourceLayoutD3D11::dbgVerifyBindings()const +{ + +#define LOG_MISSING_BINDING(VarType, Attrs, BindPt)\ +{ \ + if(Attrs.BindCount == 1) \ + LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable \"", Attrs.Name, "\" in shader \"", GetShaderName(), "\"" ) \ + else \ + LOG_ERROR_MESSAGE( "No resource is bound to ", VarType, " variable \"", Attrs.Name, "[", BindPt-Attrs.BindPoint, "]\" in shader \"", GetShaderName(), "\"" ) \ +} + + m_pResourceCache->dbgVerifyCacheConsistency(); + + // Use const_cast to avoid duplication of the HandleResources() function + // The function actually changes nothing + const_cast(this)->HandleResources( + [&](const ConstBuffBindInfo&cb) + { + for(auto BindPoint = cb.Attribs.BindPoint; BindPoint < cb.Attribs.BindPoint + cb.Attribs.BindCount; ++BindPoint) + { + if( !m_pResourceCache->IsCBBound(BindPoint) ) + LOG_MISSING_BINDING("constant buffer", cb.Attribs, BindPoint) + } + }, + + [&](const TexAndSamplerBindInfo& ts) + { + for(auto BindPoint = ts.Attribs.BindPoint; BindPoint < ts.Attribs.BindPoint + ts.Attribs.BindCount; ++BindPoint) + { + if( !m_pResourceCache->IsSRVBound(BindPoint, true) ) + LOG_MISSING_BINDING("texture", ts.Attribs, BindPoint) + + if( ts.SamplerAttribs.IsValidBindPoint() ) + { + VERIFY_EXPR(ts.SamplerAttribs.BindCount == ts.Attribs.BindCount || ts.SamplerAttribs.BindCount == 1); + auto SamBindPoint = ts.SamplerAttribs.BindPoint + ((ts.SamplerAttribs.BindCount == 1) ? 0 : (BindPoint - ts.Attribs.BindPoint) ); + if(!m_pResourceCache->IsSamplerBound(SamBindPoint) ) + LOG_MISSING_BINDING("sampler", ts.SamplerAttribs, SamBindPoint) + + // Verify that if single sampler is used for all texture array elements, all samplers set in the resource views are consistent + if (ts.Attribs.BindCount > 1 && ts.SamplerAttribs.BindCount == 1) + { + ShaderResourceCacheD3D11::CachedSampler *pCachedSamplers = nullptr; + ID3D11SamplerState **ppCachedD3D11Samplers = nullptr; + m_pResourceCache->GetSamplerArrays(pCachedSamplers, ppCachedD3D11Samplers); + VERIFY_EXPR(ts.SamplerAttribs.BindPoint < m_pResourceCache->GetSamplerCount()); + const auto &Sampler = pCachedSamplers[ts.SamplerAttribs.BindPoint]; + + ShaderResourceCacheD3D11::CachedResource *pCachedResources = nullptr; + ID3D11ShaderResourceView **ppCachedD3D11Resources = nullptr; + m_pResourceCache->GetSRVArrays(pCachedResources, ppCachedD3D11Resources); + VERIFY_EXPR(BindPoint < m_pResourceCache->GetSRVCount()); + auto &CachedResource = pCachedResources[BindPoint]; + if(CachedResource.pView) + { + auto *pTexView = ValidatedCast(CachedResource.pView.RawPtr()); + auto *pSampler = pTexView->GetSampler(); + if(pSampler != Sampler.pSampler.RawPtr()) + LOG_ERROR_MESSAGE( "All elements of texture array \"", ts.Attribs.Name, "\" in shader \"", GetShaderName(), "\" share the same sampler. However, the sampler set in view for element ", BindPoint - ts.Attribs.BindPoint, " does not match bound sampler. This may cause incorrect behavior on GL platform." ) + } + } + } + } + }, + + [&](const TexUAVBindInfo& uav) + { + for(auto BindPoint = uav.Attribs.BindPoint; BindPoint < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++BindPoint) + { + if( !m_pResourceCache->IsUAVBound(BindPoint, true) ) + LOG_MISSING_BINDING("texture UAV", uav.Attribs, BindPoint) + } + }, + + [&](const BuffSRVBindInfo& buf) + { + for(auto BindPoint = buf.Attribs.BindPoint; BindPoint < buf.Attribs.BindPoint + buf.Attribs.BindCount; ++BindPoint) + { + if( !m_pResourceCache->IsSRVBound(BindPoint, false) ) + LOG_MISSING_BINDING("buffer", buf.Attribs, BindPoint) + } + }, + + [&](const BuffUAVBindInfo& uav) + { + for(auto BindPoint = uav.Attribs.BindPoint; BindPoint < uav.Attribs.BindPoint + uav.Attribs.BindCount; ++BindPoint) + { + if( !m_pResourceCache->IsUAVBound(BindPoint, false) ) + LOG_MISSING_BINDING("buffer UAV", uav.Attribs, BindPoint) + } + } + ); +#undef LOG_MISSING_BINDING +} + +#endif +} diff --git a/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp new file mode 100644 index 00000000..d3b4f82d --- /dev/null +++ b/Graphics/GraphicsEngineD3D11/src/ShaderResourcesD3D11.cpp @@ -0,0 +1,435 @@ +/* Copyright 2015-2016 Egor Yusov + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. + * + * In no event and under no legal theory, whether in tort (including negligence), + * contract, or otherwise, unless required by applicable law (such as deliberate + * and grossly negligent acts) or agreed to in writing, shall any Contributor be + * liable for any damages, including any direct, indirect, special, incidental, + * or consequential damages of any character arising as a result of this License or + * out of the use or inability to use the software (including but not limited to damages + * for loss of goodwill, work stoppage, computer failure or malfunction, or any and + * all other commercial damages or losses), even if such Contributor has been advised + * of the possibility of such damages. + */ + +#include "pch.h" + +#include +#include "ShaderResourcesD3D11.h" +#include "ShaderBase.h" +#include "D3DShaderResourceLoader.h" +#include "ShaderResourceCacheD3D11.h" +#include "RenderDeviceD3D11Impl.h" + +namespace Diligent +{ + + +ShaderResourcesD3D11::ShaderResourcesD3D11(RenderDeviceD3D11Impl *pDeviceD3D11Impl, ID3DBlob *pShaderBytecode, const ShaderDesc &ShdrDesc) : + ShaderResources(GetRawAllocator(), ShdrDesc.ShaderType), + m_ShaderName(ShdrDesc.Name), + m_StaticSamplers(nullptr, STDDeleterRawMem< void >(GetRawAllocator())) +{ + Uint32 CurrCB = 0, CurrTexSRV = 0, CurrTexUAV = 0, CurrBufSRV = 0, CurrBufUAV = 0, CurrSampler = 0; + LoadD3DShaderResources( + pShaderBytecode, + + [&](Uint32 NumCBs, Uint32 NumTexSRVs, Uint32 NumTexUAVs, Uint32 NumBufSRVs, Uint32 NumBufUAVs, Uint32 NumSamplers) + { + Initialize(GetRawAllocator(), NumCBs, NumTexSRVs, NumTexUAVs, NumBufSRVs, NumBufUAVs, NumSamplers); + }, + + [&](D3DShaderResourceAttribs&& CBAttribs) + { + VERIFY( CBAttribs.BindPoint + CBAttribs.BindCount-1 <= MaxAllowedBindPoint, "CB bind point exceeds supported range" ) + m_MaxCBBindPoint = std::max(m_MaxCBBindPoint, static_cast(CBAttribs.BindPoint + CBAttribs.BindCount-1)); + + new (&GetCB(CurrCB++)) D3DShaderResourceAttribs(std::move(CBAttribs)); + }, + + [&](D3DShaderResourceAttribs &&TexUAV) + { + VERIFY( TexUAV.BindPoint + TexUAV.BindCount-1 <= MaxAllowedBindPoint, "Tex UAV bind point exceeds supported range" ) + m_MaxUAVBindPoint = std::max(m_MaxUAVBindPoint, static_cast(TexUAV.BindPoint + TexUAV.BindCount-1)); + + new (&GetTexUAV(CurrTexUAV++)) D3DShaderResourceAttribs( std::move(TexUAV) ); + }, + + [&](D3DShaderResourceAttribs &&BuffUAV) + { + VERIFY( BuffUAV.BindPoint + BuffUAV.BindCount-1 <= MaxAllowedBindPoint, "Buff UAV bind point exceeds supported range" ) + m_MaxUAVBindPoint = std::max(m_MaxUAVBindPoint, static_cast(BuffUAV.BindPoint + BuffUAV.BindCount-1)); + + new (&GetBufUAV(CurrBufUAV++)) D3DShaderResourceAttribs( std::move(BuffUAV) ); + }, + + [&](D3DShaderResourceAttribs &&BuffSRV) + { + VERIFY( BuffSRV.BindPoint + BuffSRV.BindCount-1 <= MaxAllowedBindPoint, "Buff SRV bind point exceeds supported range" ) + m_MaxSRVBindPoint = std::max(m_MaxSRVBindPoint, static_cast(BuffSRV.BindPoint + BuffSRV.BindCount-1)); + + new (&GetBufSRV(CurrBufSRV++)) D3DShaderResourceAttribs( std::move(BuffSRV) ); + }, + + [&](D3DShaderResourceAttribs &&SamplerAttribs) + { + VERIFY( SamplerAttribs.BindPoint + SamplerAttribs.BindCount-1 <= MaxAllowedBindPoint, "Sampler bind point exceeds supported range" ) + m_MaxSamplerBindPoint = std::max(m_MaxSamplerBindPoint, static_cast(SamplerAttribs.BindPoint + SamplerAttribs.BindCount-1)); + m_NumStaticSamplers += SamplerAttribs.IsStaticSampler() ? 1 : 0; + + new (&GetSampler(CurrSampler++)) D3DShaderResourceAttribs( std::move(SamplerAttribs) ); + }, + + [&](D3DShaderResourceAttribs &&TexAttribs) + { + VERIFY(CurrSampler == GetNumSamplers(), "All samplers must be initialized before texture SRVs" ); + + VERIFY( TexAttribs.BindPoint + TexAttribs.BindCount-1 <= MaxAllowedBindPoint, "Tex SRV bind point exceeds supported range" ) + m_MaxSRVBindPoint = std::max(m_MaxSRVBindPoint, static_cast(TexAttribs.BindPoint + TexAttribs.BindCount-1)); + + auto SamplerId = FindAssignedSamplerId(TexAttribs); + new (&GetTexSRV(CurrTexSRV++)) D3DShaderResourceAttribs( std::move(TexAttribs), SamplerId); + }, + + ShdrDesc, + D3DSamplerSuffix); + + VERIFY(CurrCB == GetNumCBs(), "Not all CBs are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called"); + VERIFY(CurrTexSRV == GetNumTexSRV(), "Not all Tex SRVs are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called" ); + VERIFY(CurrTexUAV == GetNumTexUAV(), "Not all Tex UAVs are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called" ); + VERIFY(CurrBufSRV == GetNumBufSRV(), "Not all Buf SRVs are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called" ); + VERIFY(CurrBufUAV == GetNumBufUAV(), "Not all Buf UAVs are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called" ); + VERIFY(CurrSampler == GetNumSamplers(), "Not all Samplers are initialized, which will result in a crash when ~D3DShaderResourceAttribs() is called" ); + + // Create static samplers + if (m_NumStaticSamplers > 0) + { + auto MemSize = m_NumStaticSamplers * sizeof(StaticSamplerAttribs); + auto *pRawMem = ALLOCATE(GetRawAllocator(), "Allocator for array of RefCntAutoPtr", MemSize); + m_StaticSamplers.reset( pRawMem ); + for (Uint32 i = 0; i < m_NumStaticSamplers; ++i) + { + new (&GetStaticSampler(i)) StaticSamplerAttribs; + } + Uint32 CurrStaticSam = 0; + for (Uint32 s = 0; s < GetNumSamplers(); ++s) + { + const auto &Sam = GetSampler(s); + if (Sam.IsStaticSampler()) + { + Uint32 ssd = 0; + for (; ssd < ShdrDesc.NumStaticSamplers; ++ssd) + { + const auto& StaticSamplerDesc = ShdrDesc.StaticSamplers[ssd]; + if ( StrCmpSuff(Sam.Name.c_str(), StaticSamplerDesc.TextureName, D3DSamplerSuffix)) + { + auto &StaticSamplerAttrs = GetStaticSampler(CurrStaticSam++); + StaticSamplerAttrs.first = &Sam; + pDeviceD3D11Impl->CreateSampler(StaticSamplerDesc.Desc, &StaticSamplerAttrs.second); + break; + } + } + VERIFY(ssd < ShdrDesc.NumStaticSamplers, "Static sampler was not found!") + } + } + VERIFY_EXPR(CurrStaticSam == m_NumStaticSamplers); + } +} + +ShaderResourcesD3D11::~ShaderResourcesD3D11() +{ + for(Uint32 ss=0; ss < m_NumStaticSamplers; ++ss) + GetStaticSampler(ss).~StaticSamplerAttribs(); +} + +void ShaderResourcesD3D11::InitStaticSamplers(ShaderResourceCacheD3D11 &ResourceCache)const +{ + auto NumCachedSamplers = ResourceCache.GetSamplerCount(); + for(Uint32 ss=0; ss < m_NumStaticSamplers; ++ss) + { + auto &StaticSampler = const_cast(this)->GetStaticSampler(ss); + const auto *pSamAttribs = StaticSampler.first; + auto EndBindPoint = std::min( static_cast(pSamAttribs->BindPoint) + pSamAttribs->BindCount, NumCachedSamplers); + for(Uint32 BindPoint = pSamAttribs->BindPoint; BindPoint < EndBindPoint; ++BindPoint ) + ResourceCache.SetSampler(BindPoint, ValidatedCast(StaticSampler.second.RawPtr()) ); + } +} + +#ifdef VERIFY_SHADER_BINDINGS +static String DbgMakeResourceName(const D3DShaderResourceAttribs &Attr, Uint32 BindPoint) +{ + VERIFY( BindPoint >= (Uint32)Attr.BindPoint && BindPoint < (Uint32)Attr.BindPoint + Attr.BindCount, "Bind point is out of allowed range") + if(Attr.BindCount == 1) + return Attr.Name; + else + return String(Attr.Name) + '[' + std::to_string(BindPoint - Attr.BindPoint) + ']'; +} + +void ShaderResourcesD3D11::dbgVerifyCommittedResources(ID3D11Buffer* CommittedD3D11CBs[], + ID3D11ShaderResourceView* CommittedD3D11SRVs[], + ID3D11Resource* CommittedD3D11SRVResources[], + ID3D11SamplerState* CommittedD3D11Samplers[], + ID3D11UnorderedAccessView* CommittedD3D11UAVs[], + ID3D11Resource* CommittedD3D11UAVResources[], + ShaderResourceCacheD3D11 &ResourceCache)const +{ + ShaderResourceCacheD3D11::CachedCB* CachedCBs = nullptr; + ID3D11Buffer** d3d11CBs = nullptr; + ShaderResourceCacheD3D11::CachedResource* CachedSRVResources = nullptr; + ID3D11ShaderResourceView** d3d11SRVs = nullptr; + ShaderResourceCacheD3D11::CachedSampler* CachedSamplers = nullptr; + ID3D11SamplerState** d3d11Samplers = nullptr; + ShaderResourceCacheD3D11::CachedResource* CachedUAVResources = nullptr; + ID3D11UnorderedAccessView** d3d11UAVs = nullptr; + ResourceCache.GetResourceArrays(CachedCBs, d3d11CBs, CachedSRVResources, d3d11SRVs, CachedSamplers, d3d11Samplers, CachedUAVResources, d3d11UAVs); + + ProcessResources( + nullptr, 0, + + [&](const D3DShaderResourceAttribs &cb) + { + for(auto BindPoint = cb.BindPoint; BindPoint < cb.BindPoint + cb.BindCount; ++BindPoint) + { + if (BindPoint >= ResourceCache.GetCBCount()) + { + LOG_ERROR_MESSAGE( "Unable to find constant buffer \"", DbgMakeResourceName(cb,BindPoint), "\" (slot ", BindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetCBCount()," CB slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &CB = CachedCBs[BindPoint]; + if(CB.pBuff == nullptr) + { + LOG_ERROR_MESSAGE( "Constant buffer \"", DbgMakeResourceName(cb,BindPoint), "\" (slot ", BindPoint, ") is not initialized in the resource cache." ); + continue; + } + + if (!(CB.pBuff->GetDesc().BindFlags & BIND_UNIFORM_BUFFER)) + { + LOG_ERROR_MESSAGE( "Buffer \"", CB.pBuff->GetDesc().Name, "\" committed in the device context as constant buffer to variable \"", DbgMakeResourceName(cb,BindPoint), "\" (slot ", BindPoint, ") in shader \"", GetShaderName(), "\" does not have BIND_UNIFORM_BUFFER flag" ); + continue; + } + + VERIFY_EXPR(d3d11CBs[BindPoint] == CB.pBuff->GetD3D11Buffer()); + + if(CommittedD3D11CBs[BindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 resource committed to constant buffer \"", DbgMakeResourceName(cb,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\"" ); + continue; + } + + if(CommittedD3D11CBs[BindPoint] != d3d11CBs[BindPoint] ) + { + LOG_ERROR_MESSAGE( "D3D11 resource committed to constant buffer \"", DbgMakeResourceName(cb,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + continue; + } + } + }, + + [&](const D3DShaderResourceAttribs& tex) + { + for(auto BindPoint = tex.BindPoint; BindPoint < tex.BindPoint + tex.BindCount; ++BindPoint) + { + if (BindPoint >= ResourceCache.GetSRVCount()) + { + LOG_ERROR_MESSAGE( "Unable to find texture SRV \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetSRVCount()," SRV slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &SRVRes = CachedSRVResources[BindPoint]; + if(SRVRes.pBuffer != nullptr) + { + LOG_ERROR_MESSAGE( "Unexpected buffer bound to variable \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint, "). Texture is expected." ); + continue; + } + if(SRVRes.pTexture == nullptr) + { + LOG_ERROR_MESSAGE( "Texture \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint, ") is not initialized in the resource cache." ); + continue; + } + + if (!(SRVRes.pTexture->GetDesc().BindFlags & BIND_SHADER_RESOURCE)) + { + LOG_ERROR_MESSAGE( "Texture \"", SRVRes.pTexture->GetDesc().Name, "\" committed in the device context as SRV to variable \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint, ") in shader \"", GetShaderName(), "\" does not have BIND_SHADER_RESOURCE flag" ); + } + + if(CommittedD3D11SRVs[BindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 resource committed to texture SRV \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\"" ); + continue; + } + + if(CommittedD3D11SRVs[BindPoint] != d3d11SRVs[BindPoint] ) + { + LOG_ERROR_MESSAGE( "D3D11 resource committed to texture SRV \"", DbgMakeResourceName(tex,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + continue; + } + } + + if( tex.IsValidSampler() ) + { + const auto& SamAttribs = GetSampler( tex.GetSamplerId() ); + VERIFY_EXPR(SamAttribs.IsValidBindPoint()); + VERIFY_EXPR(SamAttribs.BindCount == 1 || SamAttribs.BindCount == tex.BindCount); + + for(auto SamBindPoint = SamAttribs.BindPoint; SamBindPoint < SamAttribs.BindPoint + SamAttribs.BindCount; ++SamBindPoint) + { + if (SamBindPoint >= ResourceCache.GetSamplerCount()) + { + LOG_ERROR_MESSAGE( "Unable to find sampler \"", DbgMakeResourceName(SamAttribs,SamBindPoint), "\" (slot ", SamBindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetSamplerCount()," Sampler slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &Sam = CachedSamplers[SamBindPoint]; + if(Sam.pSampler == nullptr) + { + LOG_ERROR_MESSAGE( "Sampler \"", DbgMakeResourceName(SamAttribs,SamBindPoint), "\" (slot ", SamBindPoint, ") is not initialized in the resource cache." ); + continue; + } + VERIFY_EXPR(d3d11Samplers[SamBindPoint] == Sam.pSampler->GetD3D11SamplerState()); + + if(CommittedD3D11Samplers[SamBindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 sampler committed to variable \"", DbgMakeResourceName(SamAttribs,SamBindPoint), "\" (slot ", SamBindPoint ,") in shader \"", GetShaderName(), "\"" ); + continue; + } + + if(CommittedD3D11Samplers[SamBindPoint] != d3d11Samplers[SamBindPoint]) + { + LOG_ERROR_MESSAGE( "D3D11 sampler committed to variable \"", DbgMakeResourceName(SamAttribs,SamBindPoint), "\" (slot ", SamBindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + continue; + } + } + } + }, + + [&](const D3DShaderResourceAttribs &uav) + { + for(auto BindPoint = uav.BindPoint; BindPoint < uav.BindPoint + uav.BindCount; ++BindPoint) + { + if (BindPoint >= ResourceCache.GetUAVCount()) + { + LOG_ERROR_MESSAGE( "Unable to find texture UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetUAVCount()," UAV slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &UAVRes = CachedUAVResources[BindPoint]; + if(UAVRes.pBuffer != nullptr) + { + LOG_ERROR_MESSAGE( "Unexpected buffer bound to variable \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, "). Texture is expected." ); + continue; + } + if(UAVRes.pTexture == nullptr) + { + LOG_ERROR_MESSAGE( "Texture \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") is not initialized in the resource cache." ); + continue; + } + + if (!(UAVRes.pTexture->GetDesc().BindFlags & BIND_UNORDERED_ACCESS)) + { + LOG_ERROR_MESSAGE( "Texture \"", UAVRes.pTexture->GetDesc().Name, "\" committed in the device context as UAV to variable \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") in shader \"", GetShaderName(), "\" does not have BIND_UNORDERED_ACCESS flag" ); + } + + if(CommittedD3D11UAVs[BindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 resource committed to texture UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\"" ); + continue; + } + + if(CommittedD3D11UAVs[BindPoint] != d3d11UAVs[BindPoint] ) + { + LOG_ERROR_MESSAGE( "D3D11 resource committed to texture UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + continue; + } + } + }, + + + [&](const D3DShaderResourceAttribs &buf) + { + for(auto BindPoint = buf.BindPoint; BindPoint < buf.BindPoint + buf.BindCount; ++BindPoint) + { + if (BindPoint >= ResourceCache.GetSRVCount()) + { + LOG_ERROR_MESSAGE( "Unable to find buffer SRV \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetSRVCount()," SRV slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &SRVRes = CachedSRVResources[BindPoint]; + if(SRVRes.pTexture != nullptr) + { + LOG_ERROR_MESSAGE( "Unexpected texture bound to variable \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint, "). Buffer is expected." ); + continue; + } + if(SRVRes.pBuffer == nullptr) + { + LOG_ERROR_MESSAGE( "Buffer \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint ,") is not initialized in the resource cache." ); + continue; + } + + if (!(SRVRes.pBuffer->GetDesc().BindFlags & BIND_SHADER_RESOURCE)) + { + LOG_ERROR_MESSAGE( "Buffer \"", SRVRes.pBuffer->GetDesc().Name, "\" committed in the device context as SRV to variable \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint, ") in shader \"", GetShaderName(), "\" does not have BIND_SHADER_RESOURCE flag" ); + } + + if(CommittedD3D11SRVs[BindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 resource committed to buffer SRV \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\"" ); + continue; + } + + if(CommittedD3D11SRVs[BindPoint] != d3d11SRVs[BindPoint] ) + { + LOG_ERROR_MESSAGE( "D3D11 resource committed to buffer SRV \"", DbgMakeResourceName(buf,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + continue; + } + } + }, + + [&](const D3DShaderResourceAttribs &uav) + { + for(auto BindPoint = uav.BindPoint; BindPoint < uav.BindPoint + uav.BindCount; ++BindPoint) + { + if (BindPoint >= ResourceCache.GetUAVCount()) + { + LOG_ERROR_MESSAGE( "Unable to find buffer UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") in the resource cache: the cache reserves ", ResourceCache.GetUAVCount()," UAV slots only. This should never happen and may be the result of using wrong resource cache." ); + continue; + } + auto &UAVRes = CachedUAVResources[BindPoint]; + if(UAVRes.pTexture != nullptr) + { + LOG_ERROR_MESSAGE( "Unexpected texture bound to variable \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, "). Buffer is expected." ); + return; + } + if(UAVRes.pBuffer == nullptr) + { + LOG_ERROR_MESSAGE( "Buffer UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") is not initialized in the resource cache." ); + return; + } + + if (!(UAVRes.pBuffer->GetDesc().BindFlags & BIND_UNORDERED_ACCESS)) + { + LOG_ERROR_MESSAGE( "Buffer \"", UAVRes.pBuffer->GetDesc().Name, "\" committed in the device context as UAV to variable \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint, ") in shader \"", GetShaderName(), "\" does not have BIND_UNORDERED_ACCESS flag" ); + } + + if(CommittedD3D11UAVs[BindPoint] == nullptr ) + { + LOG_ERROR_MESSAGE( "No D3D11 resource committed to buffer UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\"" ); + return; + } + + if(CommittedD3D11UAVs[BindPoint] != d3d11UAVs[BindPoint] ) + { + LOG_ERROR_MESSAGE( "D3D11 resource committed to buffer UAV \"", DbgMakeResourceName(uav,BindPoint), "\" (slot ", BindPoint ,") in shader \"", GetShaderName(), "\" does not match the resource in the resource cache" ); + return; + } + } + } + ); +} +#endif + +} diff --git a/Graphics/GraphicsEngineD3D11/src/SwapChainD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/SwapChainD3D11Impl.cpp index d2f639a6..85b908f6 100644 --- a/Graphics/GraphicsEngineD3D11/src/SwapChainD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/SwapChainD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,24 +25,22 @@ #include "SwapChainD3D11Impl.h" #include "RenderDeviceD3D11Impl.h" #include "DeviceContextD3D11Impl.h" +#include using namespace Diligent; namespace Diligent { -SwapChainD3D11Impl::SwapChainD3D11Impl(const SwapChainDesc& SCDesc, - RenderDeviceD3D11Impl* pRenderDeviceD3D11, - DeviceContextD3D11Impl* pDeviceContextD3D11, - void* pNativeWndHandle) : - TSwapChainBase(pRenderDeviceD3D11, pDeviceContextD3D11, SCDesc) +SwapChainD3D11Impl::SwapChainD3D11Impl(IMemoryAllocator &Allocator, + const SwapChainDesc& SCDesc, + RenderDeviceD3D11Impl* pRenderDeviceD3D11, + DeviceContextD3D11Impl* pDeviceContextD3D11, + void* pNativeWndHandle) : + TSwapChainBase(Allocator, pRenderDeviceD3D11, pDeviceContextD3D11, SCDesc) { - auto *pDevice = pRenderDeviceD3D11->GetD3D11Device(); - - auto DXGIColorBuffFmt = TexFormatToDXGI_Format(m_SwapChainDesc.ColorBufferFormat); - -#if defined( PLATFORM_WINDOWS ) +#ifdef PLATFORM_WIN32 auto hWnd = reinterpret_cast(pNativeWndHandle); if( m_SwapChainDesc.Width == 0 || m_SwapChainDesc.Height == 0 ) @@ -52,50 +50,48 @@ SwapChainD3D11Impl::SwapChainD3D11Impl(const SwapChainDesc& SCDesc, m_SwapChainDesc.Width = rc.right - rc.left; m_SwapChainDesc.Height = rc.bottom - rc.top; } +#endif + + auto *pDevice = pRenderDeviceD3D11->GetD3D11Device(); + + auto DXGIColorBuffFmt = TexFormatToDXGI_Format(m_SwapChainDesc.ColorBufferFormat); + + DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; + swapChainDesc.Width = m_SwapChainDesc.Width; + swapChainDesc.Height = m_SwapChainDesc.Height; + // Flip model swapchains (DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL and DXGI_SWAP_EFFECT_FLIP_DISCARD) only support the following Formats: + // - DXGI_FORMAT_R16G16B16A16_FLOAT + // - DXGI_FORMAT_B8G8R8A8_UNORM + // - DXGI_FORMAT_R8G8B8A8_UNORM + // - DXGI_FORMAT_R10G10B10A2_UNORM + // If RGBA8_UNORM_SRGB swap chain is required, we will create RGBA8_UNORM swap chain, but + // create RGBA8_UNORM_SRGB render target view + swapChainDesc.Format = DXGIColorBuffFmt == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGIColorBuffFmt; + swapChainDesc.Stereo = FALSE; + swapChainDesc.SampleDesc.Count = 1; + swapChainDesc.SampleDesc.Quality = 0; + swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swapChainDesc.BufferCount = m_SwapChainDesc.BufferCount; + swapChainDesc.Scaling = DXGI_SCALING_NONE; + swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; // Not used + swapChainDesc.Flags = 0; + + CComPtr pSwapChain1; +#if defined( PLATFORM_WIN32 ) // This sequence obtains the DXGI factory that was used to create the Direct3D device above. CComPtr pDXGIDevice; pDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast( static_cast(&pDXGIDevice) ) ); CComPtr pDXGIAdapter; pDXGIDevice->GetAdapter(&pDXGIAdapter); - CComPtr pDXGIFactory; - pDXGIAdapter->GetParent(__uuidof(pDXGIFactory), reinterpret_cast( static_cast(&pDXGIFactory) )); - - DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory( &sd, sizeof( sd ) ); - sd.BufferCount = 1; - sd.BufferDesc.Width = m_SwapChainDesc.Width; - sd.BufferDesc.Height = m_SwapChainDesc.Height; - sd.BufferDesc.Format = DXGIColorBuffFmt; - sd.BufferDesc.RefreshRate.Numerator = 0; - sd.BufferDesc.RefreshRate.Denominator = 0; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd.OutputWindow = hWnd; - sd.SampleDesc.Count = m_SwapChainDesc.SamplesCount; - sd.SampleDesc.Quality = 0; - sd.Windowed = TRUE; - sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // Set this flag to enable an application to switch - // modes by calling IDXGISwapChain::ResizeTarget. When switching from windowed to full-screen mode, the - // display mode (or monitor resolution) will be changed to match the dimensions of the application window. - CHECK_D3D_RESULT_THROW( pDXGIFactory->CreateSwapChain(pDevice, &sd, &m_pSwapChain), - "Failed to create DXGI swap chain" ); - -#elif defined( PLATFORM_WINDOWS_STORE ) + CComPtr pDXGIFactory; + pDXGIAdapter->GetParent(__uuidof(pDXGIFactory), reinterpret_cast( static_cast(&pDXGIFactory) )); - DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 }; + CHECK_D3D_RESULT_THROW( pDXGIFactory->CreateSwapChainForHwnd(pDevice, hWnd, &swapChainDesc, nullptr, nullptr, &pSwapChain1), + "Failed to create DXGI swap chain" ); - swapChainDesc.Width = m_SwapChainDesc.Width; - swapChainDesc.Height = m_SwapChainDesc.Height; - swapChainDesc.Format = DXGIColorBuffFmt; - swapChainDesc.Stereo = false; - swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling. - swapChainDesc.SampleDesc.Quality = 0; - swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency. - swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect. - swapChainDesc.Flags = 0; - swapChainDesc.Scaling = DXGI_SCALING_NONE; - swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; +#elif defined( PLATFORM_UNIVERSAL_WINDOWS ) CComPtr pDXGIDevice; pDevice->QueryInterface(__uuidof(IDXGIDevice3), reinterpret_cast(static_cast(&pDXGIDevice))); @@ -103,8 +99,7 @@ SwapChainD3D11Impl::SwapChainD3D11Impl(const SwapChainDesc& SCDesc, pDXGIDevice->GetAdapter(&pDXGIAdapter); CComPtr pDXGIFactory; pDXGIAdapter->GetParent(__uuidof(pDXGIFactory), reinterpret_cast(static_cast(&pDXGIFactory))); - - CComPtr pSwapChain1; + HRESULT hr = pDXGIFactory->CreateSwapChainForCoreWindow( pDevice, reinterpret_cast(pNativeWndHandle), @@ -113,14 +108,14 @@ SwapChainD3D11Impl::SwapChainD3D11Impl(const SwapChainDesc& SCDesc, &pSwapChain1); CHECK_D3D_RESULT_THROW( hr, "Failed to create DXGI swap chain" ); - pSwapChain1->QueryInterface( __uuidof(m_pSwapChain), reinterpret_cast(static_cast(&m_pSwapChain)) ); - // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and // ensures that the application will only render after each VSync, minimizing power consumption. pDXGIDevice->SetMaximumFrameLatency( 1 ); #endif + pSwapChain1->QueryInterface( __uuidof(m_pSwapChain), reinterpret_cast(static_cast(&m_pSwapChain)) ); + CreateRTVandDSV(); } @@ -141,7 +136,13 @@ void SwapChainD3D11Impl::CreateRTVandDSV() CHECK_D3D_RESULT_THROW( m_pSwapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), reinterpret_cast( static_cast(&pBackBuffer) ) ), "Failed to get back buffer from swap chain" ); - CHECK_D3D_RESULT_THROW( pDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pRenderTargetView ), + D3D11_RENDER_TARGET_VIEW_DESC RTVDesc = {}; + RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; + // We need to explicitly specify RTV format, as we may need to create RGBA8_UNORM_SRGB RTV for + // a RGBA8_UNORM swap chain + RTVDesc.Format = TexFormatToDXGI_Format(m_SwapChainDesc.ColorBufferFormat); + RTVDesc.Texture2D.MipSlice = 0; + CHECK_D3D_RESULT_THROW( pDevice->CreateRenderTargetView( pBackBuffer, &RTVDesc, &m_pRenderTargetView ), "Failed to get RTV for the back buffer" ); // Create depth buffer @@ -172,7 +173,7 @@ IMPLEMENT_QUERY_INTERFACE( SwapChainD3D11Impl, IID_SwapChainD3D11, TSwapChainBas void SwapChainD3D11Impl::Present() { UINT SyncInterval = 0; -#ifdef PLATFORM_WINDOWS_STORE +#ifdef PLATFORM_UNIVERSAL_WINDOWS SyncInterval = 1; // Interval 0 is not supported on Windows Phone #endif @@ -193,13 +194,11 @@ void SwapChainD3D11Impl::Present() m_pSwapChain->Present( SyncInterval, 0 ); -#ifdef PLATFORM_WINDOWS_STORE // A successful Present call for DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL SwapChains unbinds // backbuffer 0 from all GPU writeable bind points. // We need to rebind all render targets to make sure that // the back buffer is not unbound pImmediateCtxD3D11->RebindRenderTargets(); -#endif } void SwapChainD3D11Impl::Resize( Uint32 NewWidth, Uint32 NewHeight ) diff --git a/Graphics/GraphicsEngineD3D11/src/Texture1D_D3D11.cpp b/Graphics/GraphicsEngineD3D11/src/Texture1D_D3D11.cpp index 75eaab86..7a6cba6e 100644 --- a/Graphics/GraphicsEngineD3D11/src/Texture1D_D3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/Texture1D_D3D11.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,12 @@ namespace Diligent { -Texture1D_D3D11 :: Texture1D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData /*= TextureData()*/) : - TextureBaseD3D11(pRenderDeviceD3D11, TexDesc, InitData) +Texture1D_D3D11 :: Texture1D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + RenderDeviceD3D11Impl *pRenderDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData /*= TextureData()*/) : + TextureBaseD3D11(TexObjAllocator, TexViewObjAllocator, pRenderDeviceD3D11, TexDesc, InitData) { auto D3D11TexFormat = TexFormatToDXGI_Format(m_Desc.Format, m_Desc.BindFlags); auto D3D11BindFlags = BindFlagsToD3D11BindFlags(m_Desc.BindFlags); @@ -51,7 +55,7 @@ Texture1D_D3D11 :: Texture1D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, co MiscFlags }; - std::vector D3D11InitData; + std::vector> D3D11InitData( STD_ALLOCATOR_RAW_MEM(D3D11_SUBRESOURCE_DATA, GetRawAllocator(), "Allocator for vector") ); PrepareD3D11InitData(InitData, Tex1DDesc.ArraySize * Tex1DDesc.MipLevels, D3D11InitData); ID3D11Texture1D *ptex1D = nullptr; @@ -69,8 +73,8 @@ void Texture1D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV VERIFY( ppD3D11SRV && *ppD3D11SRV == nullptr, "SRV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( SRVDesc.ViewType == TEXTURE_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected" ); - if( !(SRVDesc.TextureType == TEXTURE_TYPE_1D || SRVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY) ) - LOG_ERROR_AND_THROW( "Unsupported texture type. Only TEXTURE_TYPE_1D or TEXTURE_TYPE_1D_ARRAY is allowed" ); + if( !(SRVDesc.TextureDim == RESOURCE_DIM_TEX_1D || SRVDesc.TextureDim == RESOURCE_DIM_TEX_1D_ARRAY) ) + LOG_ERROR_AND_THROW( "Unsupported texture type. Only RESOURCE_DIM_TEX_1D or RESOURCE_DIM_TEX_1D_ARRAY is allowed" ); if( SRVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -78,27 +82,7 @@ void Texture1D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV } D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SRVDesc; - memset(&D3D11_SRVDesc, 0, sizeof(D3D11_SRVDesc)); - D3D11_SRVDesc.Format = TexFormatToDXGI_Format(SRVDesc.Format, BIND_SHADER_RESOURCE); - - if( SRVDesc.TextureType == TEXTURE_TYPE_1D ) - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - D3D11_SRVDesc.Texture1D.MipLevels = SRVDesc.NumMipLevels; - D3D11_SRVDesc.Texture1D.MostDetailedMip = SRVDesc.MostDetailedMip; - } - else if( SRVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY ) - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; - D3D11_SRVDesc.Texture1DArray.ArraySize = SRVDesc.NumArraySlices; - D3D11_SRVDesc.Texture1DArray.FirstArraySlice = SRVDesc.FirstArraySlice; - D3D11_SRVDesc.Texture1DArray.MipLevels = SRVDesc.NumMipLevels; - D3D11_SRVDesc.Texture1DArray.MostDetailedMip = SRVDesc.MostDetailedMip; - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_SRV_DESC(SRVDesc, D3D11_SRVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateShaderResourceView( m_pd3d11Texture, &D3D11_SRVDesc, ppD3D11SRV ), @@ -110,8 +94,8 @@ void Texture1D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie VERIFY( ppD3D11RTV && *ppD3D11RTV == nullptr, "RTV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( RTVDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); - if( !(RTVDesc.TextureType == TEXTURE_TYPE_1D || RTVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY ) ) - LOG_ERROR_AND_THROW( "Unsupported texture type. Only TEXTURE_TYPE_1D or TEXTURE_TYPE_1D_ARRAY is allowed" ); + if( !(RTVDesc.TextureDim == RESOURCE_DIM_TEX_1D || RTVDesc.TextureDim == RESOURCE_DIM_TEX_1D_ARRAY ) ) + LOG_ERROR_AND_THROW( "Unsupported texture type. Only RESOURCE_DIM_TEX_1D or RESOURCE_DIM_TEX_1D_ARRAY is allowed" ); if( RTVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -119,25 +103,7 @@ void Texture1D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie } D3D11_RENDER_TARGET_VIEW_DESC D3D11_RTVDesc; - memset(&D3D11_RTVDesc, 0, sizeof(D3D11_RTVDesc)); - D3D11_RTVDesc.Format = TexFormatToDXGI_Format(RTVDesc.Format, BIND_RENDER_TARGET); - - if( RTVDesc.TextureType == TEXTURE_TYPE_1D ) - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D; - D3D11_RTVDesc.Texture1D.MipSlice = RTVDesc.MostDetailedMip; - } - else if( RTVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY ) - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY; - D3D11_RTVDesc.Texture1DArray.ArraySize = RTVDesc.NumArraySlices; - D3D11_RTVDesc.Texture1DArray.FirstArraySlice = RTVDesc.FirstArraySlice; - D3D11_RTVDesc.Texture1DArray.MipSlice = RTVDesc.MostDetailedMip; - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_RTV_DESC(RTVDesc, D3D11_RTVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateRenderTargetView( m_pd3d11Texture, &D3D11_RTVDesc, ppD3D11RTV ), @@ -149,8 +115,8 @@ void Texture1D_D3D11::CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilVie VERIFY( ppD3D11DSV && *ppD3D11DSV == nullptr, "DSV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( DSVDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); - if( !(DSVDesc.TextureType == TEXTURE_TYPE_1D || DSVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY) ) - LOG_ERROR_AND_THROW("Unsupported texture type. Only TEXTURE_TYPE_1D or TEXTURE_TYPE_1D_ARRAY is allowed"); + if( !(DSVDesc.TextureDim == RESOURCE_DIM_TEX_1D || DSVDesc.TextureDim == RESOURCE_DIM_TEX_1D_ARRAY) ) + LOG_ERROR_AND_THROW("Unsupported texture type. Only RESOURCE_DIM_TEX_1D or RESOURCE_DIM_TEX_1D_ARRAY is allowed"); if( DSVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -158,25 +124,7 @@ void Texture1D_D3D11::CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilVie } D3D11_DEPTH_STENCIL_VIEW_DESC D3D11_DSVDesc; - memset(&D3D11_DSVDesc, 0, sizeof(D3D11_DSVDesc)); - D3D11_DSVDesc.Format = TexFormatToDXGI_Format(DSVDesc.Format, BIND_DEPTH_STENCIL); - - if( DSVDesc.TextureType == TEXTURE_TYPE_1D ) - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1D; - D3D11_DSVDesc.Texture1D.MipSlice = DSVDesc.MostDetailedMip; - } - else if( DSVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY ) - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE1DARRAY; - D3D11_DSVDesc.Texture1DArray.ArraySize = DSVDesc.NumArraySlices; - D3D11_DSVDesc.Texture1DArray.FirstArraySlice = DSVDesc.FirstArraySlice; - D3D11_DSVDesc.Texture1DArray.MipSlice = DSVDesc.MostDetailedMip; - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_DSV_DESC(DSVDesc, D3D11_DSVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateDepthStencilView( m_pd3d11Texture, &D3D11_DSVDesc, ppD3D11DSV ), @@ -188,8 +136,8 @@ void Texture1D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess VERIFY( ppD3D11UAV && *ppD3D11UAV == nullptr, "UAV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( UAVDesc.ViewType == TEXTURE_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected" ); - if( !(UAVDesc.TextureType == TEXTURE_TYPE_1D || UAVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY) ) - LOG_ERROR_AND_THROW("Unsupported texture type. Only TEXTURE_TYPE_1D or TEXTURE_TYPE_1D_ARRAY is allowed"); + if( !(UAVDesc.TextureDim == RESOURCE_DIM_TEX_1D || UAVDesc.TextureDim == RESOURCE_DIM_TEX_1D_ARRAY) ) + LOG_ERROR_AND_THROW("Unsupported texture type. Only RESOURCE_DIM_TEX_1D or RESOURCE_DIM_TEX_1D_ARRAY is allowed"); if( UAVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -197,26 +145,7 @@ void Texture1D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess } D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UAVDesc; - memset(&D3D11_UAVDesc, 0, sizeof(D3D11_UAVDesc)); - D3D11_UAVDesc.Format = TexFormatToDXGI_Format(UAVDesc.Format, BIND_UNORDERED_ACCESS); - - if( UAVDesc.TextureType == TEXTURE_TYPE_1D ) - { - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1D; - D3D11_UAVDesc.Texture1D.MipSlice = UAVDesc.MostDetailedMip; - } - else if( UAVDesc.TextureType == TEXTURE_TYPE_1D_ARRAY ) - { - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE1DARRAY; - D3D11_UAVDesc.Texture1DArray.ArraySize = UAVDesc.NumArraySlices; - D3D11_UAVDesc.Texture1DArray.FirstArraySlice = UAVDesc.FirstArraySlice; - D3D11_UAVDesc.Texture1DArray.MipSlice = UAVDesc.MostDetailedMip; - } - else - { - UNEXPECTED( "Unexpected view type" ); - } - + TextureViewDesc_to_D3D11_UAV_DESC(UAVDesc, D3D11_UAVDesc); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateUnorderedAccessView( m_pd3d11Texture, &D3D11_UAVDesc, ppD3D11UAV ), diff --git a/Graphics/GraphicsEngineD3D11/src/Texture2D_D3D11.cpp b/Graphics/GraphicsEngineD3D11/src/Texture2D_D3D11.cpp index fc34d18d..f2fef036 100644 --- a/Graphics/GraphicsEngineD3D11/src/Texture2D_D3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/Texture2D_D3D11.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,14 +29,20 @@ namespace Diligent { -Texture2D_D3D11 :: Texture2D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData /*= TextureData()*/) : - TextureBaseD3D11(pRenderDeviceD3D11, TexDesc, InitData) +Texture2D_D3D11 :: Texture2D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + RenderDeviceD3D11Impl *pRenderDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData /*= TextureData()*/) : + TextureBaseD3D11(TexObjAllocator, TexViewObjAllocator, pRenderDeviceD3D11, TexDesc, InitData) { auto D3D11TexFormat = TexFormatToDXGI_Format(m_Desc.Format, m_Desc.BindFlags); auto D3D11BindFlags = BindFlagsToD3D11BindFlags(m_Desc.BindFlags); auto D3D11CPUAccessFlags = CPUAccessFlagsToD3D11CPUAccessFlags(m_Desc.CPUAccessFlags); auto D3D11Usage = UsageToD3D11Usage(m_Desc.Usage); UINT MiscFlags = MiscTextureFlagsToD3D11Flags(m_Desc.MiscFlags); + if(m_Desc.Type == RESOURCE_DIM_TEX_CUBE || m_Desc.Type == RESOURCE_DIM_TEX_CUBE_ARRAY) + MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; DXGI_SAMPLE_DESC D3D11SampleDesc = {m_Desc.SampleCount, 0}; auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); @@ -54,7 +60,7 @@ Texture2D_D3D11 :: Texture2D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, co MiscFlags }; - std::vector D3D11InitData; + std::vector> D3D11InitData( STD_ALLOCATOR_RAW_MEM(D3D11_SUBRESOURCE_DATA, GetRawAllocator(), "Allocator for vector") ); PrepareD3D11InitData(InitData, Tex2DDesc.ArraySize * Tex2DDesc.MipLevels, D3D11InitData); ID3D11Texture2D *ptex2D = nullptr; @@ -72,8 +78,9 @@ void Texture2D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV VERIFY( ppD3D11SRV && *ppD3D11SRV == nullptr, "SRV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( SRVDesc.ViewType == TEXTURE_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected" ); - if( !(SRVDesc.TextureType == TEXTURE_TYPE_2D || SRVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY) ) - LOG_ERROR_AND_THROW("Unsupported texture type. Only TEXTURE_TYPE_2D or TEXTURE_TYPE_2D_ARRAY is allowed"); + if( !(SRVDesc.TextureDim == RESOURCE_DIM_TEX_2D || SRVDesc.TextureDim == RESOURCE_DIM_TEX_2D_ARRAY || + SRVDesc.TextureDim == RESOURCE_DIM_TEX_CUBE || SRVDesc.TextureDim == RESOURCE_DIM_TEX_CUBE_ARRAY) ) + LOG_ERROR_AND_THROW("Unsupported texture type. Only RESOURCE_DIM_TEX_2D, RESOURCE_DIM_TEX_2D_ARRAY, RESOURCE_DIM_TEX_CUBE, or RESOURCE_DIM_TEX_CUBE_ARRAY is allowed"); if( SRVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -81,45 +88,7 @@ void Texture2D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV } D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SRVDesc; - memset(&D3D11_SRVDesc, 0, sizeof(D3D11_SRVDesc)); - D3D11_SRVDesc.Format = TexFormatToDXGI_Format(SRVDesc.Format, BIND_SHADER_RESOURCE); - - - if( SRVDesc.TextureType == TEXTURE_TYPE_2D ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS; - D3D11_SRVDesc.Texture2DMS.UnusedField_NothingToDefine = 0; - } - else - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - D3D11_SRVDesc.Texture2D.MipLevels = SRVDesc.NumMipLevels; - D3D11_SRVDesc.Texture2D.MostDetailedMip = SRVDesc.MostDetailedMip; - } - } - else if( SRVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY; - D3D11_SRVDesc.Texture2DMSArray.ArraySize = SRVDesc.NumArraySlices; - D3D11_SRVDesc.Texture2DMSArray.FirstArraySlice = SRVDesc.FirstArraySlice; - } - else - { - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; - D3D11_SRVDesc.Texture2DArray.ArraySize = SRVDesc.NumArraySlices; - D3D11_SRVDesc.Texture2DArray.FirstArraySlice = SRVDesc.FirstArraySlice; - D3D11_SRVDesc.Texture2DArray.MipLevels = SRVDesc.NumMipLevels; - D3D11_SRVDesc.Texture2DArray.MostDetailedMip = SRVDesc.MostDetailedMip; - } - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_SRV_DESC(SRVDesc, D3D11_SRVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateShaderResourceView( m_pd3d11Texture, &D3D11_SRVDesc, ppD3D11SRV ), @@ -131,8 +100,8 @@ void Texture2D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie VERIFY( ppD3D11RTV && *ppD3D11RTV == nullptr, "RTV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( RTVDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); - if( !(RTVDesc.TextureType == TEXTURE_TYPE_2D || RTVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY) ) - LOG_ERROR_AND_THROW( "Unsupported texture type. Only TEXTURE_TYPE_2D or TEXTURE_TYPE_2D_ARRAY is allowed" ); + if( !(RTVDesc.TextureDim == RESOURCE_DIM_TEX_2D || RTVDesc.TextureDim == RESOURCE_DIM_TEX_2D_ARRAY) ) + LOG_ERROR_AND_THROW( "Unsupported texture type. Only RESOURCE_DIM_TEX_2D or RESOURCE_DIM_TEX_2D_ARRAY is allowed" ); if( RTVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -140,43 +109,7 @@ void Texture2D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie } D3D11_RENDER_TARGET_VIEW_DESC D3D11_RTVDesc; - memset(&D3D11_RTVDesc, 0, sizeof(D3D11_RTVDesc)); - D3D11_RTVDesc.Format = TexFormatToDXGI_Format(RTVDesc.Format, BIND_RENDER_TARGET); - - if( RTVDesc.TextureType == TEXTURE_TYPE_2D ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; - D3D11_RTVDesc.Texture2DMS.UnusedField_NothingToDefine = 0; - } - else - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; - D3D11_RTVDesc.Texture2D.MipSlice = RTVDesc.MostDetailedMip; - } - } - else if( RTVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY; - D3D11_RTVDesc.Texture2DMSArray.ArraySize = RTVDesc.NumArraySlices; - D3D11_RTVDesc.Texture2DMSArray.FirstArraySlice = RTVDesc.FirstArraySlice; - } - else - { - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; - D3D11_RTVDesc.Texture2DArray.ArraySize = RTVDesc.NumArraySlices; - D3D11_RTVDesc.Texture2DArray.FirstArraySlice = RTVDesc.FirstArraySlice; - D3D11_RTVDesc.Texture2DArray.MipSlice = RTVDesc.MostDetailedMip; - } - } - else - { - UNEXPECTED( "Unexpected view type" ); - } - + TextureViewDesc_to_D3D11_RTV_DESC(RTVDesc, D3D11_RTVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateRenderTargetView( m_pd3d11Texture, &D3D11_RTVDesc, ppD3D11RTV ), @@ -188,8 +121,8 @@ void Texture2D_D3D11::CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilVie VERIFY( ppD3D11DSV && *ppD3D11DSV == nullptr, "DSV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( DSVDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); - if( !(DSVDesc.TextureType == TEXTURE_TYPE_2D || DSVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY) ) - LOG_ERROR_AND_THROW("Unsupported texture type. Only TEXTURE_TYPE_2D or TEXTURE_TYPE_2D_ARRAY is allowed"); + if( !(DSVDesc.TextureDim == RESOURCE_DIM_TEX_2D || DSVDesc.TextureDim == RESOURCE_DIM_TEX_2D_ARRAY) ) + LOG_ERROR_AND_THROW("Unsupported texture type. Only RESOURCE_DIM_TEX_2D or RESOURCE_DIM_TEX_2D_ARRAY is allowed"); if( DSVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -197,42 +130,7 @@ void Texture2D_D3D11::CreateDSV( TextureViewDesc &DSVDesc, ID3D11DepthStencilVie } D3D11_DEPTH_STENCIL_VIEW_DESC D3D11_DSVDesc; - memset(&D3D11_DSVDesc, 0, sizeof(D3D11_DSVDesc)); - D3D11_DSVDesc.Format = TexFormatToDXGI_Format(DSVDesc.Format, BIND_DEPTH_STENCIL); - - if( DSVDesc.TextureType == TEXTURE_TYPE_2D ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; - D3D11_DSVDesc.Texture2DMS.UnusedField_NothingToDefine = 0; - } - else - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; - D3D11_DSVDesc.Texture2D.MipSlice = DSVDesc.MostDetailedMip; - } - } - else if( DSVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY ) - { - if( m_Desc.SampleCount > 1 ) - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY; - D3D11_DSVDesc.Texture2DMSArray.ArraySize = DSVDesc.NumArraySlices; - D3D11_DSVDesc.Texture2DMSArray.FirstArraySlice = DSVDesc.FirstArraySlice; - } - else - { - D3D11_DSVDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY; - D3D11_DSVDesc.Texture2DArray.ArraySize = DSVDesc.NumArraySlices; - D3D11_DSVDesc.Texture2DArray.FirstArraySlice = DSVDesc.FirstArraySlice; - D3D11_DSVDesc.Texture2DArray.MipSlice = DSVDesc.MostDetailedMip; - } - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_DSV_DESC(DSVDesc, D3D11_DSVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateDepthStencilView( m_pd3d11Texture, &D3D11_DSVDesc, ppD3D11DSV ), @@ -247,8 +145,8 @@ void Texture2D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess LOG_ERROR_AND_THROW("UAVs are not allowed for multisampled resources"); VERIFY( UAVDesc.ViewType == TEXTURE_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected" ); - if( !(UAVDesc.TextureType == TEXTURE_TYPE_2D || UAVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY) ) - LOG_ERROR_AND_THROW( "Unsupported texture type. Only TEXTURE_TYPE_2D or TEXTURE_TYPE_2D_ARRAY is allowed" ); + if( !(UAVDesc.TextureDim == RESOURCE_DIM_TEX_2D || UAVDesc.TextureDim == RESOURCE_DIM_TEX_2D_ARRAY) ) + LOG_ERROR_AND_THROW( "Unsupported texture type. Only RESOURCE_DIM_TEX_2D or RESOURCE_DIM_TEX_2D_ARRAY is allowed" ); if( UAVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -256,25 +154,7 @@ void Texture2D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess } D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UAVDesc; - memset(&D3D11_UAVDesc, 0, sizeof(D3D11_UAVDesc)); - D3D11_UAVDesc.Format = TexFormatToDXGI_Format(UAVDesc.Format, BIND_UNORDERED_ACCESS); - - if( UAVDesc.TextureType == TEXTURE_TYPE_2D ) - { - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; - D3D11_UAVDesc.Texture2D.MipSlice = UAVDesc.MostDetailedMip; - } - else if( UAVDesc.TextureType == TEXTURE_TYPE_2D_ARRAY ) - { - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY; - D3D11_UAVDesc.Texture2DArray.ArraySize = UAVDesc.NumArraySlices; - D3D11_UAVDesc.Texture2DArray.FirstArraySlice = UAVDesc.FirstArraySlice; - D3D11_UAVDesc.Texture2DArray.MipSlice = UAVDesc.MostDetailedMip; - } - else - { - UNEXPECTED( "Unexpected view type" ); - } + TextureViewDesc_to_D3D11_UAV_DESC(UAVDesc, D3D11_UAVDesc); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateUnorderedAccessView( m_pd3d11Texture, &D3D11_UAVDesc, ppD3D11UAV ), diff --git a/Graphics/GraphicsEngineD3D11/src/Texture3D_D3D11.cpp b/Graphics/GraphicsEngineD3D11/src/Texture3D_D3D11.cpp index 9546660e..bb7bd484 100644 --- a/Graphics/GraphicsEngineD3D11/src/Texture3D_D3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/Texture3D_D3D11.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,12 @@ namespace Diligent { -Texture3D_D3D11 :: Texture3D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData /*= TextureData()*/) : - TextureBaseD3D11(pRenderDeviceD3D11, TexDesc, InitData) +Texture3D_D3D11 :: Texture3D_D3D11(FixedBlockMemoryAllocator &TexObjAllocator, + FixedBlockMemoryAllocator &TexViewObjAllocator, + RenderDeviceD3D11Impl *pRenderDeviceD3D11, + const TextureDesc& TexDesc, + const TextureData &InitData /*= TextureData()*/) : + TextureBaseD3D11(TexObjAllocator, TexViewObjAllocator, pRenderDeviceD3D11, TexDesc, InitData) { auto D3D11TexFormat = TexFormatToDXGI_Format(m_Desc.Format, m_Desc.BindFlags); auto D3D11BindFlags = BindFlagsToD3D11BindFlags(m_Desc.BindFlags); @@ -52,7 +56,7 @@ Texture3D_D3D11 :: Texture3D_D3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, co MiscFlags }; - std::vector D3D11InitData; + std::vector> D3D11InitData( STD_ALLOCATOR_RAW_MEM(D3D11_SUBRESOURCE_DATA, GetRawAllocator(), "Allocator for vector") ); PrepareD3D11InitData(InitData, Tex3DDesc.MipLevels, D3D11InitData); ID3D11Texture3D *ptex3D = nullptr; @@ -66,8 +70,8 @@ void Texture3D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV VERIFY( ppD3D11SRV && *ppD3D11SRV == nullptr, "SRV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( SRVDesc.ViewType == TEXTURE_VIEW_SHADER_RESOURCE, "Incorrect view type: shader resource is expected" ); - if( SRVDesc.TextureType != TEXTURE_TYPE_3D ) - LOG_ERROR_AND_THROW("Unsupported texture view type. Only TEXTURE_TYPE_3D is allowed"); + if( SRVDesc.TextureDim != RESOURCE_DIM_TEX_3D ) + LOG_ERROR_AND_THROW("Unsupported texture view type. Only RESOURCE_DIM_TEX_3D is allowed"); if( SRVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -75,12 +79,7 @@ void Texture3D_D3D11::CreateSRV( TextureViewDesc &SRVDesc, ID3D11ShaderResourceV } D3D11_SHADER_RESOURCE_VIEW_DESC D3D11_SRVDesc; - memset(&D3D11_SRVDesc, 0, sizeof(D3D11_SRVDesc)); - D3D11_SRVDesc.Format = TexFormatToDXGI_Format(SRVDesc.Format, BIND_SHADER_RESOURCE); - - D3D11_SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - D3D11_SRVDesc.Texture3D.MipLevels = SRVDesc.NumMipLevels; - D3D11_SRVDesc.Texture3D.MostDetailedMip = SRVDesc.MostDetailedMip; + TextureViewDesc_to_D3D11_SRV_DESC(SRVDesc, D3D11_SRVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateShaderResourceView( m_pd3d11Texture, &D3D11_SRVDesc, ppD3D11SRV ), @@ -92,8 +91,8 @@ void Texture3D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie VERIFY( ppD3D11RTV && *ppD3D11RTV == nullptr, "RTV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( RTVDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); - if( RTVDesc.TextureType != TEXTURE_TYPE_3D ) - LOG_ERROR_AND_THROW( "Unsupported texture view type. Only TEXTURE_TYPE_3D is allowed" ); + if( RTVDesc.TextureDim != RESOURCE_DIM_TEX_3D ) + LOG_ERROR_AND_THROW( "Unsupported texture view type. Only RESOURCE_DIM_TEX_3D is allowed" ); if( RTVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -101,13 +100,7 @@ void Texture3D_D3D11::CreateRTV( TextureViewDesc &RTVDesc, ID3D11RenderTargetVie } D3D11_RENDER_TARGET_VIEW_DESC D3D11_RTVDesc; - memset(&D3D11_RTVDesc, 0, sizeof(D3D11_RTVDesc)); - D3D11_RTVDesc.Format = TexFormatToDXGI_Format(RTVDesc.Format, BIND_RENDER_TARGET); - - D3D11_RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D; - D3D11_RTVDesc.Texture3D.FirstWSlice = RTVDesc.FirstDepthSlice; - D3D11_RTVDesc.Texture3D.WSize = RTVDesc.NumDepthSlices; - D3D11_RTVDesc.Texture3D.MipSlice = RTVDesc.MostDetailedMip; + TextureViewDesc_to_D3D11_RTV_DESC(RTVDesc, D3D11_RTVDesc, m_Desc.SampleCount); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateRenderTargetView( m_pd3d11Texture, &D3D11_RTVDesc, ppD3D11RTV ), @@ -124,8 +117,8 @@ void Texture3D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess VERIFY( ppD3D11UAV && *ppD3D11UAV == nullptr, "UAV pointer address is null or contains non-null pointer to an existing object" ); VERIFY( UAVDesc.ViewType == TEXTURE_VIEW_UNORDERED_ACCESS, "Incorrect view type: unordered access is expected" ); - if( UAVDesc.TextureType != TEXTURE_TYPE_3D ) - LOG_ERROR_AND_THROW("Unsupported texture view type. Only TEXTURE_TYPE_3D is allowed"); + if( UAVDesc.TextureDim != RESOURCE_DIM_TEX_3D ) + LOG_ERROR_AND_THROW("Unsupported texture view type. Only RESOURCE_DIM_TEX_3D is allowed"); if( UAVDesc.Format == TEX_FORMAT_UNKNOWN ) { @@ -133,13 +126,7 @@ void Texture3D_D3D11::CreateUAV( TextureViewDesc &UAVDesc, ID3D11UnorderedAccess } D3D11_UNORDERED_ACCESS_VIEW_DESC D3D11_UAVDesc; - memset(&D3D11_UAVDesc, 0, sizeof(D3D11_UAVDesc)); - D3D11_UAVDesc.Format = TexFormatToDXGI_Format(UAVDesc.Format, BIND_UNORDERED_ACCESS); - - D3D11_UAVDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D; - D3D11_UAVDesc.Texture3D.FirstWSlice = UAVDesc.FirstDepthSlice; - D3D11_UAVDesc.Texture3D.WSize = UAVDesc.NumDepthSlices; - D3D11_UAVDesc.Texture3D.MipSlice = UAVDesc.MostDetailedMip; + TextureViewDesc_to_D3D11_UAV_DESC(UAVDesc, D3D11_UAVDesc); auto *pDeviceD3D11 = static_cast(GetDevice())->GetD3D11Device(); CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateUnorderedAccessView( m_pd3d11Texture, &D3D11_UAVDesc, ppD3D11UAV ), diff --git a/Graphics/GraphicsEngineD3D11/src/TextureBaseD3D11.cpp b/Graphics/GraphicsEngineD3D11/src/TextureBaseD3D11.cpp index 2462bec7..7401a714 100644 --- a/Graphics/GraphicsEngineD3D11/src/TextureBaseD3D11.cpp +++ b/Graphics/GraphicsEngineD3D11/src/TextureBaseD3D11.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,14 +27,13 @@ #include "DeviceContextD3D11Impl.h" #include "D3D11TypeConversions.h" #include "TextureViewD3D11Impl.h" - -using namespace Diligent; +#include "EngineMemory.h" namespace Diligent { -TextureBaseD3D11 :: TextureBaseD3D11(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData /*= TextureData()*/) : - TTextureBase(pRenderDeviceD3D11, TexDesc) +TextureBaseD3D11 :: TextureBaseD3D11(FixedBlockMemoryAllocator &TexObjAllocator, FixedBlockMemoryAllocator &TexViewObjAllocator, RenderDeviceD3D11Impl *pRenderDeviceD3D11, const TextureDesc& TexDesc, const TextureData &InitData /*= TextureData()*/) : + TTextureBase(TexObjAllocator, TexViewObjAllocator, pRenderDeviceD3D11, TexDesc) { if( TexDesc.Usage == USAGE_STATIC && InitData.pSubResources == nullptr ) LOG_ERROR_AND_THROW("Static Texture must be initialized with data at creation time"); @@ -53,7 +52,6 @@ void TextureBaseD3D11::CreateViewInternal( const struct TextureViewDesc &ViewDes try { auto UpdatedViewDesc = ViewDesc; - CorrectTextureViewDesc( UpdatedViewDesc ); RefCntAutoPtr pD3D11View; @@ -98,7 +96,11 @@ void TextureBaseD3D11::CreateViewInternal( const struct TextureViewDesc &ViewDes default: UNEXPECTED( "Unknown view type" ); break; } - auto pViewD3D11 = new TextureViewD3D11Impl( GetDevice(), UpdatedViewDesc, this, pD3D11View, bIsDefaultView ); + auto *pDeviceD3D11Impl = ValidatedCast(GetDevice()); + auto &TexViewAllocator = pDeviceD3D11Impl->GetTexViewObjAllocator(); + VERIFY( &TexViewAllocator == &m_dbgTexViewObjAllocator, "Texture view allocator does not match allocator provided during texture initialization" ); + + auto pViewD3D11 = NEW(TexViewAllocator, "TextureViewD3D11Impl instance", TextureViewD3D11Impl, pDeviceD3D11Impl, UpdatedViewDesc, this, pD3D11View, bIsDefaultView ); VERIFY( pViewD3D11->GetDesc().ViewType == ViewDesc.ViewType, "Incorrect view type" ); if( bIsDefaultView ) @@ -113,7 +115,8 @@ void TextureBaseD3D11::CreateViewInternal( const struct TextureViewDesc &ViewDes } } -void TextureBaseD3D11 :: PrepareD3D11InitData(const TextureData &InitData, Uint32 NumSubresources, std::vector &D3D11InitData) +void TextureBaseD3D11 :: PrepareD3D11InitData(const TextureData &InitData, Uint32 NumSubresources, + std::vector > &D3D11InitData) { if( InitData.pSubResources ) { @@ -205,9 +208,9 @@ void TextureBaseD3D11 :: Map(IDeviceContext *pContext, MAP_TYPE MapType, Uint32 //VERIFY( pMappedData, "Map failed" ); } -void TextureBaseD3D11::Unmap( IDeviceContext *pContext ) +void TextureBaseD3D11::Unmap( IDeviceContext *pContext, MAP_TYPE MapType ) { - TTextureBase::Unmap( pContext ); + TTextureBase::Unmap( pContext, MapType ); //auto *pd3d11DeviceContext = static_cast( static_cast(m_pDevice) )->GetD3D11DeviceContext(); //pd3d11DeviceContext->Unmap(m_pd3d11Texture, 0); diff --git a/Graphics/GraphicsEngineD3D11/src/TextureViewD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/TextureViewD3D11Impl.cpp index 1cebd403..9cc8b41d 100644 --- a/Graphics/GraphicsEngineD3D11/src/TextureViewD3D11Impl.cpp +++ b/Graphics/GraphicsEngineD3D11/src/TextureViewD3D11Impl.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,21 +28,17 @@ namespace Diligent { -TextureViewD3D11Impl::TextureViewD3D11Impl( IRenderDevice *pDevice, - const TextureViewDesc& ViewDesc, - ITexture *pTexture, - ID3D11View* pD3D11View, - bool bIsDefaultView ) : - TTextureViewBase( pDevice, ViewDesc, pTexture, bIsDefaultView ), +TextureViewD3D11Impl::TextureViewD3D11Impl( FixedBlockMemoryAllocator &TexViewAllocator, + IRenderDevice *pDevice, + const TextureViewDesc& ViewDesc, + ITexture *pTexture, + ID3D11View* pD3D11View, + bool bIsDefaultView ) : + TTextureViewBase( TexViewAllocator, pDevice, ViewDesc, pTexture, bIsDefaultView ), m_pD3D11View( pD3D11View ) { } -ID3D11View* TextureViewD3D11Impl::GetD3D11View() -{ - return m_pD3D11View; -} - IMPLEMENT_QUERY_INTERFACE( TextureViewD3D11Impl, IID_TextureViewD3D11, TTextureViewBase ) void TextureViewD3D11Impl::GenerateMips( IDeviceContext *pContext ) diff --git a/Graphics/GraphicsEngineD3D11/src/VertexDescD3D11Impl.cpp b/Graphics/GraphicsEngineD3D11/src/VertexDescD3D11Impl.cpp deleted file mode 100644 index 46be4675..00000000 --- a/Graphics/GraphicsEngineD3D11/src/VertexDescD3D11Impl.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright 2015 Egor Yusov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. - * - * In no event and under no legal theory, whether in tort (including negligence), - * contract, or otherwise, unless required by applicable law (such as deliberate - * and grossly negligent acts) or agreed to in writing, shall any Contributor be - * liable for any damages, including any direct, indirect, special, incidental, - * or consequential damages of any character arising as a result of this License or - * out of the use or inability to use the software (including but not limited to damages - * for loss of goodwill, work stoppage, computer failure or malfunction, or any and - * all other commercial damages or losses), even if such Contributor has been advised - * of the possibility of such damages. - */ - -#include "pch.h" -#include "VertexDescD3D11Impl.h" -#include "RenderDeviceD3D11Impl.h" -#include "ShaderD3D11Impl.h" -#include "D3D11TypeConversions.h" - -namespace Diligent -{ - -VertexDescD3D11Impl::VertexDescD3D11Impl(RenderDeviceD3D11Impl *pRenderDeviceD3D11, const LayoutDesc &LayoutDesc, IShader *pVertexShader) : - TVertexDescriptionBase( pRenderDeviceD3D11, LayoutDesc ) -{ - // Use m_LayoutDesc as original LayoutDescription might have been corrected - auto *pLayoutElements = m_LayoutElements.data(); - auto NumElements = m_LayoutElements.size(); - - if( pVertexShader->GetDesc().ShaderType != SHADER_TYPE_VERTEX ) - LOG_ERROR_AND_THROW( "Invalid shader type provided for the input layout creation" ); - std::vector InputElements; - ID3DBlob *pVSByteCode = static_cast(pVertexShader)->m_pShaderByteCode; - if( !pVSByteCode ) - LOG_ERROR_AND_THROW( "Vertex Shader byte code does not exist" ); - - InputElements.resize(NumElements); - for(Uint32 iElem=0; iElem < NumElements; ++iElem) - { - const auto &CurrElem = pLayoutElements[iElem]; - auto &D3D11Elem = InputElements[iElem]; - D3D11Elem.SemanticName = "ATTRIB"; - D3D11Elem.SemanticIndex = CurrElem.InputIndex; - D3D11Elem.AlignedByteOffset = CurrElem.RelativeOffset; - D3D11Elem.InputSlot = CurrElem.BufferSlot; - D3D11Elem.Format = TypeToDXGI_Format(CurrElem.ValueType, CurrElem.NumComponents, CurrElem.IsNormalized); - D3D11Elem.InputSlotClass = (CurrElem.Frequency == LayoutElement::FREQUENCY_PER_VERTEX) ? D3D11_INPUT_PER_VERTEX_DATA : D3D11_INPUT_PER_INSTANCE_DATA; - D3D11Elem.InstanceDataStepRate = (CurrElem.Frequency == LayoutElement::FREQUENCY_PER_VERTEX) ? 0 : CurrElem.InstanceDataStepRate; - } - - auto *pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device(); - CHECK_D3D_RESULT_THROW( pDeviceD3D11->CreateInputLayout(InputElements.data(), static_cast(InputElements.size()), pVSByteCode->GetBufferPointer(), pVSByteCode->GetBufferSize(), &m_pd3d11InputLayout), - "Failed to create the Direct3D11 input layout"); -} - -VertexDescD3D11Impl::~VertexDescD3D11Impl() -{ -} - -IMPLEMENT_QUERY_INTERFACE( VertexDescD3D11Impl, IID_VertexDescriptionD3D11, TVertexDescriptionBase ) - -} diff --git a/Graphics/GraphicsEngineD3D11/src/pch.cpp b/Graphics/GraphicsEngineD3D11/src/pch.cpp index c7d1ec78..860c4217 100644 --- a/Graphics/GraphicsEngineD3D11/src/pch.cpp +++ b/Graphics/GraphicsEngineD3D11/src/pch.cpp @@ -1,4 +1,4 @@ -/* Copyright 2015 Egor Yusov +/* Copyright 2015-2016 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. -- cgit v1.2.3