gluProject() 的奇怪结果

Weird Result with gluProject()

我的 gluProject 函数 (OpenGL) 有问题。 我想将一个简单的 3D 点从对象 space 转换到屏幕 space。 我的代码如下:

int main(){
    GLdouble mvmatrix[16];
    GLdouble projmatrix[16];
    GLint viewport[4];
    GLdouble winx;
    GLdouble winy;
    GLdouble winz;
    glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
    glGetIntegerv(GL_VIEWPORT, viewport);
    gluProject(0.0, 0.0, 0.0, mvmatrix, projmatrix, viewport, &winx, &winy, &winz);
    std::cout << winx << winy;
    getchar();
    getchar();
    return 0;
}

输出为:

-1.71799e+009 -1.71799e+009

这是一个奇怪的结果,对我来说没有意义。 有谁知道出了什么问题?我没有在网上找到任何东西。

Does anyone know what went wrong?

您尚未创建 GL context 并在使用 glGetDoublev()glGetIntegerv() 之前将其设为当前:

In order for any OpenGL commands to work, a context must be current; all OpenGL commands affect the state of whichever context is current. The current context is a thread-local variable, so a single process can have several threads, each of which has its own current context. However, a single context cannot be current in multiple threads at the same time.

您可以使用 (Free)GLUT (among other things (not exhaustive)) 创建一个 window 和关联的 GL 上下文:

#include <GL/glut.h>
#include <iostream>

int main(int argc, char **argv)
{
    // create context & make it current
    glutInit( &argc, argv );
    glutInitWindowSize( 200, 200 );
    glutInitDisplayMode( GLUT_RGBA );
    glutCreateWindow( "GLUT" );

    GLdouble mvmatrix[16];
    GLdouble projmatrix[16];
    GLint viewport[4];
    GLdouble winx;
    GLdouble winy;
    GLdouble winz;
    glGetDoublev( GL_MODELVIEW_MATRIX, mvmatrix );
    glGetDoublev( GL_PROJECTION_MATRIX, projmatrix );
    glGetIntegerv( GL_VIEWPORT, viewport );
    gluProject
        (
        0.0, 0.0, 0.0, 
        mvmatrix, projmatrix, viewport,
        &winx, &winy, &winz
        );
    std::cout << winx << " " << winy << std::endl;
    return 0;
}

输出:

100 100