DirectX 11 native triangle rendering
Draw a triangle from Device to Draw
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
To draw a triangle in DirectX 11, you need Device, DeviceContext, SwapChain, RenderTargetView, VertexBuffer, and Shader. Let's summarize only the core flow required for rendering, excluding the window creation code.
Create a device and swap chain
DXGI_SWAP_CHAIN_DESC Desc{};
Desc.BufferCount = 1;
Desc.BufferDesc.Width = Width;
Desc.BufferDesc.Height = Height;
Desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
Desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
Desc.OutputWindow = WindowHandle;
Desc.SampleDesc.Count = 1;
Desc.Windowed = TRUE;
Desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
0,
nullptr,
0,
D3D11_SDK_VERSION,
&Desc,
&SwapChain,
&Device,
nullptr,
&DeviceContext
);
Device creates GPU resources, and DeviceContext is used to record and execute commands. SwapChain replaces the BackBuffer shown on the screen.
Create RenderTargetView
ID3D11Texture2D* BackBuffer = nullptr;
SwapChain->GetBuffer(0, IID_PPV_ARGS(&BackBuffer));
Device->CreateRenderTargetView(BackBuffer, nullptr, &RenderTargetView);
BackBuffer->Release();
Create a View so that the BackBuffer texture can be used as a render target.
Create vertex buffer
struct Vertex
{
DirectX::XMFLOAT3 Position;
DirectX::XMFLOAT4 Color;
};
Vertex Vertices[] =
{
{ { 0.0f, 0.5f, 0.0f }, { 1, 0, 0, 1 } },
{ { 0.5f, -0.5f, 0.0f }, { 0, 1, 0, 1 } },
{ { -0.5f, -0.5f, 0.0f }, { 0, 0, 1, 1 } }
};
D3D11_BUFFER_DESC BufferDesc{};
BufferDesc.ByteWidth = sizeof(Vertices);
BufferDesc.Usage = D3D11_USAGE_DEFAULT;
BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA InitialData{};
InitialData.pSysMem = Vertices;
Device->CreateBuffer(&BufferDesc, &InitialData, &VertexBuffer);
Draw every frame
const float ClearColor[4] = { 0.08f, 0.08f, 0.12f, 1.0f };
DeviceContext->ClearRenderTargetView(RenderTargetView, ClearColor);
UINT Stride = sizeof(Vertex);
UINT Offset = 0;
DeviceContext->IASetVertexBuffers(0, 1, &VertexBuffer, &Stride, &Offset);
DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
DeviceContext->IASetInputLayout(InputLayout);
DeviceContext->VSSetShader(VertexShader, nullptr, 0);
DeviceContext->PSSetShader(PixelShader, nullptr, 0);
DeviceContext->OMSetRenderTargets(1, &RenderTargetView, nullptr);
DeviceContext->RSSetViewports(1, &Viewport);
DeviceContext->Draw(3, 0);
SwapChain->Present(1, 0);
Draw(3, 0)reads 3 vertices starting from 0 and draws a triangle. If only a black screen appears, it is best to check the vertex order, Viewport, Shader compilation results, and RenderTarget connection.