c++ - 移植到 Qt5 后 OpenGL 应用程序看起来很奇怪

标签 c++ qt opengl qt5 qglwidget

我最近将我的引擎从 QGLWidget 移植到了 QWindow。一切都很好,除了纹理。它们看起来有很多洞,又黑又奇怪。

举例说明我的意思: (损坏的构建(QWindow)) Broken build (QWindow)

第二个例子:(工作构建 QGLWidget): Working build QGLWidget

为了设置纹理,我使用了QOpenGLTexture。它显示 glTextureView 无法解析的警告,但仍然有效。在 QGLWidget 版本中,我使用了 QGLWidget::convertToGLFormat,以及一些原始的 OpenGL 调用。

QGLWidget版本代码:

if(!mProgram.isLinked())
{
    qCritical() << tr("Error: the shader program is not linked, object name: %1").arg(mName);
    return false;
}

if(mTextureID != 0)
{
    qCritical() << tr("Error: texture already set, object name: %1").arg(mName);
    return false;
}

QImage tex;
bool loadok = tex.load(path);
if(!loadok)
{
    qCritical() << tr("Error: failed to load the image, object name: %1").arg(mName);
    return false;
}

tex = QGLWidget::convertToGLFormat(tex);



glGenTextures(1, &mTextureID);
if(mTextureID == 0)
{
    qCritical() << tr("Error: failed to generate the texture, object name: %1").arg(mName);
    return false;
}
mVAO.bind();

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mTextureID);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.width(), tex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.constBits());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

mProgram.setUniformValue("objectTexture", 0);

mVAO.release();

return true;

QWindow 版本代码:

if(!mProgram.isLinked())
{
    qCritical() << tr("Error: the shader program is not linked, object name: %1").arg(mName);
    return false;
}

QImage img;
bool ok = img.load(path);
if(!ok)
{
    qCritical() << tr("Error: failed to load the image, object name: %1").arg(mName);
    return ok;
}

ok = mTexture.create();

qDebug() << img.size();

if(!ok)
{
    qCritical() << tr("Error: create the texture, object name: %1").arg(mName);
    return ok;
}


mTexture.setFormat(QOpenGLTexture::RGBA8_UNorm);
mTexture.setData(img);

QOpenGLVertexArrayObject::Binder vaoBinder(&mVAO);
glActiveTexture(GL_TEXTURE0);
mTexture.bind();

mProgram.setUniformValue("objectTexture", 0);


return ok;

知道是什么原因造成的吗?

最佳答案

我想通了!!!使用 QGLWidget::convertToGLFormat 为我翻转了 Y 轴上的纹理。 QOpenGLTexture 不会那样做。所以着色器中的一条简单的线解决了这个问题。

varying highp vec2 outUV;
uniform sampler2D objectTexture;
void main()
{
    vec2 flipped_texcoord = vec2(outUV.x, 1.0 - outUV.y);
    gl_FragColor = texture2D(objectTexture, flipped_texcoord);
}

或者我可以只使用 img = img.mirrored(); 在 C++ 中做到这一点。

关于c++ - 移植到 Qt5 后 OpenGL 应用程序看起来很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24853789/

相关文章:

c++ - 为QScrollArea预留空间

opengl - 将整数纹理附加到帧缓冲区

c++ - 数组内存地址总是按从小到大的顺序排列吗?

c++ - 我应该在包含虚方法的类上使用 'memcpy' 吗?如果不是,如何替换它?

c++ - 如何在 qt 标签中显示 em dash 字符?

c++ - Qt 多线程信号和槽行为的问题

c++ - 投影和 View 矩阵

linux - OpenGL glutSwapBuffers 不绘制场景

c++ - 在 C++ 的析构函数中调用 delete[]

c++ - 从/dev/urandom 获取一个 float