Step 2.4: Prepare the Viewport

After you create a rendering device, you can create a viewport object and assign it to the device. In short, the viewport determines how the geometry in a 3-D scene is clipped and then represented in the 2-D space of a display screen. (For a conceptual overview about viewports, see Viewports and Clipping.)

Setting up a viewport is a straight-forward process that starts with preparing the viewport parameters in a D3DVIEWPORT2 structure. The Triangle sample sets the viewport parameters to the dimensions of the render target surface, with a standard 3-D clipping region that exists from -1.0 to 1.0 in x, from 1.0 to -1.0 in y, and from 0.0 to 1.0 in z:

    // Set up the viewport data parameters
    D3DVIEWPORT2 vdData;
    ZeroMemory( &vdData, sizeof(D3DVIEWPORT2) );
 
    // Always set the structure size!
    vdData.dwSize       = sizeof(D3DVIEWPORT2);  
    vdData.dwWidth      = g_rcScreenRect.right - g_rcScreenRect.left;
    vdData.dwHeight     = g_rcScreenRect.bottom - g_rcScreenRect.top;
    vdData.dvClipX      = -1.0f;
    vdData.dvClipWidth  = 2.0f;
    vdData.dvClipY      = 1.0f;
    vdData.dvClipHeight = 2.0f;
    vdData.dvMaxZ       = 1.0f;
 

Once the viewport parameter structure is ready, Triangle creates the viewport and assigns it to the rendering device. Note that it doesn't actually apply the parameters until after the viewport is assigned to the device. This is a requirement.

    // Create the viewport.
    hr = g_pD3D->CreateViewport( &g_pvViewport, NULL );
    if( FAILED( hr ) )
        return hr;
 
    // Associate the viewport with the device.
    g_pd3dDevice->AddViewport( g_pvViewport );
 
    // Set the parameters for the new viewport.
    g_pvViewport->SetViewport2( &vdData );
 

Assigning the viewport to the device merely adds it to an internal list of viewports for the device, it doesn't actually select the viewport to be used during rendering. The following code selects the viewport:

    // Set the current viewport for the device
    g_pd3dDevice->SetCurrentViewport( g_pvViewport );
 

Now that the basic DirectX objects have been created, you can start preparing the subordinate objects required to render scene, which is the topic of Step 3: Initialize the Scene.