Platform SDK: DirectX

Setting Up a Projection Matrix

[C++]

The following ProjectionMatrix sample function—written in C++—takes four input parameters that set the front and back clipping planes, as well as the horizontal and vertical field of view angles. (This code parallels the approach discussed in the What Is the Projection Transformation? topic.) The fields-of-view should be less than pi radians.

D3DMATRIX 
ProjectionMatrix(const float near_plane,
     // distance to near clipping plane
 const float far_plane,
     // distance to far clipping plane
 const float fov_horiz,
     // horizontal field of view angle, in radians
 const float fov_vert)
     // vertical field of view angle, in radians
{
    float    h, w, Q;
 
    w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
    h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
    Q = far_plane/(far_plane - near_plane);
 
    D3DMATRIX ret;
    ZeroMemory(&ret, sizeof(ret));

    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // end of ProjectionMatrix()

When you have created the matrix, you need set it in a call to the IDirect3DDevice7::SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.

[Visual Basic]

Applications written in Visual Basic can create a projection matrix "by hand" as described in the What Is the Projection Transformation? topic. However, the DirectX7 object includes an implementation of this approach, offered through the DirectX7.ProjectionMatrix method.

The following Visual Basic code fragment shows how this DirectX7.ProjectionMatrix is commonly used.

' 
' For this example, the g_dx variable contains a reference to a global
' DirectX7 object.
' 
' The pi variable is a variable of type Single that loosely approximates
' the trigonometric constant of the same name (3.141592).
Dim matProj As D3DMATRIX

' Initialize the matrix to the identity.
g_dx.IdentityMatrix matProj

' Create a projection matrix that reflects a viewing frustum with the 
' front and rear clipping planes at 1 and 1000, and a field-of-view 
' angle of pi/2 radians (90 degrees).
Call g_dx.ProjectionMatrix(matProj, 1, 1000, pi / 2)

When you have created the matrix, you need set it in a call to the Direct3DDevice7.SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.