#include "cameraglwidget.h"
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QPainter>
#include<QImageReader.h>
struct VertexData
{
QVector2D position;
QVector2D texCoord;
};
CameraGLWidget::CameraGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
}
CameraGLWidget::~CameraGLWidget()
{
arrayBuf.destroy();
}
void CameraGLWidget::resizeGL(int w, int h)
{
glViewport(0,0,w,h);
}
void CameraGLWidget::paintGL()
{
// Clear color and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_texture->bind();
// Use texture unit 0 which contains cube.png
m_program->setUniformValue(m_textureUniform, 0);
// Draw cube geometry using indices from VBO 1
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
void CameraGLWidget::initializeGL()
{
initializeOpenGLFunctions();
initShaders();
initTextures();
initBuffArray();
}
void CameraGLWidget::initShaders()
{
//Create QOpenGLShaderProgram
m_program = new QOpenGLShaderProgram;
// Compile vertex shader
m_program->addShaderFromSourceFile(QOpenGLShader::Vertex,"GLSL/vshader.glsl");
// Compile fragment shader
m_program->addShaderFromSourceFile(QOpenGLShader::Fragment,"GLSL/fshader.glsl");
// Link shader pipeline
m_program->link();
// Bind shader pipeline for use
m_program->bind();
//Get identifer of Attribute or uniform value in vshader.glsl and fshader.glsl
m_vertexAttr = m_program->attributeLocation("vertexIn");
m_textureAttr = m_program->attributeLocation("textureIn");
m_textureUniform = m_program->uniformLocation("texture");
}
void CameraGLWidget::initTextures()
{
// Load image
m_texture = new QOpenGLTexture(QImage("./S40_duplicate.png").mirrored());
// Set nearest filtering mode for texture minification
m_texture->setMinificationFilter(QOpenGLTexture::Nearest);
// Set bilinear filtering mode for texture magnification
m_texture->setMagnificationFilter(QOpenGLTexture::Linear);
// Wrap texture coordinates by repeating
// f.ex. texture coordinate (1.1, 1.2) is same as (0.1, 0.2)
m_texture->setWrapMode(QOpenGLTexture::Repeat);
}
void CameraGLWidget:: initBuffArray()
{
// Vertex data and texture data
VertexData vertices[] = {
{QVector2D(-1.0f, -1.0f), QVector2D(0.0f, 0.0f)}, // v0
{QVector2D( 1.0f, -1.0f), QVector2D(1.0f, 0.0f)}, // v1
{QVector2D(-1.0f, 1.0f), QVector2D(0.0f, 1.0f)}, //v2
{QVector2D( 1.0f, 1.0f), QVector2D(1.0f, 1.0f)} // v3
};
arrayBuf.create();
arrayBuf.bind();
arrayBuf.allocate(vertices, 4 * sizeof(VertexData));
// Offset for position
quintptr offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
m_program->enableAttributeArray(m_vertexAttr);
m_program->setAttributeBuffer(m_vertexAttr, GL_FLOAT, offset, 2, sizeof(VertexData));
// Offset for texture coordinate
offset += sizeof(QVector2D);
// Tell OpenGL programmable pipeline how to locate vertex texture coordinate data
m_program->enableAttributeArray(m_textureAttr);
m_program->setAttributeBuffer(m_textureAttr, GL_FLOAT, offset, 2, sizeof(VertexData));
}