How to draw a 3d square in Qt?

67 views Asked by At

I've been trying to draw a simple 3d square but I'm getting nothing. From my understanding I'm setting it up correctly. There's a context, vao and vbo with vertex data allocated to it, and the shader is properly linked. My guess is that I'm messing up putting the data into the vbo somehow or, the view in 3d space is messed up. From the examples I've seen, many don't use the mvp matrix which is a little confusing to me.

//vertex shader
#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;

out vec4 f_color;

void main()
{
    gl_Position = position;
   f_color = color;
};

...................................

//fragment shader
in vec4 f_color;
out vec4 outputColor;

void main()
{
    outputColor = vec4(0.5, 0.5, 0, .5);
};

These are the shaders I use, the color is just something random to see.

GLfloat cube[] = {
         //pos                          color
         -0.5f, -0.5f, -1.0f, 1.0f,     1.0f, 0.0f, 0.5f, 0.5f,
          0.5f, -0.5f, -1.0f, 1.0f,     1.0f, 1.0f, 0.5f, 0.5f,
          0.5f,  0.5f, -1.0f, 1.0f,     1.0f, 0.5f, 0.5f, 0.5f,
         -0.5f,  0.5f, -1.0f, 1.0f,     0.0f, 0.5f, 0.5f, 0.5f,
    };

void MyOpenGLWidget::paintGL(){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    m_program->bind();
    m_program->enableAttributeArray(attributePos);
    m_program->enableAttributeArray(attributeColor);

    m_vao.bind();
    glDrawArrays(GL_LINES, 0, 4);
    m_vao.release();
    m_program->release();
}


void MyOpenGLWidget::initializeGL()
{
    initializeOpenGLFunctions();
    glClearColor(1, 1, 1, 0.5);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);

    m_vao.create();
    if (m_vao.isCreated())
        m_vao.bind();

    m_vbo.create();
    m_vbo.bind();
    m_vbo.setUsagePattern(QOpenGLBuffer::StreamDraw);
    m_vbo.allocate(sizeof(cube));

//...... setup m_program (QOpenGLShaderProgram) .....

    attributePos = m_program->attributeLocation("position");
    attributeColor = m_program->attributeLocation("color");

    int stride = 8 * sizeof(GLfloat);
    m_program->enableAttributeArray(attributePos);
    m_program->setAttributeBuffer(attributePos, GL_FLOAT, 0, 4, stride);

    m_program->enableAttributeArray(attributeColor);
    m_program->setAttributeBuffer(attributeColor, GL_FLOAT, 4 * sizeof(GLfloat), 4, stride);

    m_vbo.release();
    m_program->release();
    m_vao.release();
}


void MyOpenGLWidget::resizeGL(int w, int h){
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
}

I'm having trouble finding what I'm doing wrong. From my understanding I'm inputing the vbo's correctly and if the coordinate systems origin is in the center, the -1 z value of the cube should put the cube into perspective.

0

There are 0 answers