当对象放入容器类中时,OpenGL 不会绘制

OpenGL doesn't draw when objects are put in a container class

本文关键字:OpenGL 绘制 对象 容器类      更新时间:2023-10-16

我正在尝试创建一个类来描述我尝试呈现到屏幕上的特定对象。 我有一个着色器、网格和纹理对象,我一直在 main() 中运行,工作正常。 它现在所做的只是将图像绘制到屏幕上。

但是,当我将这些对象放在名为 Entity 的类中并尝试使用它进行渲染时,它不会绘制图像。

主代码:

int main(int argc, char*argv[]) {
    Display display;
    display.init();  //Sets up SDL and glew
    Shaders shaders("basicShader");
    Mesh mesh(shaders.getProgram());    
    Texture texture("kitten.png");
    Entity entity;

    //Loop stuff
    bool quit = false;
    SDL_Event e;
    double frameCounter = 0;
    double time = SDL_GetTicks();
    while (!quit) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                quit = true;
            }
            if (e.type == SDL_KEYDOWN) {
                if (e.key.keysym.sym == SDLK_ESCAPE)
                    quit = true;
            }
        }
        ++frameCounter;
        if (SDL_GetTicks() - time >= 500) {
            std::cout << "FPS: " << frameCounter / ((SDL_GetTicks() - time) / 1000) << std::endl;
            frameCounter = 0;
            time = SDL_GetTicks();
        }
        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        mesh.draw();
        //entity.render();
        // Swap buffers
        display.render();
    }
    mesh.~Mesh();
    entity.~Entity();
    display.~Display();
    return 0;
}

实体标头:

#pragma once
#include "Mesh.h"
#include "Shaders.h"
#include "Texture.h"
class Entity
{
public:
    Entity();
    void render();
    ~Entity();
private:
    Mesh mesh;
    Shaders shaders;
    Texture texture;
};

实体类代码:

#include "Entity.h"

Entity::Entity() {
    shaders = Shaders("basicShader");
    mesh = Mesh(shaders.getProgram());
    texture = Texture("kitten.png");
}
void Entity::render() {
    mesh.draw();
}
Entity::~Entity() {
    mesh.~Mesh();
}

当 mesh.draw() 未注释且 entity.render() 在 main() 中注释时,此代码有效,但反之则不然。如有必要,我可以从标头和其他类中发布代码。

Reto Koradi 对另一个问题的回答的链接有助于解决这个问题:使用默认构造函数调用的网格类不起作用 OpenGL C++

为了解决这个问题,我将对象声明为类 Entity 中的指针,并像这样初始化:

实体标头:

#pragma once
#include "Mesh.h"
#include "Shaders.h"
#include "Texture.h"
class Entity
{
public:
    Entity();
    void render();
    ~Entity();
private:
    Mesh* mesh;
    Shaders* shaders;
    Texture* texture;
};

实体构造函数:

Entity::Entity() {
    shaders = new Shaders("basicShader");
    mesh = new Mesh(shaders->getProgram());
    texture = new Texture("kitten.png");
}