Opengl渲染到纹理,但纹理为null

时间:2017-10-24 15:14:25

标签: c++ opengl textures

我正在尝试渲染到纹理,然后将其渲染到正方形上。但结果是一个粉红色的方块。

我创建了纹理,帧缓冲等等。

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;
}

编译时我没有任何错误...

有什么我想念的吗? 有人知道如何解决它吗?

非常感谢。

1 个答案:

答案 0 :(得分:-1)

问题出在这里

texture renderTexture = texture();

您错过了new关键字。这样可以防止纹理构造函数被调用,这似乎是在执行纹理生成。

替换为

texture* renderTexture = new texture();