【发布时间】:2018-06-28 19:49:26
【问题描述】:
我正在使用 QT QOpenGLWidget,我想将鼠标点击位置取消投影回 3D,所以我使用了 glReadPixels。 (我还阅读了Pangolin的源代码,一个非常好的旋转、平移、缩放示例,它也使用了glReadPixels)
这是我的简单代码的一部分:
void myGLWidget::initializeGL()
{
glClearColor(0.2, 0.2, 0.2, 1.0); //background color
glClearDepthf(1.0); //set depth test
glEnable(GL_DEPTH_TEST); //enable depth test
}
void myGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear color and depth buffer
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(cameraView_.data()); // cameraView_ is a QMatrix4x4
drawingTeapot();
// reading pixels in paintGL works well!!! returns lots of 1s
GLfloat zs[10 * 10];
glReadPixels(0, 0, 10, 10, GL_DEPTH_COMPONENT, GL_FLOAT, &zs);
}
void myGLWidget::mousePressEvent(QMouseEvent *event)
{
// glReadBuffer(GL_FRONT); // also tried this, nothing works
GLfloat zs[10 * 10];
glReadPixels(0, 0, 10, 10, GL_DEPTH_COMPONENT, GL_FLOAT, &zs);
GLenum e = glGetError(); // this gives 1282 err code!!!
}
我正在使用 macOS Sierra,Pangolin 在我的笔记本电脑上完美运行,但是,我的 qt 项目可以运行??!!
说不工作,我的意思是输出变量 zs 仍然是随机值,例如 0 和 123123e-315,并且它在 glReadPixels 之前和之后永远不会改变。
为什么 glReadPixels 只适用于 PaintGL 函数?
我也试过python版本,它给我一个错误说:
File "errorchecker.pyx", line 53, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError (src/errorchecker.c:1218)
OpenGL.error.GLError: GLError(
err = 1282,
description = b'invalid operation',
baseOperation = glReadPixels,
可能是这样的:
GL_INVALID_OPERATION is generated if format is GL_DEPTH_COMPONENT and there is no depth buffer.来自document的参考
但我还是不知道该怎么办
【问题讨论】:
-
在您的绘制函数中,上下文处于活动状态。这由 Qt 为您处理。在其他地方,您需要手动激活 OpenGL 上下文。
-
@craig-zhang,@DietrichEpp 是正确的,您可以尝试将上下文设为最新,看看它是否有效?在
mousePressEvent()方法的开头尝试makeCurrent();。 -
谢谢!!! @DietrichEpp 和 Harish!,它现在可以工作了