Qt之OpenGL使用Qt封装好的着色器和编译器

发布于:2025-04-16 ⋅ 阅读:(29) ⋅ 点赞:(0)

代码

#include "sunopengl.h"

sunOpengl::sunOpengl(QWidget *parent) {}



unsigned int VBO,VAO;
float vertices[]={
    0.5f,0.5f,0.0f,
    0.5f,-0.5f,0.0f,
    -0.5f,-0.5f,0.0f,
    -0.5f,0.5f,0.0f
};

unsigned int indices[]={
    0,1,3,
    1,2,3,
};
unsigned int EBO;
sunOpengl::~sunOpengl()
{
    makeCurrent();
    glDeleteVertexArrays(1,&VAO);
    glDeleteBuffers(1,&VBO);
    glDeleteBuffers(1,&EBO);
    //glDeleteProgram(shaderProgram);
    doneCurrent();
}
void sunOpengl::initializeGL()
{
    this->initializeOpenGLFunctions();
    glGenVertexArrays(1,&VAO);
    glGenBuffers(1,&VBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    //将数据传入显存
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);
    //显卡解析参数
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(float),(GLvoid*)0);
    //开始VOA属性
    glEnableVertexAttribArray(0);

    //EBO
    glGenBuffers(1,&EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);

    shaderProgram.addShaderFromSourceFile(QOpenGLShader::Vertex,":/shades/shapes.vert");
    shaderProgram.addShaderFromSourceFile(QOpenGLShader::Fragment,":/shades/shapes.frag");
    bool success=shaderProgram.link();
    if(!success)
    {
        qDebug()<<shaderProgram.log();
    }

    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER,0);
}

void sunOpengl::resizeGL(int w, int h)
{

}

void sunOpengl::paintGL()
{
     shaderProgram.bind();
     //glUseProgram(shaderProgram);
    glClearColor(0.2f,0.3f,0.3f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    if(!isDraw)
        return;
    glBindVertexArray(VAO);
   // glDrawArrays(GL_TRIANGLES,0,6);
    glDrawElements(ShapeType,6,GL_UNSIGNED_INT,0);
    glBindVertexArray(0);

}

void sunOpengl::drawrectangle()
{
    ShapeType=GL_TRIANGLES;
    isDraw=true;
    update();
}

void sunOpengl::setPloygonMode(bool isWire)
{
    makeCurrent();
    if(isWire)
    {
        glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
    }
    else
    {
        glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
    }
    doneCurrent();
    update();
}

void sunOpengl::clear()
{
    isDraw=false;
    update();
}
//定点着色器-》几何着色-》图元装配-》光栅化-》片段着色器-》测试与混合
#ifndef SUNOPENGL_H
#define SUNOPENGL_H

#include <QOpenGLWidget>
#include<QOpenGLFunctions_3_3_Core>//unction_>
#include<QOpenGLShaderProgram>
class sunOpengl : public QOpenGLWidget,QOpenGLFunctions_3_3_Core
{
public:
    explicit sunOpengl(QWidget* parent = nullptr);
    ~sunOpengl();
    virtual void initializeGL();
    virtual void resizeGL(int w, int h);
    virtual void paintGL();
    void drawrectangle();
    void clear();
    void setPloygonMode(bool isWire);
    bool isDraw;
    int ShapeType;
    QOpenGLShaderProgram shaderProgram;
};

#endif // SUNOPENGL_H

 


网站公告

今日签到

点亮在社区的每一天
去签到