| ?/TD> |
| Microsoft DirectX 9.0 |
Alpha can also be provided with textures. First, the texture must be created. Then it must be set on a texture stage and the appropriate stage operation and operands selected. Then, the primitive can be drawn with transparency.
// Create an alpha texture CreateEmptyTexture( "gradient", 128,128,0,D3DTEXTR_32BITSPERPIXEL|D3DTEXTR_CREATEWITHALPHA); LoadGradient( "gradient" );
The body of these routines does the work. CreateEmptyTexture sets everything up by creating an empty texture.
HRESULT LoadGradient( TCHAR* strName )
{
TextureContainer* ptcTexture = FindTexture( strName );
// Load a gradient
return ptcTexture->LoadGradient32( strName );
}
It calls LoadGradient32 to load the alpha channel when it has performed a texture lookup.
HRESULT TextureContainer::LoadGradient32( TCHAR* strPathname )
{
int yGrad, xGrad;
// w x h set in createempty
m_pRGBAData = new DWORD[m_dwWidth*m_dwHeight];
if( m_pRGBAData == NULL )
{
return E_FAIL;
}
for( DWORD y=0; y < m_dwHeight; y++ )
{
DWORD dwOffset = y*m_dwWidth;
yGrad = (int)(((float)y/(float)m_dwWidth) * 255.0f);
for( DWORD x=0; x < m_dwWidth; x )
{
xGrad = (int)(((float)x/(float)m_dwWidth) * 255.0f);
DWORD b = (DWORD)(xGrad + (255 - yGrad))/2 & 0xFF;
DWORD g = (DWORD)((255 - xGrad) + yGrad)/2 & 0xFF;
DWORD r = (DWORD)(xGrad + yGrad)/2 & 0xFF;
DWORD a = (DWORD)(xGrad + yGrad)/2 & 0xFF;
m_pRGBAData[dwOffset+x] = (r<<24L)+(g<<16L)+(b<<8L)+(a);
x++;
}
}
return S_OK;
}
The alpha value is calculated based on the current pixel's relative x/y position within the texture size.
Next, assign the texture to a texture stage and set up the texture stage.
// Assign texture
m_pd3dDevice->SetTexture( 0, D3DTextr_GetSurface("gradient") );
// Texture stage states
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
m_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
// Draw the lit sphere
m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
m_pObstacleVertices, m_dwNumObstacleVertices,
m_pObstacleIndices, m_dwNumObstacleIndices, 0 );
This results in a transparent, textured sphere.