【发布时间】:2017-10-24 15:14:24
【问题描述】:
我正在尝试渲染到纹理,然后将其渲染到正方形上。但结果是一个粉红色的正方形。
我创建纹理、帧缓冲区等
texture renderTexture = texture();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1000, 600, 0, GL_BGRA, GL_UNSIGNED_BYTE, 0);
unsigned int fb;
glGenFramebuffers(1, &fb);
glBindRenderbuffer(GL_RENDERBUFFER, fb);
glFramebufferTexture2D(GL_RENDERBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture.getId(), 0);
然后在游戏循环中我称之为:
show(fb);
showMenu(renderTexture.getId());
void game::show(unsigned int fb){
glBindFramebuffer(GL_FRAMEBUFFER, fb);
glViewport(0, 0, 1000, 600);
glClearColor(0.5, 0.5, 0.5, 1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -7.0f);
glBegin(GL_QUADS);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glEnd();
// Render a pyramid consists of 4 triangles
glLoadIdentity(); // Reset the model-view matrix
glTranslatef(-1.5f, 0.0f, -6.0f); // Move left and into the screen
}
void game::showMenu(unsigned int renderTexture){
bindWindowAsRenderTarget();
glViewport(0, 0, 1000, 600);
glClearColor(0.5, 0.5, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glOrtho(0.0, 1000.0, 0.0, 600.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBindTexture(GL_TEXTURE_2D, renderTexture);
glTranslatef(0.0,0.0,-5.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0,2.0);
glVertex3f(-2.0,2.0,0.0);
glTexCoord2f(0.0,0.0);
glVertex3f(-2.0,-2.0,0.0);
glTexCoord2f(2.0,0.0);
glVertex3f(2.0,-2.0,0.0);
glTexCoord2f(2.0,2.0);
glVertex3f(2.0,2.0,0.0);
glEnd();
glLoadIdentity();
}
void game::bindWindowAsRenderTarget(){
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, 1000, 600);
}
这是纹理类:
#include "texture.h"
texture::texture(){
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
}
texture::~texture(){
glDeleteTextures(1, &id);
}
void texture::loadImage(const char* filename){
SDL_Surface* img = SDL_LoadBMP(filename);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img->w, img->h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, img->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(img);
}
unsigned int texture::getId(){
return id;
}
我在编译时没有任何错误...
我有什么遗漏吗? 有人知道怎么解决吗?
非常感谢。
【问题讨论】:
-
texture renderTexture = texture()看起来很不对劲。如果您希望它存在于堆上,那么它应该是texture renderTexture();。但我想主要的问题是纹理在你尝试使用它之前就超出了范围。