繁体   English   中英

具有Opengl的MFC从鼠标的2d坐标获取3d坐标

[英]MFC with Opengl get 3d coordinate from 2d coordinate of mouse

我在基于鼠标的MFC应用程序中使用NEHE教程中的代码

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);
}

好的,我发现由于以下情况而产生的问题

我在两个不同的hdc的设置之间使用绘图功能,因为我有两个不同的mfc图片控制窗口,并且两者都有不同的绘图。 这就是为什么当我使用上述gl代码时,在鼠标按下或鼠标单击事件内部,总是通过s = glGetError()给我带来错误1282的原因。

因此,要使其正常工作,我刚刚在

wglMakeCurrent(hdc, hrc);

//my code

wglMakeCurrent(NULL, NULL);

它起作用了,现在所有xy和z值都在屏幕上

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM