Diligent Engine
 
Loading...
Searching...
No Matches
Overview

Diligent Core is a modern, cross-platform low-level graphics API that forms the foundation of Diligent Engine. It provides implementations for Direct3D11, Direct3D12, OpenGL, OpenGLES, Vulkan, and WebGPU rendering backends. A Metal backend is also available for commercial clients. In addition, the module includes essential platform-specific utilities. Diligent Core is fully self-contained and can be built independently of the rest of the engine. For details on supported platforms, features, and build instructions, please refer to the main repository.

Platform Build Status
Win32 Build Status
Universal Windows Build Status
Linux Build Status
Android Build Status
MacOS Build Status
iOS Build Status
tvOS Build Status
Web Build Status

Documentation License Chat on Discord Lines of code Appveyor Build Status CodeQL Scanning MSVC Analysis

Table of Contents

Cloning the Repository

To get the repository and all submodules, use the following command:

git clone --recursive https://github.com/DiligentGraphics/DiligentCore.git

To build the module, see build instructions in the master repository.

API Basics

Initializing the Engine

Before you can use any functionality provided by the engine, you need to create a render device, an immediate context and a swap chain.

Win32

On Win32 platform, you can create OpenGL, Direct3D11, Direct3D12 or Vulkan device as shown below:

void InitializeDiligentEngine(HWND NativeWindowHandle)
{
SwapChainDesc SCDesc;
// RefCntAutoPtr<IRenderDevice> m_pDevice;
// RefCntAutoPtr<IDeviceContext> m_pImmediateContext;
// RefCntAutoPtr<ISwapChain> m_pSwapChain;
switch (m_DeviceType)
{
case RENDER_DEVICE_TYPE_D3D11:
{
EngineD3D11CreateInfo EngineCI;
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D11() function
auto* GetEngineFactoryD3D11 = LoadGraphicsEngineD3D11();
# endif
auto* pFactoryD3D11 = GetEngineFactoryD3D11();
pFactoryD3D11->CreateDeviceAndContextsD3D11(EngineCI, &m_pDevice, &m_pImmediateContext);
Win32NativeWindow Window{hWnd};
pFactoryD3D11->CreateSwapChainD3D11(m_pDevice, m_pImmediateContext, SCDesc,
FullScreenModeDesc{}, Window, &m_pSwapChain);
}
break;
case RENDER_DEVICE_TYPE_D3D12:
{
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D12() function
auto GetEngineFactoryD3D12 = LoadGraphicsEngineD3D12();
# endif
EngineD3D12CreateInfo EngineCI;
auto* pFactoryD3D12 = GetEngineFactoryD3D12();
pFactoryD3D12->CreateDeviceAndContextsD3D12(EngineCI, &m_pDevice, &m_pImmediateContext);
Win32NativeWindow Window{hWnd};
pFactoryD3D12->CreateSwapChainD3D12(m_pDevice, m_pImmediateContext, SCDesc,
FullScreenModeDesc{}, Window, &m_pSwapChain);
}
break;
{
# if EXPLICITLY_LOAD_ENGINE_GL_DLL
// Load the dll and import GetEngineFactoryOpenGL() function
auto GetEngineFactoryOpenGL = LoadGraphicsEngineOpenGL();
# endif
auto* pFactoryOpenGL = GetEngineFactoryOpenGL();
EngineGLCreateInfo EngineCI;
EngineCI.Window.hWnd = hWnd;
pFactoryOpenGL->CreateDeviceAndSwapChainGL(EngineCI, &m_pDevice, &m_pImmediateContext,
SCDesc, &m_pSwapChain);
}
break;
{
# if EXPLICITLY_LOAD_ENGINE_VK_DLL
// Load the dll and import GetEngineFactoryVk() function
auto GetEngineFactoryVk = LoadGraphicsEngineVk();
# endif
EngineVkCreateInfo EngineCI;
auto* pFactoryVk = GetEngineFactoryVk();
pFactoryVk->CreateDeviceAndContextsVk(EngineCI, &m_pDevice, &m_pImmediateContext);
Win32NativeWindow Window{hWnd};
pFactoryVk->CreateSwapChainVk(m_pDevice, m_pImmediateContext, SCDesc, Window, &m_pSwapChain);
}
break;
default:
std::cerr << "Unknown device type";
}
}
@ RENDER_DEVICE_TYPE_GL
OpenGL device.
Definition GraphicsTypes.h:1612
@ RENDER_DEVICE_TYPE_VULKAN
Vulkan device.
Definition GraphicsTypes.h:1614
NativeWindow Window
Native window wrapper.
Definition GraphicsTypes.h:3632

On Windows, the engine can be statically linked to the application or built as a separate DLL. In the first case, factory functions GetEngineFactoryOpenGL(), GetEngineFactoryD3D11(), GetEngineFactoryD3D12(), and GetEngineFactoryVk() can be called directly. In the second case, you need to load the DLL into the process's address space using LoadGraphicsEngineOpenGL(), LoadGraphicsEngineD3D11(), LoadGraphicsEngineD3D12(), or LoadGraphicsEngineVk() function. Each function loads appropriate dynamic library and imports the functions required to initialize the engine. You need to include the following headers:

You also need to add the following directories to the include search paths:

  • DiligentCore/Graphics/GraphicsEngineD3D11/interface
  • DiligentCore/Graphics/GraphicsEngineD3D12/interface
  • DiligentCore/Graphics/GraphicsEngineOpenGL/interface
  • DiligentCore/Graphics/GraphicsEngineVulkan/interface

As an alternative, you may only add the path to the root folder and then use include paths relative to it.

Enable Diligent namespace:

using namespace Diligent;
Graphics engine namespace.
Definition AdvancedMath.hpp:43

IEngineFactoryD3D11::CreateDeviceAndContextsD3D11(), IEngineFactoryD3D12::CreateDeviceAndContextsD3D12(), and IEngineFactoryVk::CreateDeviceAndContextsVk() functions can also create a specified number of immediate and deferred contexts, which can be used for asynchronous rendering and multi-threaded command recording. The contexts may only be created during the initialization of the engine. The function populates an array of pointers to the contexts, where the immediates contexts go first, followed by all deferred contexts.

For more details, take a look at Tutorial00_HelloWin32.cpp file.

Universal Windows Platform

On Universal Windows Platform, you can create Direct3D11 or Direct3D12 device. Initialization is performed the same way as on Win32 Platform. The difference is that you first create the render device and device contexts by calling IEngineFactoryD3D11::CreateDeviceAndContextsD3D11() or IEngineFactoryD3D12::CreateDeviceAndContextsD3D12(). The swap chain is created later by a call to IEngineFactoryD3D11::CreateSwapChainD3D11() or IEngineFactoryD3D12::CreateSwapChainD3D12(). Please look at SampleAppUWP.cpp file for more details.

Linux

On Linux platform, the engine supports OpenGL and Vulkan backends. Initialization of GL context on Linux is tightly coupled with window creation. As a result, Diligent Engine does not initialize the context, but attaches to the one initialized by the app. An example of the engine initialization on Linux can be found in Tutorial00_HelloLinux.cpp.

MacOS

On MacOS, Diligent Engine supports OpenGL, Vulkan and Metal backends. Initialization of GL context on MacOS is performed by the application, and the engine attaches to the context created by the app; see GLView.mm for details. Vulkan backend is initialized similar to other platforms. See MetalView.mm.

Android

On Android, you can create OpenGLES or Vulkan device. The following code snippet shows an example:

auto* pFactoryOpenGL = GetEngineFactoryOpenGL();
EngineCI.Window.pAWindow = NativeWindowHandle;
pFactoryOpenGL->CreateDeviceAndSwapChainGL(
EngineCI, &m_pDevice, &m_pContext, SCDesc, &m_pSwapChain);
Attributes of the OpenGL-based engine implementation.
Definition GraphicsTypes.h:3629

If the engine is built as dynamic library, the library needs to be loaded by the native activity. The following code shows one possible way:

static
{
try{
System.loadLibrary("GraphicsEngineOpenGL");
} catch (UnsatisfiedLinkError e) {
Log.e("native-activity", "Failed to load GraphicsEngineOpenGL library.\n" + e);
}
}
Definition Matrix3x4.cs:29

iOS

iOS implementation supports OpenGLES, Vulkan and Metal backend. Initialization of GL context on iOS is performed by the application, and the engine attaches to the context initialized by the app; see EAGLView.mm for details.

Web

On the Web, you can create OpenGLES or WebGPU device. The following code snippet shows an example:

//You need to pass the id of the canvas to NativeWindow
auto* pFactoryOpenGL = GetEngineFactoryOpenGL();
EngineGLCreateInfo EngineCI = {};
EngineCI.Window = NativeWindow{"#canvas"};
pFactoryOpenGL->CreateDeviceAndSwapChainGL(EngineCI, &m_pDevice, &m_pContext, SCDesc, &m_pSwapChain);

If you are using SDL or GLFW with existing context, you can provide null as the native window handle: EngineCI.Window = NativeWindow{nullptr}

Destroying the Engine

The engine performs automatic reference counting and shuts down when the last reference to an engine object is released.

Creating Resources

Device resources are created by the render device. The two main resource types are buffers, which represent linear memory, and textures, which use memory layouts optimized for fast filtering. To create a buffer, you need to populate BufferDesc structure and call IRenderDevice::CreateBuffer(). The following code creates a uniform (constant) buffer:

BufferDesc BuffDesc;
BuffDesc.Name = "Uniform buffer";
BuffDesc.Usage = USAGE_DYNAMIC;
BuffDesc.uiSizeInBytes = sizeof(ShaderConstants);
m_pDevice->CreateBuffer(BuffDesc, nullptr, &m_pConstantBuffer);
@ CPU_ACCESS_WRITE
A resource can be mapped for writing.
Definition GraphicsTypes.h:238
@ USAGE_DYNAMIC
Definition GraphicsTypes.h:201
@ BIND_UNIFORM_BUFFER
Definition GraphicsTypes.h:142
Buffer description.
Definition Buffer.h:86
USAGE Usage
Buffer usage, see Diligent::USAGE for details.
Definition Buffer.h:101
CPU_ACCESS_FLAGS CPUAccessFlags
CPU access flags or 0 if no CPU access is allowed, see Diligent::CPU_ACCESS_FLAGS for details.
Definition Buffer.h:104
BIND_FLAGS BindFlags
Buffer bind flags, see Diligent::BIND_FLAGS for details.
Definition Buffer.h:98
const Char * Name
Object name.
Definition GraphicsTypes.h:1319

Similar, to create a texture, populate TextureDesc structure and call IRenderDevice::CreateTexture() as in the following example:

TextureDesc TexDesc;
TexDesc.Name = "My texture 2D";
TexDesc.Type = TEXTURE_TYPE_2D;
TexDesc.Width = 1024;
TexDesc.Height = 1024;
TexDesc.Usage = USAGE_DEFAULT;
TexDesc.Name = "Sample 2D Texture";
m_pRenderDevice->CreateTexture(TexDesc, nullptr, &m_pTestTex);
@ USAGE_DEFAULT
Definition GraphicsTypes.h:196
@ BIND_RENDER_TARGET
A texture can be bound as a render target.
Definition GraphicsTypes.h:151
@ BIND_SHADER_RESOURCE
A buffer or a texture can be bound as a shader resource.
Definition GraphicsTypes.h:145
@ BIND_UNORDERED_ACCESS
A buffer or a texture can be bound as an unordered access view.
Definition GraphicsTypes.h:157
@ TEX_FORMAT_RGBA8_UNORM
Definition GraphicsTypes.h:508
Texture description.
Definition Texture.h:81
USAGE Usage
Texture usage. See Diligent::USAGE for details.
Definition Texture.h:125
TEXTURE_FORMAT Format
Texture format, see Diligent::TEXTURE_FORMAT.
Definition Texture.h:107
Uint32 Height
Texture height, in pixels.
Definition Texture.h:90
Uint32 Width
Texture width, in pixels.
Definition Texture.h:87
BIND_FLAGS BindFlags
Bind flags, see Diligent::BIND_FLAGS for details.
Definition Texture.h:122
RESOURCE_DIMENSION Type
Texture type. See Diligent::RESOURCE_DIMENSION for details.
Definition Texture.h:84

There is only one function CreateTexture() that is capable of creating all types of textures. Type, format, array size and all other parameters are specified by the members of the TextureDesc structure.

For every bind flag specified during the texture creation time, the texture object creates a default view. Default shader resource view addresses the entire texture, default render target and depth stencil views reference all array slices in the most detailed mip level, and unordered access view references the entire texture. To get a default view from the texture, use ITexture::GetDefaultView() function. Note that this function does not increment the reference counter of the returned interface. You can create additional texture views using ITexture::CreateView(). Use IBuffer::CreateView() to create additional views of a buffer.

Creating Shaders

To create a shader, populate ShaderCreateInfo structure:

Shader creation attributes.
Definition Shader.h:420

There are three ways to create a shader. The first way is to provide a pointer to the shader source code through ShaderCreateInfo::Source member. The second way is to provide a file name. The third way is to provide a pointer to the compiled byte code through ShaderCreateInfo::ByteCode member. Graphics Engine is entirely decoupled from the platform. Since the host file system is platform-dependent, the structure exposes ShaderCreateInfo::pShaderSourceStreamFactory member that is intended to give the engine access to the file system. If you provided the source file name, you must also provide a non-null pointer to the shader source stream factory. If the shader source contains any #include directives, the source stream factory will also be used to load these files. The engine provides default implementation for every supported platform that should be sufficient in most cases. You can however define your own implementation.

An important member is ShaderCreateInfo::SourceLanguage. The following are valid values for this member:

  • SHADER_SOURCE_LANGUAGE_DEFAULT - The shader source format matches the underlying graphics API: HLSL for D3D11 or D3D12 mode, and GLSL for OpenGL, OpenGLES, and Vulkan modes.
  • SHADER_SOURCE_LANGUAGE_HLSL - The shader source is in HLSL. For OpenGL and OpenGLES modes, the source code will be converted to GLSL. In Vulkan back-end, the code will be compiled to SPIRV directly.
  • SHADER_SOURCE_LANGUAGE_GLSL - The shader source is in GLSL.
  • SHADER_SOURCE_LANGUAGE_GLSL_VERBATIM - The shader source language is GLSL and should be compiled verbatim.
  • SHADER_SOURCE_LANGUAGE_MSL - The source language is Metal Shading Language.

Other members of the ShaderCreateInfo structure define the shader include search directories, shader macro definitions, shader entry point and other parameters.

ShaderMacroHelper Macros;
Macros.AddShaderMacro("USE_SHADOWS", 1);
Macros.AddShaderMacro("NUM_SHADOW_SAMPLES", 4);
Macros.Finalize();
ShaderCI.Macros = Macros;
ShaderMacroArray Macros
Shader macros (see Diligent::ShaderMacroArray)
Definition Shader.h:480

When everything is ready, call IRenderDevice::CreateShader() to create the shader object:

ShaderCI.Desc.Name = "MyPixelShader";
ShaderCI.FilePath = "MyShaderFile.fx";
ShaderCI.EntryPoint = "MyPixelShader";
const auto* SearchDirectories = "shaders;shaders\\inc;";
m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(SearchDirectories, &pShaderSourceFactory);
ShaderCI.pShaderSourceStreamFactory = pShaderSourceFactory;
m_pDevice->CreateShader(ShaderCI, &pShader);
Template class that implements reference counting.
Definition RefCntAutoPtr.hpp:77
@ SHADER_SOURCE_LANGUAGE_HLSL
The source language is HLSL.
Definition Shader.h:54
@ SHADER_TYPE_PIXEL
Pixel (fragment) shader.
Definition GraphicsTypes.h:74
SHADER_SOURCE_LANGUAGE SourceLanguage
Shader source language. See Diligent::SHADER_SOURCE_LANGUAGE.
Definition Shader.h:486
const Char * FilePath
Source file path.
Definition Shader.h:424
const Char * EntryPoint
Shader entry point.
Definition Shader.h:477
ShaderDesc Desc
Shader description. See Diligent::ShaderDesc.
Definition Shader.h:483
IShaderSourceInputStreamFactory * pShaderSourceStreamFactory
Pointer to the shader source input stream factory.
Definition Shader.h:430
SHADER_TYPE ShaderType
Shader type. See Diligent::SHADER_TYPE.
Definition Shader.h:133

Initializing Pipeline State

Diligent Engine follows Direct3D12/Vulkan style to configure the graphics/compute pipeline. One monolithic Pipelines State Object (PSO) encompasses all required states (all shader stages, input layout description, depth stencil, rasterizer and blend state descriptions etc.). To create a graphics pipeline state object, define an instance of GraphicsPipelineStateCreateInfo structure:

PipelineStateDesc& PSODesc = PSOCreateInfo.PSODesc;
PSODesc.Name = "My pipeline state";
Graphics pipeline state initialization information.
Definition PipelineState.h:783
PipelineStateDesc PSODesc
Pipeline state description.
Definition PipelineState.h:702
Pipeline state description.
Definition PipelineState.h:590

Describe the pipeline specifics such as the number and format of render targets as well as depth-stencil format:

// This is a graphics pipeline
@ PIPELINE_TYPE_GRAPHICS
Definition PipelineState.h:564
@ TEX_FORMAT_RGBA8_UNORM_SRGB
Definition GraphicsTypes.h:512
@ TEX_FORMAT_D32_FLOAT
Definition GraphicsTypes.h:560
TEXTURE_FORMAT RTVFormats[DILIGENT_MAX_RENDER_TARGETS]
Render target formats.
Definition PipelineState.h:331
Uint8 NumRenderTargets
The number of render targets in the RTVFormats array.
Definition PipelineState.h:318
TEXTURE_FORMAT DSVFormat
Depth-stencil format.
Definition PipelineState.h:336
GraphicsPipelineDesc GraphicsPipeline
Graphics pipeline state description.
Definition PipelineState.h:786
PIPELINE_TYPE PipelineType
Pipeline type.
Definition PipelineState.h:593

Initialize depth-stencil state description DepthStencilStateDesc. Note that the constructor initializes the members with default values and you may only set the ones that are different from default.

// Init depth-stencil state
DepthStencilStateDesc& DepthStencilDesc = PSOCreateInfo.GraphicsPipeline.DepthStencilDesc;
DepthStencilDesc.DepthEnable = true;
DepthStencilDesc.DepthWriteEnable = true;
Depth stencil state description.
Definition DepthStencilState.h:161
Bool DepthWriteEnable
Enable or disable writes to a depth buffer. Default value: True.
Definition DepthStencilState.h:168
Bool DepthEnable
Definition DepthStencilState.h:165
DepthStencilStateDesc DepthStencilDesc
Depth-stencil state description.
Definition PipelineState.h:304

Initialize blend state description BlendStateDesc:

// Init blend state
BlendStateDesc& BSDesc = PSOCreateInfo.GraphicsPipeline.BlendDesc;
BSDesc.IndependentBlendEnable = False;
auto &RT0 = BSDesc.RenderTargets[0];
RT0.BlendEnable = True;
RT0.RenderTargetWriteMask = COLOR_MASK_ALL;
RT0.SrcBlend = BLEND_FACTOR_SRC_ALPHA;
RT0.BlendOp = BLEND_OPERATION_ADD;
RT0.SrcBlendAlpha = BLEND_FACTOR_SRC_ALPHA;
RT0.DestBlendAlpha = BLEND_FACTOR_INV_SRC_ALPHA;
RT0.BlendOpAlpha = BLEND_OPERATION_ADD;
@ BLEND_OPERATION_ADD
Definition BlendState.h:146
@ BLEND_FACTOR_INV_SRC_ALPHA
Definition BlendState.h:78
@ BLEND_FACTOR_SRC_ALPHA
Definition BlendState.h:74
@ COLOR_MASK_ALL
Allow data to be stored in all components.
Definition BlendState.h:194
Blend state description.
Definition BlendState.h:380
RenderTargetBlendDesc RenderTargets[DILIGENT_MAX_RENDER_TARGETS]
Definition BlendState.h:391
Bool IndependentBlendEnable
Definition BlendState.h:387
BlendStateDesc BlendDesc
Blend state description.
Definition PipelineState.h:290
Bool BlendEnable
Enable or disable blending for this render target. Default value: False.
Definition BlendState.h:284

Initialize rasterizer state description RasterizerStateDesc:

// Init rasterizer state
RasterizerStateDesc& RasterizerDesc = PSOCreateInfo.GraphicsPipeline.RasterizerDesc;
RasterizerDesc.FillMode = FILL_MODE_SOLID;
RasterizerDesc.CullMode = CULL_MODE_NONE;
RasterizerDesc.FrontCounterClockwise = True;
RasterizerDesc.ScissorEnable = True;
RasterizerDesc.AntialiasedLineEnable = False;
@ FILL_MODE_SOLID
Definition RasterizerState.h:57
@ CULL_MODE_NONE
Definition RasterizerState.h:76
RasterizerStateDesc RasterizerDesc
Rasterizer state description.
Definition PipelineState.h:301
Rasterizer state description.
Definition RasterizerState.h:97
FILL_MODE FillMode
Determines triangle fill mode, see Diligent::FILL_MODE for details.
Definition RasterizerState.h:101
CULL_MODE CullMode
Determines triangle cull mode, see Diligent::CULL_MODE for details.
Definition RasterizerState.h:106
Bool FrontCounterClockwise
Determines if a triangle is front- or back-facing.
Definition RasterizerState.h:115
Bool ScissorEnable
Enable scissor-rectangle culling. All pixels outside an active scissor rectangle are culled.
Definition RasterizerState.h:132
Bool AntialiasedLineEnable
Specifies whether to enable line antialiasing.
Definition RasterizerState.h:137

Initialize input layout description InputLayoutDesc:

// Define input layout
LayoutElement LayoutElems[] =
{
LayoutElement( 0, 0, 3, VT_FLOAT32, False ),
LayoutElement( 1, 0, 4, VT_UINT8, True ),
LayoutElement( 2, 0, 2, VT_FLOAT32, False ),
};
Layout.LayoutElements = LayoutElems;
Layout.NumElements = _countof(LayoutElems);
@ VT_UINT8
Unsigned 8-bit integer.
Definition GraphicsTypes.h:59
@ VT_FLOAT32
Full-precision 32-bit floating point.
Definition GraphicsTypes.h:63
InputLayoutDesc InputLayout
Input layout, ignored in a mesh pipeline.
Definition PipelineState.h:307
Layout description.
Definition InputLayout.h:219
Uint32 NumElements
The number of layout elements in LayoutElements array.
Definition InputLayout.h:224
const LayoutElement * LayoutElements
Array of layout elements.
Definition InputLayout.h:221
Description of a single element of the input layout.
Definition InputLayout.h:70

Define primitive topology and set shader pointers:

// Define shader and primitive topology
PSOCreateInfo.pVS = m_pVS;
PSOCreateInfo.pPS = m_pPS;
@ PRIMITIVE_TOPOLOGY_TRIANGLE_LIST
Definition GraphicsTypes.h:1061
PRIMITIVE_TOPOLOGY PrimitiveTopology
Primitive topology type, ignored in a mesh pipeline.
Definition PipelineState.h:310
IShader * pPS
Pixel shader to be used with the pipeline.
Definition PipelineState.h:792
IShader * pVS
Vertex shader to be used with the pipeline.
Definition PipelineState.h:789

Pipeline Resource Layout

Pipeline resource layout informs the engine how the application is going to use different shader resource variables. To allow grouping of resources based on the expected frequency of resource bindings changes, Diligent Engine introduces classification of shader variables:

  • Static variables (SHADER_RESOURCE_VARIABLE_TYPE_STATIC) are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. Note that it is the resource binding that may not change, while the contents of the resource is allowed to change according to its usage.
  • Mutable variables (SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE) define resources that are expected to change on a per-material frequency. Examples may include diffuse textures, normal maps etc. Again updates to the contents of the resource are orthogobal to the binding changes.
  • Dynamic variables (SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC) are expected to change frequently and randomly.

To define variable types, prepare an array of ShaderResourceVariableDesc structures and initialize PSODesc.ResourceLayout.Variables and PSODesc.ResourceLayout.NumVariables members. Also PSODesc.ResourceLayout.DefaultVariableType can be used to set the type that will be used if a variable name is not provided.

{
};
PSODesc.ResourceLayout.Variables = ShaderVars;
PSODesc.ResourceLayout.NumVariables = _countof(ShaderVars);
@ SHADER_RESOURCE_VARIABLE_TYPE_STATIC
Definition ShaderResourceVariable.h:53
@ SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE
Definition ShaderResourceVariable.h:59
@ SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC
Definition ShaderResourceVariable.h:63
const ShaderResourceVariableDesc * Variables
Array of shader resource variable descriptions.
Definition PipelineState.h:230
SHADER_RESOURCE_VARIABLE_TYPE DefaultVariableType
Default shader resource variable type.
Definition PipelineState.h:208
Uint32 NumVariables
Number of elements in Variables array.
Definition PipelineState.h:224
PipelineResourceLayoutDesc ResourceLayout
Pipeline layout description.
Definition PipelineState.h:614
Describes shader variable.
Definition PipelineState.h:131

When creating a pipeline state, textures can be permanently assigned immutable samplers. If an immutable sampler is assigned to a texture, it will always be used instead of the one initialized in the texture shader resource view. To define immutable samplers, prepare an array of ImmutableSamplerDesc structures and initialize PSODesc.ResourceLayout.ImmutableSamplers and PSODesc.ResourceLayout.NumImmutableSamplers members. Notice that immutable samplers can be assigned to a texture variable of any type, not necessarily static, so that the texture binding can be changed at run-time, while the sampler will stay immutable. It is highly recommended to use immutable samplers whenever possible.

ImmutableSamplerDesc ImtblSampler;
ImtblSampler.TextureName = "g_MutableTexture";
PSODesc.ResourceLayout.ImmutableSamplers = &ImtblSampler;
@ FILTER_TYPE_LINEAR
Linear filtering.
Definition GraphicsTypes.h:947
Immutable sampler description.
Definition PipelineResourceSignature.h:52
SHADER_TYPE ShaderStages
Shader stages that this immutable sampler applies to. More than one shader stage can be specified.
Definition PipelineResourceSignature.h:54
struct SamplerDesc Desc
Sampler description.
Definition PipelineResourceSignature.h:61
const ImmutableSamplerDesc * ImmutableSamplers
Array of immutable sampler descriptions.
Definition PipelineState.h:236
Uint32 NumImmutableSamplers
Number of immutable samplers in ImmutableSamplers array.
Definition PipelineState.h:233
FILTER_TYPE MinFilter
Texture minification filter, see Diligent::FILTER_TYPE for details.
Definition Sampler.h:83
FILTER_TYPE MipFilter
Mip filter, see Diligent::FILTER_TYPE for details.
Definition Sampler.h:95
FILTER_TYPE MagFilter
Texture magnification filter, see Diligent::FILTER_TYPE for details.
Definition Sampler.h:88

This document provides a detailed information about working with texture samplers.

When all required fields of PSO description structure are set, call IRenderDevice::CreateGraphicsPipelineState() to create the PSO object:

m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO);

Binding Shader Resources

As mentioned above, shader resource binding in Diligent Engine is based on grouping variables in 3 different groups (static, mutable and dynamic). Static variables are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. They are bound directly to the Pipeline State Object:

m_pPSO->GetStaticShaderVariable(SHADER_TYPE_PIXEL, "g_tex2DShadowMap")->Set(pShadowMapSRV);

Mutable and dynamic variables are bound via a new object called Shader Resource Binding (SRB), which is created by the pipeline state (IPipelineState::CreateShaderResourceBinding()), or pipeline resource signature in advanced use cases:

m_pPSO->CreateShaderResourceBinding(&m_pSRB, true);

The second parameter tells the system to initialize internal structures in the SRB object that reference static variables in the PSO.

Dynamic and mutable resources are then bound through the SRB object:

m_pSRB->GetVariable(SHADER_TYPE_PIXEL, "tex2DDiffuse")->Set(pDiffuseTexSRV);
m_pSRB->GetVariable(SHADER_TYPE_VERTEX, "cbRandomAttribs")->Set(pRandomAttrsCB);
@ SHADER_TYPE_VERTEX
Vertex shader.
Definition GraphicsTypes.h:73

The difference between mutable and dynamic resources is that mutable resources can only be set once per instance of a shader resource binding. Dynamic resources can be set multiple times. It is important to properly set the variable type as this affects performance. Static and mutable variables are more efficient. Dynamic variables are more expensive and introduce some run-time overhead.

An alternative way to bind shader resources is to create an IResourceMapping interface that maps resource literal names to the actual resources:

{
{"g_Texture", pTexture->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE)}
};
ResMappingCI.pEntries = Entries;
ResMappingCI.NumEntries = _countof(Entries);
pRenderDevice->CreateResourceMapping(ResMappingCI, &pResMapping);
@ TEXTURE_VIEW_SHADER_RESOURCE
Definition GraphicsTypes.h:327
Resource mapping create information.
Definition ResourceMapping.h:75
Uint32 NumEntries
The number of entries in pEntries array.
Definition ResourceMapping.h:80
const ResourceMappingEntry * pEntries
A pointer to the array of resource mapping entries.
Definition ResourceMapping.h:77
Describes the resource mapping object entry.
Definition ResourceMapping.h:43

The resource mapping can then be used to bind all static resources in a pipeline state (IPipelineState::BindStaticResources()):

m_pPSO->BindStaticResources(SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, pResMapping,
@ BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED
Definition ShaderResourceVariable.h:129

or all mutable and dynamic resources in a shader resource binding (IShaderResourceBinding::BindResources()):

The last parameter to all BindResources() functions defines how resources should be resolved:

  • BIND_SHADER_RESOURCES_UPDATE_STATIC - Indicates that static variable bindings are to be updated.
  • BIND_SHADER_RESOURCES_UPDATE_MUTABLE - Indicates that mutable variable bindings are to be updated.
  • BIND_SHADER_RESOURCES_UPDATE_DYNAMIC -Indicates that dynamic variable bindings are to be updated.
  • BIND_SHADER_RESOURCES_UPDATE_ALL - Indicates that all variable types (static, mutable and dynamic) are to be updated. Note that if none of BIND_SHADER_RESOURCES_UPDATE_STATIC, BIND_SHADER_RESOURCES_UPDATE_MUTABLE, and BIND_SHADER_RESOURCES_UPDATE_DYNAMIC flags are set, all variable types are updated as if BIND_SHADER_RESOURCES_UPDATE_ALL was specified.
  • BIND_SHADER_RESOURCES_KEEP_EXISTING - If this flag is specified, only unresolved bindings will be updated. All existing bindings will keep their original values. If this flag is not specified, every shader variable will be updated if the mapping contains corresponding resource.
  • BIND_SHADER_RESOURCES_VERIFY_ALL_RESOLVED - If this flag is specified, all shader bindings are expected be resolved after the call. If this is not the case, an error will be reported.

BindResources() may be called several times with different resource mappings to bind resources. However, it is recommended to use one large resource mapping as the size of the mapping does not affect element search time.

The engine performs run-time checks to verify that correct resources are being bound. For example, if you try to bind a constant buffer to a shader resource view variable, an error will be output to the debug console.

Setting the Pipeline State and Invoking Draw Command

Before any draw command can be invoked, all required vertex and index buffers as well as the pipeline state should be bound to the device context:

// Set render targets before issuing any draw command.
auto* pRTV = m_pSwapChain->GetCurrentBackBufferRTV();
auto* pDSV = m_pSwapChain->GetDepthBufferDSV();
m_pContext->SetRenderTargets(1, &pRTV, pDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
// Clear render target and depth-stencil
const float zero[4] = {0, 0, 0, 0};
m_pContext->ClearRenderTarget(pRTV, ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
m_pContext->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
// Set vertex and index buffers
IBuffer* buffer[] = {m_pVertexBuffer};
Uint32 offsets[] = {0};
m_pContext->SetVertexBuffers(0, 1, buffer, offsets, SET_VERTEX_BUFFERS_FLAG_RESET,
m_pContext->SetIndexBuffer(m_pIndexBuffer, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
m_pContext->SetPipelineState(m_pPSO);
@ RESOURCE_STATE_TRANSITION_MODE_TRANSITION
Definition DeviceContext.h:242
uint32_t Uint32
32-bit unsigned integer
Definition BasicTypes.h:53
@ SET_VERTEX_BUFFERS_FLAG_RESET
Definition DeviceContext.h:971
@ CLEAR_DEPTH_FLAG
Clear depth part of the buffer.
Definition DeviceContext.h:784
Buffer interface.
Definition Buffer.h:245

All methods that may need to perform resource state transitions take RESOURCE_STATE_TRANSITION_MODE enum as parameter. The enum defines the following modes:

  • RESOURCE_STATE_TRANSITION_MODE_NONE - Perform no resource state transitions.
  • RESOURCE_STATE_TRANSITION_MODE_TRANSITION - Transition resources to the states required by the command.
  • RESOURCE_STATE_TRANSITION_MODE_VERIFY - Do not transition, but verify that states are correct.

The final step is to commit shader resources to the device context. This is accomplished by the IDeviceContext::CommitShaderResources() method:

m_pContext->CommitShaderResources(m_pSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES);

If the method is not called, the engine will detect that resources are not committed and output a debug message. Note that the last parameter tells the system to transition resources to correct states. If this flag is not specified, the resources must be explicitly transitioned to required states by a call to IDeviceContext::TransitionShaderResources():

m_pContext->TransitionShaderResources(m_pPSO, m_pSRB);

Note that the method requires pointer to the pipeline state that created the shader resource binding.

When all required states and resources are bound, IDeviceContext::DrawIndexed() can be used to execute a draw command or IDeviceContext::DispatchCompute() can be used to execute a compute command. Note that for a draw command, a graphics pipeline must be bound, and for a dispatch command, a compute pipeline must be bound. DrawIndexed() takes DrawIndexedAttribs structure as an argument, for example:

attrs.NumIndices = 36;
pContext->DrawIndexed(attrs);
@ DRAW_FLAG_VERIFY_STATES
Definition DeviceContext.h:160
@ VT_UINT16
Unsigned 16-bit integer.
Definition GraphicsTypes.h:60
Defines the indexed draw command attributes.
Definition DeviceContext.h:316
Uint32 NumIndices
The number of indices to draw.
Definition DeviceContext.h:318
DRAW_FLAGS Flags
Additional flags, see Diligent::DRAW_FLAGS.
Definition DeviceContext.h:326
VALUE_TYPE IndexType
The type of elements in the index buffer.
Definition DeviceContext.h:323

DRAW_FLAG_VERIFY_STATES flag instructs the engine to verify that vertex and index buffers used by the draw command are transitioned to proper states.

DispatchCompute() takes DispatchComputeAttribs structure that defines compute grid dimensions:

m_pContext->SetPipelineState(m_pComputePSO);
m_pContext->CommitShaderResources(m_pComputeSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES);
DispatchComputeAttribs DispatchAttrs{64, 64, 8};
m_pContext->DispatchCompute(DispatchAttrs);
Describes dispatch command arguments.
Definition DeviceContext.h:796

You can learn more about the engine API by studying samples and tutorials.

Low-level API interoperability

Diligent Engine extensively supports interoperability with underlying low-level APIs. The engine can be initialized by attaching to existing D3D11/D3D12 device or OpenGL/GLES context and provides access to the underlying native API objects. Refer to the following pages for more information:

Direct3D11 Interoperability

Direct3D12 Interoperability

OpenGL/GLES Interoperability

Vulkan Interoperability

NuGet Package Build Instructions

Follow the following steps to build the NuGet package:

  1. Install the required Python packages
python -m pip install -r ./BuildTools/.NET/requirements.txt
  1. Run the NuGet package build script, for example:
python ./BuildTools/.NET/dotnet-build-package.py -c Debug -d ./

Command Line Arguments

Argument Description Required
-c (configuration) Native dynamic libraries build configuration (e.g. Debug, Release, etc.) Yes
-d (root-dir) The path to the root directory of DiligentCore Yes
-s (settings) The path to the settings file No
dotnet-tests Flag indicating whether to run .NET tests No
dotnet-publish Flag indicating whether to publish the package to NuGet Gallery No
free-memory Use this argument if you encounter insufficient memory during the build process No

You can override the default settings using a settings file (check the default_settings dictionary in dotnet-build-package.py)

License

See Apache 2.0 license.

This project has some third-party dependencies, each of which may have independent licensing:

Contributing

To contribute your code, submit a Pull Request to this repository. Diligent Engine is distributed under the Apache 2.0 license that guarantees that content in the DiligentCore repository is free of Intellectual Property encumbrances. In submitting any content to this repository, you license that content under the same terms, and you agree that the content is free of any Intellectual Property claims and you have the right to license it under those terms.

Diligent Engine uses clang-format to ensure consistent source code style throughout the code base. The format is validated by CI for each commit and pull request, and the build will fail if any code formatting issue is found. Please refer to this page for instructions on how to set up clang-format and automatic code formatting.

Release History

See Release History


diligentgraphics.com

Diligent Engine on Twitter Diligent Engine on Facebook