HRESULT hr;
D3DXVECTOR3 vPickRayDir;
D3DXVECTOR3 vPickRayOrig;
m_dwNumIntersections = 0L;
// Get the pick ray from the mouse position
if( GetCapture() )
{
D3DXMATRIXA16 matProj;
m_pd3dDevice->GetTransform( D3DTS_PROJECTION, &matProj );
POINT ptCursor;
GetCursorPos( &ptCursor );
ScreenToClient( m_hWnd, &ptCursor );
// Compute the vector of the pick ray in screen space
D3DXVECTOR3 v;
v.x = ( ( ( 2.0f * ptCursor.x ) / m_d3dsdBackBuffer.Width ) - 1 ) / matProj._11;
v.y = -( ( ( 2.0f * ptCursor.y ) / m_d3dsdBackBuffer.Height ) - 1 ) / matProj._22;
v.z = 1.0f;
// Get the inverse of the composite view and world matrix
D3DXMATRIXA16 matView, matWorld, m;
m_pd3dDevice->GetTransform( D3DTS_VIEW, &matView );
m_pd3dDevice->GetTransform( D3DTS_WORLD, &matWorld );
m = matWorld * matView;
D3DXMatrixInverse( &m, NULL, &m );
// Transform the screen space pick ray into 3D space
vPickRayDir.x = v.x*m._11 + v.y*m._21 + v.z*m._31;
vPickRayDir.y = v.x*m._12 + v.y*m._22 + v.z*m._32;
vPickRayDir.z = v.x*m._13 + v.y*m._23 + v.z*m._33;
vPickRayOrig.x = m._41;
vPickRayOrig.y = m._42;
vPickRayOrig.z = m._43;
}