在D3D中创建一个深度纹理,并传入片段程序。主要步骤如下:
1、创建一个深度纹理
//创建深度纹理
//1 获取后台缓存信息
IDirect3DSurface9 * pSurface = nullptr;
hr = pDevice->GetRenderTarget(0, &pSurface); //ref count +1
if (FAILED(hr))
{
MessageBox(NULL, _T("获取RenderTarget failed"), NULL, MB_OK);
return false;
}
D3DSURFACE_DESC desc;
pSurface->GetDesc(&desc);
pSurface->Release(); //ref count -1
int texWidth, texHeight;
texWidth = desc.Width;
texHeight = desc.Height;
//2 根据后台缓存大小创建深度纹理
hr = pDevice->CreateTexture(texWidth,
texHeight,
1,
D3DUSAGE_DEPTHSTENCIL,
D3DFMT_D16,
D3DPOOL_DEFAULT,
&g_pShadowTexture,
nullptr);
2、设置深度纹理到后台
IDirect3DSurface9 * pOldDepthSurface = nullptr;
IDirect3DSurface9 * pNewDepthSurface = nullptr;
hr = pDev->GetDepthStencilSurface(&pOldDepthSurface);
assert(SUCCEEDED(hr));
hr = g_pShadowTexture->GetSurfaceLevel(0, &pNewDepthSurface); //顶层纹理是0,先前这里犯了个错误,设置了1,导致失败
assert(SUCCEEDED(hr));
hr = pDev->SetDepthStencilSurface(pNewDepthSurface); //设置新的深度缓存
assert(SUCCEEDED(hr));
pDev->Clear(0, NULL, D3DCLEAR_ZBUFFER, 0, 1.f, 0); //*** //重置深度缓存的值,以免影响正确的结果
3、设置好深度缓存后,下面就可以进行场景的渲染,将深度值写入上面设置的深度缓存中
Render Objects
在渲染场景前,最好将关闭对颜色缓存的写入操作,后面再将其开启
pDev->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
4、设置回原来旧的深度缓存,并开启颜色写操作
pDev->SetDepthStencilSurface(pOldDepthSurface); //设置旧的深度模版缓存
pOldDepthSurface->Release();
pNewDepthSurface->Release();
pDev->SetRenderState(D3DRS_COLORWRITEENABLE, //开启颜色写
D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
5、后面就可以进行我们正常的操作了