【发布时间】:2017-12-11 19:33:39
【问题描述】:
我正在重写渲染器(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%)。
我已经启用了这样的混合:
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 );
拨打
draw_texture和draw_rectangle_filledSDL_GL_SwapWindow(window);然后一切都显示出来了
【问题讨论】:
-
glColor4f(1, 1, 1, 1);不应该是纯黑色,应该是纯白色。 -
是的,你是对的,对不起。我的意思是写
glColor4f(0, 0, 0, 1);应该是纯黑色的。我编辑了问题:) -
您需要提供Minimal, Complete, and Verifiable example。或者至少显示重现所述问题的完整帧渲染代码。这个绘图函数看起来不错,但谁知道你之前/之后还做了什么?
-
整个渲染代码太多,这里就不贴了,但我会尽量展示加载和绘制纹理的函数,因为我认为问题出在哪里。