在着色器中访问索引缓冲区 (Directx 11)
Accessing Index buffer in shaders (Directx 11)
我有一个顶点和索引缓冲区,我正在将网格渲染为一个像素,我想知道渲染了网格的哪个三角形,并在 cpu 上访问其在索引缓冲区中的索引以进行进一步处理(基于我的网格,只有一个三角形可以渲染到该像素)。
我首先用 SV_PrimitiveId 实现它,我希望它会为索引缓冲区(第一个三角形)的前三个索引生成 0,为后三个索引生成 1,所以 on.This 我可以这样从 gpu 复制数据并读取该 id 并找到三角形,但问题是 id 与我的索引缓冲区不对应(即。因为我 运行 它给出的程序例如第三个三角形 id 7,其他时间 10等等)。
我想知道有没有办法确定像素着色器正在绘制哪个三角形并在索引缓冲区中找到它的索引以便在 cpu 上找到它?
这应该有效:
C++:
...
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPrimitiveIDs;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pPIDsRTV;
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPIDsStaging;
...
const int number_of_rtvs = 2;
ID3D11RenderTargetView* rtvs[number_of_rtvs] =
{
pScreenRTV.Get(),
pPIDsRTV.Get(),
};
pDeviceContext->OMSetRenderTargets(number_of_rtvs, rtvs, pDepthStencilView.Get());
...
pDeviceContext->CopyResource(pPIDStaging.Get(), pPrimitiveIDs.Get());
D3D11_MAPPED_SUBRESOURCE MappedResource;
pDeviceContext->Map(pPIDStaging.Get(), 0, D3D11_MAP_READ, 0, &MappedResource);
// here is the pid
// in case of a 1x1 back buffer you would just read the first value
UINT pid = *((UINT*)MappedResource.pData + MouseX + WindowWidth * MouseY);
pDeviceContext->Unmap(pPIDStaging.Get(), 0);
...
像素着色器:
struct PSOutput
{
float4 color : SV_Target0;
uint pid : SV_Target1;
};
PSOutput main(..., uint pid : SV_PrimitiveId)
{
...
PSOutput output =
{
color,
pid,
};
return output;
}
我有一个顶点和索引缓冲区,我正在将网格渲染为一个像素,我想知道渲染了网格的哪个三角形,并在 cpu 上访问其在索引缓冲区中的索引以进行进一步处理(基于我的网格,只有一个三角形可以渲染到该像素)。
我首先用 SV_PrimitiveId 实现它,我希望它会为索引缓冲区(第一个三角形)的前三个索引生成 0,为后三个索引生成 1,所以 on.This 我可以这样从 gpu 复制数据并读取该 id 并找到三角形,但问题是 id 与我的索引缓冲区不对应(即。因为我 运行 它给出的程序例如第三个三角形 id 7,其他时间 10等等)。
我想知道有没有办法确定像素着色器正在绘制哪个三角形并在索引缓冲区中找到它的索引以便在 cpu 上找到它?
这应该有效:
C++:
...
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPrimitiveIDs;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pPIDsRTV;
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPIDsStaging;
...
const int number_of_rtvs = 2;
ID3D11RenderTargetView* rtvs[number_of_rtvs] =
{
pScreenRTV.Get(),
pPIDsRTV.Get(),
};
pDeviceContext->OMSetRenderTargets(number_of_rtvs, rtvs, pDepthStencilView.Get());
...
pDeviceContext->CopyResource(pPIDStaging.Get(), pPrimitiveIDs.Get());
D3D11_MAPPED_SUBRESOURCE MappedResource;
pDeviceContext->Map(pPIDStaging.Get(), 0, D3D11_MAP_READ, 0, &MappedResource);
// here is the pid
// in case of a 1x1 back buffer you would just read the first value
UINT pid = *((UINT*)MappedResource.pData + MouseX + WindowWidth * MouseY);
pDeviceContext->Unmap(pPIDStaging.Get(), 0);
...
像素着色器:
struct PSOutput
{
float4 color : SV_Target0;
uint pid : SV_Target1;
};
PSOutput main(..., uint pid : SV_PrimitiveId)
{
...
PSOutput output =
{
color,
pid,
};
return output;
}