Книга: DirectX 8 Programming Tutorial

Depth Buffers

Depth Buffers

Using a Depth Buffer (also called a z-buffer) ensures that polygons are rendered correctly based on their depth (distance from the camera). Lets say, for example, that in your scene you have two squares – one blue and one green. The blue one has a z value of 10 and the green square has a z value of 20 (the camera is at the origin). This means that the blue square is in front of the green one. A depth buffer is used to make sure that where one object is in front of another, the correct one is rendered. DirectX will test a pixel on the screen against an object to see how close it is to the camera. It stores this value in the depth buffer. It will then test the same pixel against the next object and compares it's distance with the value held in the depth buffer. If it is shorter, it'll overwrite the old value with the new one, otherwise it will be ignored (there is something in front of it). This will determine what colour the pixel will be, blue or green. Fig 4.1 below, shows this for a given pixel on the rendering surface.


Fig 4.1

To use a depth buffer in your program is pretty easy. All you need to do is select the correct format in your InitialiseD3D function, enable depth buffering and ensure that you clear the depth buffer in your Render function. In the source for this tutorial (download above), I have added some code to select a depth buffer format in the InitialiseD3D method of CGame. There are two properties of the D3DPRESENT_PARAMETERS structure that need to be set:

d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.EnableAutoDepthStencil = TRUE;

To enable depth buffering, you need to add the following line to your InitialiseD3D method.

m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

Then in the Render method of CGame, make sure that you clear the depth buffer as well as the back buffer by adding the D3DCLEAR_ZBUFFER flag to the device clear method, shown below.

m_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

Оглавление книги

Оглавление статьи/книги

Генерация: 0.854. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз