SV_PrimitiveID 的含义由D3D11_PRIMITIVE_TOPOLOGY 确定(由ID3D11DeviceContext::IASetPrimitiveTopology 设置)。每个绘制调用每个图元都被分配一个编号,以便绘制图元。
例如:
// buffers that will be copied to the gpu
struct Vertex { float X, Y, Z; } VertexData[6] =
{
{ 0, 0, 0 },
{ 1, 0, 0 },
{ 1, 1, 0 },
{ 1, 1, 0 },
{ 0, 1, 0 },
{ 0, 0, 0 },
};
struct Triangle { int A, B, C; } IndexData[2] =
{
{ 0, 1, 2 },// SV_PrimitiveID == 0
{ 2, 4, 0 },// SV_PrimitiveID == 1
};
struct Instance { float X, Y, Z; } InstanceData[2] =
{
{ 0, 0, 0 },// SV_InstanceID == 0
{ 0, 0, 1 },// SV_InstanceID == 1
};
...
pDeviceConstext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pDeviceConstext->Draw(6, 0);// would result in two triangles numbered (value of SV_PrimitiveID) 0 and 1
pDeviceConstext->DrawIndexed(2 * 3, 0, 0);// same thing
pDeviceConstext->DrawInstanced(6, 2, 0, 0);// now 4 triangles, 2 for the 0th instance and 2 for the 1st; SV_PrimitiveID restarts from zero for every instance!
...
我不确定几何着色器和 SV_PrimitiveID 之间的交互,但 DirectX 有据可查。以下是一些链接:
https://docs.microsoft.com/en-us/windows/win32/direct3d11/geometry-shader-stage
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-geometry-shader
我个人觉得直观地显示任何我可能会感到困惑的信息很有用。例如设置像这样的像素着色器:
float4 main(uint pid : SV_PrimitiveId) : SV_Target
{
static const uint N = 16;
float3 color = float3(((pid / uint3(1, N, N * N)) % N) / (float)N);
return float4(color, 1);
}