随手记录Qt学习开发过程中遇到的问题和解决方法
环境:Qt5.12.9 QtCreator4.12.2 MinGW7.3.0
考虑采用OpenGL固定管线绘制图像效率低下,一直想学习采用OpenGL ES的方式进行图像绘制,网上这方面的可参考资料不够丰富, 自己OpenGL的基础又十分欠缺,完全是在一步步自己摸索着学习的。建议跟我一样对OpenGL本身基础就差的同志们,先到https://learnopengl-cn.github.io/这个网站上自学一下,尤其是从“入门→你好,三角形”这部分开始,讲得真的非常清楚,一定要耐心学习。
不废话了,下面就进入正题,把我实现彩色立方体的程序记录一下。
1、首先贴上glsl代码
先是顶点着色器的部分,后是片段着色器的部分。
const char *vshader_code =
"uniform mat4 mvp_matrix; \n"
"attribute vec4 vPosition; \n"
"attribute vec3 aColor; \n"
"varying vec3 vColor; \n"
"void main() \n"
"{ \n"
" gl_Position = mvp_matrix * vPosition; \n"
" vColor = aColor; \n"
"} \n";
const char *fshader_code =
"varying vec3 vColor; \n"
"void main() \n"
"{ \n"
" gl_FragColor = vec4(vColor,1.0f); \n"
"}
因为这部分代码量太小了,所以没有单独存成glsl文件。这部分内容就不做详细介绍了,不清楚的浏览我上面写的网站进行学习。
2、彩色立方体定义部分代码
#include "cubegeometry.h"
CubeGeometry::CubeGeometry():QOpenGLFunctions()
, indexBuf(QOpenGLBuffer::IndexBuffer)
{
initializeOpenGLFunctions();
this->arrayBuf.create();
this->indexBuf.create();
initCubeGeometry();
}
CubeGeometry::~CubeGeometry()
{
this->arrayBuf.destroy();
this->indexBuf.destroy();
}
void CubeGeometry::drawCubeGeometry(QOpenGLShaderProgram *program)
{
this->arrayBuf.bind();
this->indexBuf.bind();
quintptr offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
int vPos = program->attributeLocation("vPosition");
program->enableAttributeArray(vPos);
program->setAttributeBuffer(vPos, GL_FLOAT, offset, 3, sizeof(VertexData));
// Offset for texture coordinate
offset += sizeof(QVector3D);
// Tell OpenGL programmable pipeline how to locate vertex texture coordinate data
int aColor = program->attributeLocation("aColor");
program->enableAttributeArray(aColor);
program->setAttributeBuffer(aColor, GL_FLOAT, offset, 3, sizeof(VertexData));
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);
}
void CubeGeometry::initCubeGeometry()
{
//一个正方体有八个顶点,分别对顶点位置和顶点颜色进行定义
VertexData vertices[] = {
{
QVector3D( 1.0f, 1.0f, 1.0f), QVector3D(1.0f, 0.0f, 0.0f)}, // v0, a-red
{
QVector3D(-1.0f, 1.0f, 1.0f), QVector3D(1.0f, 0.5f, 0.0f)}, // v1, b-orange
{
QVector3D(-1.0f, -1.0f, 1.0f), QVector3D(1.0f, 1.0f, 0.0f)}, // v2, c-yellow
{
QVector3D( 1.0f, -1.0f, 1.0f), QVector3D(0.0f, 1.0f, 0.0f)}, // v3, d-green
{
QVector3D( 1.0f, 1.0f, -1.0f), QVector3D(0.0f, 1.0f, 1.0f)}, // v4, e-sky
{
QVector3D(-1.0f, 1.0f, -1.0f), QVector3D(0.0f, 0.0f, 1.0f)}, // v5, f-blue
{
QVector3D(-1.0f, -1.0f, -1.0f), QVector3D(0.5f, 0.0f, 1.0f)}, // v6, g-purple
{
QVector3D(<