The second method of deep sorting is the Z-buffer method, which is the most commonly used method for graphics hardware devices. This method depends on pixels. Each pixel has a Z value (the Z value is the distance between the pixel and the observer ). When each pixel is written, the Renderer first checks whether a pixel with a smaller Z value exists. If it does not exist, the pixel is drawn. If it exists, the pixel is skipped.
Many 3D graphics acceleration cards have a built-in Z buffer, which is also the reason for choosing the Z buffer method for deep sorting. The easiest way to use the Z buffer in an application is to initialize the Z buffer when creating a device object and setting the display mode, as shown below:
View Source
Print?
01 |
D3DPRESENT_PARAMETERS d3dpp; |
02 |
ZeroMemory(&d3dpp, sizeof(d3dpp)); |
03 |
d3dpp.Windowed = TRUE; |
04 |
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; |
05 |
d3dpp.BackBufferFormat = d3ddm.Format; |
06 |
// Set the Z buffer and the Z buffer format. |
07 |
d3dpp.EnableAutoDepthStencil = TRUE; |
08 |
d3dpp.AutoDepthStencilFormat = D3DFMT_D16; |
10 |
if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,g_hWnd, |
11 |
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice))) |
14 |
// Set the rendering states |
15 |
g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); |
16 |
g_pD3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); |
At the same time, idirect3ddevice9: Clear should be used to clear the Z cache before each frame is drawn.
View Source
Print?
1 |
// clear device back buffer |
2 |
g_d3d_device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 0, 255), 1.0f, 0); |
In fact, this is because of Z-test. When rendering a polygon mesh object to a scenario, the object that is farther away from the observer should be blurred, and the object that is closer to the observer should be clearer. This is the depth sorting ).