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

glColor4f - Cannot get full opacity when drawing

本文关键字:不透明度 绘制 glcolor4f-      更新时间:2023-10-16

我正在重写渲染器(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,让我们现在就忽略它)这绘制了带有给定颜色和α值的矩形。问题是,即使设置这样的颜色:glColor4f(0, 0, 0, 1);不会导致纯黑色,而是半透明的黑色(类似于将alpha设置为标准SDL渲染器中的50%)。

我启用了这样的混合:

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

我尝试了glBlendFunc的不同参数,但没有解决该问题。我永远无法获得纯色。矩形是在已经呈现到屏幕上的纹理上的。(这些矩形应为黑色,α大约70% - 太黑了,但仍然透明)。感谢您的任何帮助。

代码从SDL_Surface*std::unordered_map加载纹理

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);,然后显示一切

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