glColor4f - 绘制时无法获得完全不透明度

时间:2017-12-11 19:33:39

标签: c++ opengl

我正在重写渲染器(2D游戏的一部分)以使用OpenGL而不是SDL。 我有以下代码的问题:

void renderer_opengl::draw_rectangle_filled(int x, int y, int w, int h, SDL_Color color){
    glColor4f((1.0f/255)*color.r, (1.0f/255)*color.g, (1.0f/255)*color.b, (1.0f/255)*color.a);
    glBegin(GL_POLYGON);
        glVertex2f(x, y);
        glVertex2f(x + w, y);
        glVertex2f(x + w, y + h);
        glVertex2f(x, y + h);
    glEnd();
    glColor4f(1, 1, 1, 1);
} 

(是的,我知道这已被弃用GL,让我们现在忽略它) 这将绘制一个具有给定颜色和alpha值的矩形。问题是即使设置这样的颜色:glColor4f(0, 0, 0, 1);也不会产生纯黑色,而是半透明黑色(类似于在标准SDL渲染器中将alpha设置为50%)。 / p>

我启用了这样的混合:

glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

我尝试了glBlendFunc的不同参数,但没有解决问题。我永远无法获得纯色。矩形绘制在已经渲染到屏幕的纹理上。 (这些矩形应为黑色,大约70%的alpha - 非常暗,但仍然透明)。谢谢你的帮助。

std::unordered_map SDL_Surface*

加载纹理的代码
void renderer_opengl::upload_surfaces(std::unordered_map<int, SDL_Surface*>* surfaces){
    for ( auto it = surfaces->begin(); it != surfaces->end(); ++it ){
        if(it->second != NULL && textures[it->first] == NULL){
            glEnable(GL_TEXTURE_2D);
            GLuint TextureID = new_texture_id();
            glGenTextures(1, &TextureID);
            glBindTexture(GL_TEXTURE_2D, TextureID);
            int Mode = GL_RGB;
            if(it->second->format->BytesPerPixel == 4) {
                Mode = GL_RGBA;
            }
            glTexImage2D(GL_TEXTURE_2D, 0, Mode, it->second->w, it->second->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, it->second->pixels);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            textures[it->first] = new texture(TextureID, Mode, it->second->w, it->second->h); //texture is just a struct that holds the GLuint, the Mode, width and height


       }
   }
}

绘制纹理的函数:

void renderer_opengl::draw_texture(int arg, int x, int y){
    texture* Texture = textures[arg];
    glBindTexture(GL_TEXTURE_2D, Texture->TextureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   int Width = Texture->width;
   int Height = Texture->height;
   int X = x;
   int Y = y - Height;
   glBegin(GL_QUADS);
        glTexCoord2f(0, 1); glVertex3f(X, Y+ Height, 0);
        glTexCoord2f(1, 1); glVertex3f(X + Width, Y + Height, 0);
        glTexCoord2f(1, 0); glVertex3f(X + Width, Y , 0);
        glTexCoord2f(0, 0); glVertex3f(X, Y , 0);
    glEnd();
}

我在初始化代码中做了什么,没有设置视口,宽高比等。

glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

整个渲染操作如下:

1

glClearColor(0.0,0.0,0.0,0.0); //Screen is cleared
glClear( GL_COLOR_BUFFER_BIT );
  1. 致电draw_texturedraw_rectangle_filled

  2. SDL_GL_SwapWindow(window);然后显示所有内容

1 个答案:

答案 0 :(得分:0)

我在绘制矩形之前调用glDisable(GL_TEXTURE_2D);解决了这个问题。我猜仍然有一个纹理绑定到OpenGl上下文,这导致了问题。现在一切都很完美。

相关问题