Textures in DirectX 12
Textures are fundamental resources for rendering detailed surfaces. DirectX provides a flexible API for creating, binding, and sampling textures across a wide range of formats.
Overview[show]
Textures can be 1D, 2D, 3D, cube maps, or arrays. They are stored in ID3D12Resource
objects and accessed via Shader Resource Views (SRV)
or Render Target Views (RTV)
.
// Example: Creating a 2D texture
D3D12_RESOURCE_DESC texDesc = {};
texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
texDesc.Width = 1024;
texDesc.Height = 1024;
texDesc.DepthOrArraySize = 1;
texDesc.MipLevels = 0;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.SampleDesc.Count = 1;
texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
// Allocate the resource
ID3D12Resource* texture = nullptr;
device->CreateCommittedResource(
&heapProps,
D3D12_HEAP_FLAG_NONE,
&texDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
nullptr,
IID_PPV_ARGS(&texture));
Texture Types[show]
- 1D Textures – Used for lookup tables.
- 2D Textures – Most common for images.
- 3D Textures – Volume data such as fog or medical scans.
- Cube Maps – Environment mapping.
- Texture Arrays – Batch multiple textures of same type.
// 2D texture array example
texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
texDesc.DepthOrArraySize = 6; // 6 layers
texDesc.MipLevels = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
Creating Textures[show]
Steps to create a texture include defining a D3D12_RESOURCE_DESC
, allocating memory, and uploading data.
// Uploading data
const UINT64 uploadBufferSize = GetRequiredIntermediateSize(texture, 0, 1);
ID3D12Resource* uploadHeap = nullptr;
device->CreateCommittedResource(
&heapPropsUpload,
D3D12_HEAP_FLAG_NONE,
&uploadDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&uploadHeap));
UpdateSubresources(commandList, texture, uploadHeap, 0, 0, 1, &subresourceData);
commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(texture,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));
Mapping & Sampling[show]
Shaders sample textures using SamplerState
objects. Configure address modes, filter types, and LOD settings.
// HLSL sampler definition
SamplerState samplerLinear
{
Filter = MIN_MAG_MIP_LINEAR;
AddressU = Wrap;
AddressV = Wrap;
};
Texture2D diffuseMap : register(t0);
float4 main(float2 uv : TEXCOORD) : SV_TARGET
{
return diffuseMap.Sample(samplerLinear, uv);
}
Resource Management[show]
Efficient texture usage involves proper state transitions, mipmap generation, and descriptor heap management.
// Creating an SRV descriptor
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Format = texDesc.Format;
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
device->CreateShaderResourceView(texture, &srvDesc, srvHeapHandle);
Reference[show]
For full API details, see the official DirectX 12 documentation.