Step 2: Create the Depth Buffer

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 sample uses the following code for this task:

    // If the enumerated format is good (it should be), the 
    // dwSize member will be properly initialized. Check this
    // just in case. 
    if( sizeof(DDPIXELFORMAT) != ddpfZBuffer.dwSize )
        return E_FAIL;
 
    // Get z-buffer dimensions from the render target
    // Setup the surface desc for the z-buffer.
    ddsd.dwFlags        = DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_PIXELFORMAT;
    ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER;
    ddsd.dwWidth        = g_rcScreenRect.right - g_rcScreenRect.left;
    ddsd.dwHeight       = g_rcScreenRect.bottom - g_rcScreenRect.top;
    memcpy( &ddsd.ddpfPixelFormat, &ddpfZBuffer, sizeof(DDPIXELFORMAT) );
 
    // Software devices require system-memory depth buffers.
    if( IsEqualIID( *pDeviceGUID, IID_IDirect3DHALDevice ) )
        ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
    else
        ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
 
    // Create the depth-buffer. 
    if( FAILED( hr = g_pDD4->CreateSurface( &ddsd, &g_pddsZBuffer, NULL ) ) )
        return hr;
 

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

Note  A hardware device can use a depth buffer regardless of its location in memory. When using a hardware device, it's 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. The preceding code checks for this possibility and includes the DDSCAPS_SYSTEMMEMORY flag if necessary.

Once the surface description is ready, the code calls the IDirectDraw4::CreateSurface method to create the new depth-buffer surface. 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.