2012-09-10 81 views
0

我使用從訥河教程這段代碼的座標點擊鼠標MFC使用OpenGL得到二維三維座標在我的MFC基於應用鼠標

void CRightOGL::OnLButtonDown(UINT nFlags, CPoint point) 

{ 
// TODO: Add your message handler code here and/or call default 

GLint viewport[4]; 
GLdouble modelview[16]={0}; 
GLdouble projection[16]; 
GLfloat winX, winY, winZ; 
GLdouble posX, posY, posZ; 
GLfloat mv[16]; 

glGetFloatv(GL_MODELVIEW_MATRIX, mv); 
glGetDoublev(GL_MODELVIEW_MATRIX, modelview); 
glGetDoublev(GL_PROJECTION_MATRIX, projection); 
glGetIntegerv(GL_VIEWPORT, viewport); 

winX = (float)point.x; 
winY = (float)viewport[3] - (float)point.y; 
glReadPixels(point.x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); 

gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); 


COpenGLControl::OnLButtonDown(nFlags, point); 

    } 

但問題是,我每次都得到不正確的值POSX, & posY,& posZ ...值總是在-9.25555,-9.255555,-9.255555。不僅如此,而且modelview矩陣每次都返回相同的-9.555值。

如果我把所有東西初始化爲0,那麼posX,posY和PosZ只返回0而不是正確的座標。鼠標的x和y值非常好,所以從鼠標方面來說沒有問題。

我在做什麼錯了?

我的OpenGL初始化代碼如下

void COpenGLControl::oglInitialize(void) 
{ 
// Initial Setup: 
// 
static PIXELFORMATDESCRIPTOR pfd = 
{ 
    sizeof(PIXELFORMATDESCRIPTOR), 
    1, 
    PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 
    PFD_TYPE_RGBA, 
    32, // bit depth 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    16, // z-buffer depth 
    0, 0, 0, 0, 0, 0, 0, 
}; 


// Get device context only once. 
hdc = GetDC()->m_hDC; 

// Pixel format. 
m_nPixelFormat = ChoosePixelFormat(hdc, &pfd); 
SetPixelFormat(hdc, m_nPixelFormat, &pfd); 

// Create the OpenGL Rendering Context. 
hrc = wglCreateContext(hdc); 
wglMakeCurrent(hdc, hrc); 

// Basic Setup: 
// 
// Set color to use when clearing the background. 
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); 
glClearDepth(1.0f); 

// Turn on backface culling 
glFrontFace(GL_CCW); 
glCullFace(GL_BACK); 

// Turn on depth testing 
glEnable(GL_DEPTH_TEST); 
glDepthFunc(GL_LEQUAL); 
glEnable(GL_DEPTH); 


//glEnable(GL_TEXTURE_2D); // Enable 2D textures 
// Send draw request 

GLenum a = glGetError(); 

OnDraw(NULL); 
} 

回答

0

好吧,我想通了這個問題,以下面的情形

我使用的兩種不同的HDC設置之間繪製函數生成因,因爲我有兩個mfc的不同圖片控制窗口都有不同的繪圖。這就是爲什麼在鼠標向下或鼠標點擊事件時,當我使用上面的gl代碼時,它始終用於通過s = glGetError()給出錯誤1282。

所以,使其工作我只是說內

wglMakeCurrent(hdc, hrc); 

//my code 

wglMakeCurrent(NULL, NULL); 

上面的代碼和它的工作,現在所有的X,Y和Z值是屏幕

+0

你把代碼之間嗎? – manatttta