DirectX SDK

Preparing to Draw a Sprite

This section details the preparatory steps required before drawing a sprite using the Direct3DX utility library.

Before transferring the sprite to the rendering target, call the appropriate methods to begin the scene and clear the render target.

    hr = m_pd3dDevice->BeginScene();
 
    hr = m_pd3dx->Clear(D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER);

Initialize the rasterizer for rendering sprites by calling the D3DXPrepareDeviceForSprite function. Typically, this function only needs to be called once for all of the sprites that are rendered. However, D3DXPrepareDeviceForSprite does need to be called again if any render state changes are made outside of a D3DXDrawSpriteSimple call.

    ::D3DXPrepareDeviceForSprite(m_pd3dDevice);
    

You can set up a RECT structure that will define where the sprite should appear on the source texture.

    RECT srcRect;

Often, when using sprites your images will be comprised from a grid of pictures. In this case, your source RECT structure will be a different sub-rectangle for every frame. For example, your grid of pictures may have 10 columns and 6 rows. To determine the x-position, you would compute m_currentFrame % 10 (where m_currentFrame is the current frame). To determine the y-position, you would compute m_currentFrame / 10.

    int iX = (m_currentFrame % 10);
    int iY = (m_currentFrame / 10);

Each frame is spaced into 64 pixels by 64 pixels cells.

    srcRect.left = iX * 64;
    srcRect.top  = iY * 64;

Each sub-frame of the source RECT structure is 64 pixels wide and 48 pixels tall.

    srcRect.right  = srcRect.left + 64;
    srcRect.bottom = srcRect.top  + 48;

Now, you should retrieve the current viewport.

    D3DVIEWPORT7 viewport;
    hr = m_pd3dDevice->GetViewport(&viewport);

Then, you can convert the viewport into a RECT structure.

    RECT rectViewport;
    rectViewport.left   = viewport.dwX;
    rectViewport.top    = viewport.dwY;
    rectViewport.right  = viewport.dwX + viewport.dwWidth;
    rectViewport.bottom = viewport.dwY + viewport.dwHeight;

The non-rotated render target should be centered in the viewport.

    D3DXVECTOR3 pointDest; 
    pointDest.x = (float)viewport.dwX + (float)viewport.dwWidth  / 2.0f;
    pointDest.y = (float)viewport.dwY + (float)viewport.dwHeight / 2.0f;

At this point you can draw the sprite by calling one of the sprite drawing functions provided by the Direct3DX utility library.

For information on how to draw a sprite, see Drawing a Simple Sprite and Drawing a Transformed Sprite.

After you have drawn the sprite, you should call the appropriate methods to end the scene and update the frame.

    hr = m_pd3dDevice->EndScene();
    
    hr = m_pd3dx->UpdateFrame(D3DX_DEFAULT);