OpenGL纹理2D绘制纯色但不会绘制图像

时间:2016-05-12 04:35:16

标签: opengl-es opengl-es-2.0 sdl-2

我尝试使用SDL和OpenGL在屏幕上绘制图像。我尝试将图像(像素数据)加载到GL_TEXTURE_2D并绘制它。但是,从不绘制图像。绘制纹理的形状和大小,但是我的片段着色器颜色设置为纯色。但图像永远不会出现。我一遍又一遍地检查我的代码,找不到任何原因导致它无法正常工作。此外,glGetError()不会返回任何错误。如果有人帮我找到我做错了什么,我会非常感激!

这是我在设置SDL窗口后用于设置GL的代码:

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

context = SDL_GL_CreateContext(window);

glViewport(0, 0, screenWidth, screenHeight);

glClearColor(0, 0, 0, 1);

GLuint vertexShader = loadShader(vshPath, GL_VERTEX_SHADER);
GLuint fragmentShader = loadShader(fshPath, GL_FRAGMENT_SHADER);

glProgram = glCreateProgram();
glAttachShader(glProgram, vertexShader);
glAttachShader(glProgram, fragmentShader);
glLinkProgram(glProgram);
glUseProgram(glProgram);

glEnableVertexAttribArray(position);

glEnable(GL_TEXTURE_2D);
glGenTextures(1, textureID);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, screenWidth, screenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glDisable(GL_TEXTURE_2D);

这是我用来在屏幕上绘制图像的代码:

glClear(GL_COLOR_BUFFER_BIT);

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glActiveTexture(GL_TEXTURE0);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, screenWidth, screenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

float vertices[] = {
    -1.0f, -1.0f,  0.0f,
    -1.0f,  1.0f,  0.0f,
     1.0f, -1.0f,  0.0f,
     1.0f,  1.0f,  0.0f
};

glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, vertices);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

SDL_GL_SwapWindow(window);

我的片段着色器:

precision mediump float; 
void main() { 
    gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}

我的顶点着色器:

varying vec4;
attribute vec4 position; 
void main() { 
    gl_Position = position; 
}

0 个答案:

没有答案