Overview
Resource management in DirectX textures involves allocating GPU memory, controlling resource states, and synchronizing CPU‑GPU access. Proper handling ensures optimal performance and prevents leaks or undefined behavior.
Creating Resources
Use ID3D11Device::CreateTexture2D
(or corresponding DX12 functions) with a D3D11_TEXTURE2D_DESC
that describes format, size, usage, and bind flags.
#include <d3d11.h>
ID3D11Texture2D* tex = nullptr;
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = 1024;
desc.Height = 1024;
desc.MipLevels = 0; // generate mipmaps
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
desc.CPUAccessFlags = 0;
desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
HRESULT hr = device->CreateTexture2D(&desc, nullptr, &tex);
if (FAILED(hr)) { /* handle error */ }
Managing Resource Lifetime
Resources are reference‑counted COM objects. Release them when no longer needed. Prefer ComPtr<T>
to automate lifetime management.
Microsoft::WRL::ComPtr<ID3D11Texture2D> texture;
device->CreateTexture2D(&desc, nullptr, &texture);
// texture automatically releases when it goes out of scope
Updating Resources
For dynamic data, create textures with D3D11_USAGE_DYNAMIC
and update via Map/Unmap
or UpdateSubresource
.
D3D11_MAPPED_SUBRESOURCE mapped;
deviceContext->Map(texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
memcpy(mapped.pData, sourceData, rowPitch * height);
deviceContext->Unmap(texture.Get(), 0);
Mapping & Unmapping
When mapping, respect the CPU access flags and avoid writing outside the mapped region. Always unmap before using the resource in the GPU pipeline.
// Example of read‑only mapping
D3D11_MAPPED_SUBRESOURCE ms;
deviceContext->Map(texture.Get(), 0, D3D11_MAP_READ, 0, &ms);
// Read data...
deviceContext->Unmap(texture.Get(), 0);
Best Practices
- Prefer immutable resources for static textures.
- Use staging resources only for CPU‑GPU transfers.
- Generate mipmaps after initial data upload with
GenerateMips
. - Avoid frequent state changes; batch draws with the same texture.
- Release resources promptly to free GPU memory.