【发布时间】:2018-03-09 23:28:55
【问题描述】:
我想尝试使用 OpenGL 和 GLUT 制作游戏,但事实证明,GLUT 并不适合制作游戏。所以我转而使用 SDL 1.2(这是为了某种竞争,所以我不能使用 SDL 2)。当我看到我可以在 SDL 中使用 OpenGL 时,我决定这样做,因为我已经用 OpenGL 编写了大部分代码。现在,我在尝试将图像加载到SDL_Surface 中,然后在启用 OpenGL 混合的情况下将其转换为 OpenGL 纹理时遇到问题。这是我正在使用的代码(loadImage 加载 SDL_Surface 和 loadTexture 加载到 OpenGL 纹理中):
SDL_Surface * Graphics::loadImage(const char * filename) {
SDL_Surface *loaded = nullptr;
SDL_Surface *optimized = nullptr;
loaded = IMG_Load(filename);
if (loaded) {
optimized = SDL_DisplayFormat(loaded);
SDL_FreeSurface(loaded);
}
return optimized;
}
GLuint Graphics::loadTexture(const char * filename, GLuint oldTexId) {
//return SOIL_load_OGL_texture(filename, SOIL_LOAD_AUTO, oldTexId, SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_MULTIPLY_ALPHA);
GLuint texId = 0;
SDL_Surface *s = loadImage(filename);
if (!s) return 0;
if (oldTexId) glDeleteTextures(1, &oldTexId);
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
int format;
if (s->format->BytesPerPixel == 4) {
if (s->format->Rmask == 0x000000ff)
format = GL_RGBA;
else
format = GL_BGRA;
} else if (s->format->BytesPerPixel == 3) {
if (s->format->Rmask == 0x000000ff)
format = GL_RGB;
else
format = GL_BGR;
}
glTexImage2D(GL_TEXTURE_2D, 0, s->format->BytesPerPixel, s->w, s->h, 0, format, GL_UNSIGNED_BYTE, s->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(s);
return texId;
}
我一直在网上搜索这个问题的解决方案,但我找到的解决方案都没有奏效。当我不glEnable(GL_BLEND) 时,此代码实际上有效,但是当我启用它时,它不再在屏幕上显示任何内容。我对 OpenGL 还很陌生,我不确定我是否正确使用了 glTexImage2D。
我在转换为 SDL 之前加载图像的方式是使用 SOIL 库,当我用注释掉的第一行替换 loadTexture 函数的主体时,它实际上工作正常,但我宁愿少用外部库,并使用 SDL 和 OpenGL 完成所有图形方面的工作。
【问题讨论】:
-
如果您只是将位加载到 OpenGL 纹理中,为什么还要使用
SDL_DisplayFormat()?您只需要优化表面以加速 SDL 的 blitting 系统,它与 OpenGL 无关。 -
@genpfault 当我不
SDL_DisplayFormat()表面时,format->BytesPerPixel是 1。我可能会修改我的函数以最终读取它,但现在不是,或者至少不应该't,成为一个问题