#include "GLWidget.h"
#include <QtGui/QMouseEvent>
GLWidget::GLWidget() : numVertices_(-1)
{
resize(640, 480);
maxVertices_ = 12;
// calculate the size per vertex and per index pair
bufferParams_.vCompSize = 4 * sizeof(GLfloat);
bufferParams_.iCompSize = 2 * sizeof(GLubyte);
// calculate buffer size
bufferParams_.vBufSize = maxVertices_ * bufferParams_.vCompSize;
bufferParams_.iBufSize = maxVertices_ * bufferParams_.iCompSize;
// our current example will use indices in the range [0, 1, .., 255]
bufferParams_.indexType = GL_UNSIGNED_BYTE;
}
GLWidget::~GLWidget()
{
glDeleteBuffers(2, bufferParams_.buffers);
}
void GLWidget::initializeGL()
{
// you can ignore this one
glewInit();
// init GL state
glClearColor(1.f, 1.f, 1.f, 1.f);
glLineWidth(2.f);
// init matrices
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 640, 0, 480, 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -4.f);
// init vertex color attribute
glColor3f(0.f, 0.f, 0.f);
// init vertex and index buffer
initBuffers();
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
// only issue a draw call if we got at least 2 vertices
if(numVertices_ > 0)
{
glDrawElements(GL_LINES, 2 * numVertices_, bufferParams_.indexType, NULL);
}
}
void GLWidget::resizeGL(int width, int height)
{
glViewport(0, 0, width, height);
}
void GLWidget::mousePressEvent(QMouseEvent* evt)
{
if(numVertices_ < 11)
{
++numVertices_;
float x = static_cast<float>(evt->x());
float y = static_cast<float>(height() - evt->y());
float coords[4] = {x, y, 0.f, 1.f};
updateBuffers(coords);
}
}
void GLWidget::initBuffers()
{
glGenBuffers(2, bufferParams_.buffers);
glBindBuffer(GL_ARRAY_BUFFER, bufferParams_.buffers[0]);
glBufferData(GL_ARRAY_BUFFER, bufferParams_.vBufSize, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferParams_.buffers[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferParams_.iBufSize, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
}
void GLWidget::updateBuffers(const float* coords)
{
GLintptr vertexOffset = (numVertices_) * bufferParams_.vCompSize;
glBufferSubData(GL_ARRAY_BUFFER, vertexOffset, bufferParams_.vCompSize, coords);
// we always want to add pairs of indices to the index buffer, so only do this
// if we have at least 2 vertices in the vertex buffer
if(numVertices_ > 0)
{
GLintptr indexOffset = (numVertices_ - 1) * bufferParams_.iCompSize;
GLubyte indices[] = {numVertices_ - 1, numVertices_};
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, indexOffset, sizeof(indices), indices);
}
}