向量、矩阵及线性变换的代码实现
OpenGL没有自带任何的矩阵和向量知识,所以我们必须定义自己的数学类和函数。所幸的是,QT为我们封装了相关的线性代数的库,我们可以方便地进行线性代数计算。下面我们直接演示一个例子。
首先修改顶点着色器的代码,对顶点进行旋转:
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
out vec3 ourColor;
out vec2 TexCoord;
uniform mat4 theMatrixl;
void main()
{
gl_Position = theMatrixl * vec4(aPos, 1.0);
ourColor = aColor;
TexCoord = aTexCoord;
}
设置偏移和旋转量,并输入到着色器:
void ZjjOpenGLWidget::paintGL()
{
......
shaderProgram.bind();
QMatrix4x4 matrix;
unsigned int time = QTime::currentTime().msec();
matrix.translate(0.3f, -0.3f, 0);
matrix.rotate(time, 0.0f, 0.0f, 1.0f);
......
switch (m_shape) {
case Rect:
{
// textureWall->bind(0);
// textureSmile->bind(1);
textureNose->bind(2);
shaderProgram.setUniformValue("theMatrixl", matrix);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
......
}
为了让图像实时地更新,我们设置一个QTimer
对象用于触发更新绘制:
class ZjjOpenGLWidget : public QOpenGLWidget,QOpenGLFunctions_4_5_Core
{
......
protected:
......
QTimer timer;
signals:
public slots:
void on_timeout();
};
在构造函数处配置触发机制:
ZjjOpenGLWidget::ZjjOpenGLWidget(QWidget *parent) : QOpenGLWidget(parent)
{
setFocusPolicy(Qt::StrongFocus);
connect(&timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
timer.start(200);
}
void ZjjOpenGLWidget::on_timeout()
{
update();
}
运行结果: