Platform SDK: DirectX

Step 2: Create the Depth Buffer

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Now that you have chosen the depth-buffer format, you can create the DirectDrawSurface object that will become the depth buffer. The pixel format of the surface is the one determined through enumeration, but the surface dimensions must be identical to the render-target surface to which it will be attached. The ZBuffer application uses the following code for this task:

    g_ddsd.lFlags = DDSD_CAPS Or DDSD_WIDTH Or DDSD_HEIGHT Or DDSD_PIXELFORMAT
    g_ddsd.ddsCaps.lCaps = DDSCAPS_ZBUFFER
    g_ddsd.lWidth = g_rcDest.Right - g_rcDest.Left
    g_ddsd.lHeight = g_rcDest.Bottom - g_rcDest.Top
    g_ddsd.ddpfPixelFormat = ddpfZBuffer

The preceding code simply prepares a DDSURFACEDESC2 type for the depth buffer, using the dimensions of the render-target surface calculated from previously set global variables. Finally, the pixel format information retrieved during the previous step, Step 1: Enumerate Depth-Buffer Formats, is copied into the surface description:

    g_ddsd.ddpfPixelFormat = ddpfZBuffer

Note  A hardware device can use a depth buffer regardless of its location in memory. When using a hardware device, it is best to let the device determine the best location for the buffer by omitting the DDSCAPS_VIDEOMEMORY and DDSCAPS_SYSTEMMEMORY surface capability flags. However, a software device can only be created if the depth buffer exists in system memory. In the following code, the ZBuffer tutorial application sets the DDSCAPS_SYSTEMMEMORY flag; although, your application should implement a simple searching mechanism to determine whether your application should allocate the surface memory in system memory or in display memory.

    ' Specify DDSCAPS_VIDEOMEMORY if your surface exists in display memory.
    ' See the SDK documentation for more information.
    g_ddsd.ddsCaps.lCaps = g_ddsd.ddsCaps.lCaps Or DDSCAPS_SYSTEMMEMORY

Once the surface description is ready, the code calls the DirectDraw7.CreateSurface method to create the new depth-buffer surface:

    Set g_ddsZBuffer = g_dd.CreateSurface(g_ddsd)

After the depth buffer is created, it can be attached to the surface that will be used as the render target, as described in Step 3: Attach the Depth Buffer.