开发者

Pass a Qt QImage to a glsl texture sampler

开发者 https://www.devze.com 2023-03-28 00:17 出处:网络
I am writing a rendering engine using Qt and am running into problems with texturing my models I have a very simple shader to test texturing:

I am writing a rendering engine using Qt and am running into problems with texturing my models

I have a very simple shader to test texturing: vertex shader:

Attribute vec4 Vertex; 
Attribute vec2 texcoords;   
uniform mat4 mvp;   
varying vec2 outTexture;   

void main() {     
  gl_Position = mvp * Vertex;     
  outTexture = texcoords; 
} 

and fragment shader:

uniform sampler2D tex;   
varying vec2 outTexture;
void main() {
  vec4 color = texture2D(tex, outTexture);
  gl_FragColor = color; 
} 

I am passing my texture coordinates to the shaders correctly My problem is with binding a QImage and sending it to its texture uniform.

I am using the following code to bind the texture:

const QString& filename; 
GLuint m_texture;
QImage image(filename);
image = image.convertToFormat(QImage::Format_ARGB32);
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.width(), image.height(), 0, GL_BGRA, GL_UNSIGNED_BYTE, image.bits());
glGenerateMipmap(GL_TEXTURE2D);
glEnable(GL_TEXTURE_2D); 

The shader works and I can pass a uniform to the matrix and attributes to the vertex and texture coordinates, but when I try to send a uniform to the texture t开发者_如何转开发he same way as such:

effect->setUniformValue(effect->uniformLocation("tex", texture->m_texture)); 

the program crashes with an “access violation reading location” error with glGetError() returning “invalid enumerant”

Interestingly, when I try running the program without attempting to send the texture to the sampler, the texture is actually appearing on the model. Which makes me think the way I’m binding it has something to do with the legacy texture handling and the texture is being bound to a particular texture address which is being picked up by the shader. This is not the effect I want because I want the programmer to be able to explicitly state at draw time what texture should be passed to the uniform (just as any other uniform is set)

How can I pass the texture to it’s sampler, what do I need to change when binding a texture?


Change it to

effect->setUniformValue(effect->uniformLocation("tex"), texture->m_texture);

or

effect->setUniformValue("tex", texture->m_texture); 


Try converting the QImage using:

image = QGLWidget::convertToGLFormat(image);

Another thought, if you are using ES2, then GL_RGBA8 is not valid. I think GL_BGRA may be an optional extension, or not ES 2. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号