美文网首页
QOpenGLWidget 显示点云,含旋转,平移,缩放

QOpenGLWidget 显示点云,含旋转,平移,缩放

作者: 寽虎非虫003 | 来源:发表于2022-07-06 10:01 被阅读0次

    参考

    QOpenGLWidget 显示点云

    实现

    实现上面比较简略,最好参考上一篇进行修改使用。
    着色器代码shaderSrc.cpp.in

    // 单个点的数据为“xyzbgr”,前半段是坐标,后半段是颜色
    static const char *vertexShaderSourceCore =
        "#version 460\n"
        "layout(location = 0) in vec3 aPos;\n" //输入坐标
        //"in vec4 vertex;\n"
        "layout(location = 1) in vec3 aColor;\n" //输入颜色
        // "in vec3 normal;\n"
        "out vec3 color;\n"
        // "out vec3 vert;\n"
        // "out vec3 vertNormal;\n"
        "uniform mat4 projMatrix;\n"//投影矩阵
        "uniform mat4 mvMatrix;\n"//相机和世界坐标点的转换矩阵
        "uniform vec4 transpose;\n"//最后还需要平移的坐标值
        // "uniform mat3 normalMatrix;\n"
        "void main() {\n"
        // "   vert = vertex.xyz;\n"
        // "   vertNormal = normalMatrix * normal;\n"
        "   gl_Position = projMatrix * mvMatrix * vec4(aPos,1.0) + transpose;\n"//把坐标转换成齐次坐标,再做转换
        // "   gl_Position = vec4(aPos,1.0);\n"//把坐标转换成齐次坐标,再做转换
        // "   gl_PointSize = (gl_Position.z +10.0f);\n"//点大小
        "   gl_PointSize = 10.f;\n"//点大小
        "   color = aColor.zyx;\n"//把颜色从bgr转到rgb
        "}\n";
    
    static const char *fragmentShaderSourceCore =
        "#version 460\n"
        // "in highp vec3 vert;\n"
        "in highp vec3 color;\n" //输入颜色
        // "in highp vec3 vertNormal;\n"
        "out highp vec4 fragColor;\n" //渲染颜色
        // "uniform highp vec3 lightPos;\n"//相机位置
        "void main() {\n"
        // "   highp vec3 L = normalize(lightPos - vert);\n"
        // "   highp float NL = max(dot(normalize(vertNormal), L), 0.0);\n"
        // "   highp vec3 color = vec3(0.39, 1.0, 0.0);\n"
        // "   highp vec3 col = clamp(color * 0.2 + color * 0.8 * NL, 0.0, 1.0);\n"
        "   fragColor = vec4(color, 1.0);\n"
        "}\n";
    
    

    头文件cloudUI.h修改为

    #pragma once
    
    #include <QWidget>
    #include <QOpenGLWidget>
    #include <QOpenGLFunctions>
    #include <QOpenGLVertexArrayObject>
    #include <QOpenGLBuffer>
    #include <QMatrix4x4>
    
    QT_FORWARD_DECLARE_CLASS(QOpenGLShaderProgram)
    
    class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions
    {
        Q_OBJECT
    
    public:
        GLWidget(QWidget *parent = nullptr);
        ~GLWidget();
    
        static bool isTransparent() { return m_transparent; }
        static void setTransparent(bool t) { m_transparent = t; }
    
        QSize minimumSizeHint() const override;
        QSize sizeHint() const override;
    
    public slots:
        void setXRotation(int angle);
        void setYRotation(int angle);
        void setZRotation(int angle);
        void cleanup();
    
    signals:
        // 设置绕这几个轴旋转的角度的信号
        void xRotationChanged(int angle);
        void yRotationChanged(int angle);
        void zRotationChanged(int angle);
    
    protected:
        //绘图三部曲
        void initializeGL() override;
        void paintGL() override;
        void resizeGL(int width, int height) override;
    
        void mousePressEvent(QMouseEvent *event) override;
        void mouseMoveEvent(QMouseEvent *event) override;
        void wheelEvent(QWheelEvent *envent) override;
        // void keyReleaseEvent(QKeyEvent *event) override;
    
    private:
    
        void setupVertexAttribs();
    
        bool m_core;///<???
    
        // 旋转值
        int m_xRot = 0;
        int m_yRot = 0;
        int m_zRot = 0;
    
        //平移值
        float m_xTrans = 0.0f;
        float m_yTrans = 0.0f;
        float m_zTrans = 0.0f;
    
    
        float m_scale = 1.0f;///<缩放比例
        QPoint m_lastPos;
        // Logo m_logo;
        QOpenGLVertexArrayObject m_vao;
        QOpenGLBuffer m_logoVbo; //顶点缓冲对象
        QOpenGLShaderProgram *m_program = nullptr;///<着色器程序
    
        int m_aPos = 0;///<坐标的存放位置
        int m_aColor = 1;///<颜色的存放位置
    
        int m_projMatrixLoc = 0;
        int m_mvMatrixLoc = 0;
        int m_transposeLoc = 0;
        // int m_normalMatrixLoc = 0;
        int m_lightPosLoc = 0;
        QMatrix4x4 m_proj;
        QMatrix4x4 m_camera;
        QMatrix4x4 m_world;
        // QVector4D m_transpose;///<平移向量
        static bool m_transparent;
    };
    

    源文件cloudUI.cpp

    #include "cloudUI.h"
    #include <QMouseEvent>
    #include <QOpenGLShaderProgram>
    #include <QCoreApplication>
    #include <math.h>
    
    bool GLWidget::m_transparent = false;
    
    GLWidget::GLWidget(QWidget *parent)
        : QOpenGLWidget(parent)
    {
        m_core = QSurfaceFormat::defaultFormat().profile() == QSurfaceFormat::CoreProfile;
        // --transparent causes the clear color to be transparent. Therefore, on systems that
        // support it, the widget will become transparent apart from the logo.
        if (m_transparent)
        {
            QSurfaceFormat fmt = format();
            fmt.setAlphaBufferSize(8);
            setFormat(fmt);
        }
    }
    
    GLWidget::~GLWidget()
    {
        cleanup();
    }
    
    QSize GLWidget::minimumSizeHint() const
    {
        return QSize(50, 50);
    }
    
    QSize GLWidget::sizeHint() const
    {
        return QSize(400, 400);
    }
    
    static void qNormalizeAngle(int &angle)
    {
        while (angle < 0)
            angle += 360 * 16;
        while (angle > 360 * 16)
            angle -= 360 * 16;
    }
    
    void GLWidget::setXRotation(int angle)
    {
        qNormalizeAngle(angle);
        if (angle != m_xRot)
        {
            m_xRot = angle;
            emit xRotationChanged(angle);
            update();
        }
    }
    
    void GLWidget::setYRotation(int angle)
    {
        qNormalizeAngle(angle);
        if (angle != m_yRot)
        {
            m_yRot = angle;
            emit yRotationChanged(angle);
            update();
        }
    }
    
    void GLWidget::setZRotation(int angle)
    {
        qNormalizeAngle(angle);
        if (angle != m_zRot)
        {
            m_zRot = angle;
            emit zRotationChanged(angle);
            update();
        }
    }
    
    void GLWidget::cleanup()
    {
        if (m_program == nullptr)
            return;
        makeCurrent();
        m_logoVbo.destroy();
        delete m_program;
        m_program = nullptr;
        doneCurrent();
    }
    
    #include "shaderSrc.cpp.in"
    void GLWidget::initializeGL()
    {
    
        //弄来的一个三角形的顶点集
        float vertices[] = {
            -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
            0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f};
        // In this example the widget's corresponding top-level window can change
        // several times during the widget's lifetime. Whenever this happens, the
        // QOpenGLWidget's associated context is destroyed and a new one is created.
        // Therefore we have to be prepared to clean up the resources on the
        // aboutToBeDestroyed() signal, instead of the destructor. The emission of
        // the signal will be followed by an invocation of initializeGL() where we
        // can recreate all resources.
        connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::cleanup);
    
        initializeOpenGLFunctions(); //初始化一些opengl的函数
    
        glClearColor(0, 0, 0, m_transparent ? 0 : 1);
    
        //启用修改顶点着色器的顶点大小
        glEnable(GL_PROGRAM_POINT_SIZE);
    
        //创建着色器程序并设置一些属性
        m_program = new QOpenGLShaderProgram;
        //着色器程序添加顶点着色器
        m_program->addShaderFromSourceCode(
            QOpenGLShader::Vertex,
            // m_core ? vertexShaderSourceCore : vertexShaderSource);
            vertexShaderSourceCore);
        //着色器程序添加片段着色器
        m_program->addShaderFromSourceCode(
            QOpenGLShader::Fragment,
            // m_core ? fragmentShaderSourceCore : fragmentShaderSource);
            fragmentShaderSourceCore);
        //绑定 名称 到指定 位置
        // 这儿的名称是着色器代码里面给出的
        // m_program->bindAttributeLocation("vertex", 0);
        // m_program->bindAttributeLocation("normal", 1);
    
        m_program->bindAttributeLocation("aPos", 0);
        m_program->bindAttributeLocation("aColor", 1);
    
        m_program->link(); //链接
        m_program->bind(); //绑定
    
        //返回统一变量名在着色器程序参数列表中的位置。如果name不是这个着色程序的有效统一变量,返回-1。
        // 字符串里面的变量是在着色器程序里面设置的
        m_projMatrixLoc = m_program->uniformLocation("projMatrix");
        m_mvMatrixLoc = m_program->uniformLocation("mvMatrix");
        m_transposeLoc = m_program->uniformLocation("transpose");
        // m_normalMatrixLoc = m_program->uniformLocation("normalMatrix");
        m_lightPosLoc = m_program->uniformLocation("lightPos"); //打光位置还是要保留的
    
        // 创建一个顶点阵列对象。在opengles 2.0和opengl2.x实现中这是可选的,可能根本不支持。
        // 尽管如此,下面的代码在所有情况下都可以工作,并确保在需要VAO的时候有一个VAO。
        m_vao.create();
        QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
    
        // Setup our vertex buffer object.
        m_logoVbo.create();
        m_logoVbo.bind();
        // m_logoVbo.allocate(m_logo.constData(), m_logo.count() * sizeof(GLfloat));
        m_logoVbo.allocate(vertices, 18 * sizeof(GLfloat));
    
        // Store the vertex attribute bindings for the program.
        setupVertexAttribs();
    
        // Our camera never changes in this example.
        m_camera.setToIdentity();
        m_camera.translate(0, 0, -10);
        // m_camera.lookAt(QVector3D(0, 2, 0),
        //                 QVector3D(0, 0, 0),
        //                 QVector3D(0, 0, -1));
        qDebug() << "m_camera = " << m_camera;
    
        // Light position is fixed.
        m_program->setUniformValue(m_lightPosLoc, QVector3D(0, 0, 70));
    
        m_program->release();
    }
    
    void GLWidget::setupVertexAttribs()
    {
        m_logoVbo.bind();
        QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
        f->glEnableVertexAttribArray(0);
        f->glEnableVertexAttribArray(1);
        f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
                                 nullptr);
        f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
                                 reinterpret_cast<void *>(3 * sizeof(GLfloat)));
        m_logoVbo.release();
    }
    
    void GLWidget::paintGL()
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_CULL_FACE);
    
        // 旋转
        m_world.setToIdentity();
        // m_world.rotate(180.0f - (m_xRot / 16.0f), 1, 0, 0);
        m_world.rotate(m_xRot / 16.0f, 1, 0, 0);
        m_world.rotate(m_yRot / 16.0f, 0, 1, 0);
        m_world.rotate(m_zRot / 16.0f, 0, 0, 1);
    
        //平移,直接平移坐标或者直接平移相机都容易有问题,尤其是相机,容易失控
        // 因此,还是保留相机不变,然后使用直接平移向量相加的方式进行平移
        m_world.scale(m_zTrans/ 16.0f);
        // m_world.translate(m_xTrans / 16.0f, m_yTrans / 16.0f, m_zTrans / 16.0f);
        // m_world.translate(0.0f, 0.0f, m_zTrans / 16.0f);
        // m_camera.translate(0.0f, 0.0f, m_zTrans / 16.0f);
    
        qDebug() << "m_world = " << m_world;
        qDebug() << "m_camera = " << m_camera;
        QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
        m_program->bind();
        // 把着色器程序需要使用的全局变量设置进着色器程序
        m_program->setUniformValue(m_projMatrixLoc, m_proj);
        m_program->setUniformValue(m_mvMatrixLoc, m_camera * m_world);
        m_program->setUniformValue(m_transposeLoc,
                                   QVector4D(m_xTrans / 128.0f, m_yTrans / 128.0f, 0.0f, 1.0f));
        // QMatrix3x3 normalMatrix = m_world.normalMatrix();
        // m_program->setUniformValue(m_normalMatrixLoc, normalMatrix);
    
        // 绘制目标
        // GL_TRIANGLES 是三角面片形式
        // GL_POINTS 是点云形式
        // 设置不同的绘制模式可能需要对着色器代码也进行更改才行
        glDrawArrays(GL_POINTS, 0, 3);
    
        m_program->release();
    }
    
    void GLWidget::resizeGL(int w, int h)
    {
        m_proj.setToIdentity();
        m_proj.perspective(45.0f, GLfloat(w) / h, 0.01f, 100.0f);
        qDebug() << "m_proj = " << m_proj;
    }
    
    void GLWidget::mousePressEvent(QMouseEvent *event)
    {
        m_lastPos = event->position().toPoint();
        // event->accept();
    }
    
    // 鼠标点住左右键平移的时候,进行图像的旋转,左键绕z,右键绕y
    void GLWidget::mouseMoveEvent(QMouseEvent *event)
    {
        int dx = event->position().toPoint().x() - m_lastPos.x();
        int dy = event->position().toPoint().y() - m_lastPos.y();
    
        if (event->buttons() & Qt::LeftButton) //左键按下,旋转
        {
            setXRotation(m_xRot + 8 * dy);
            setYRotation(m_yRot + 8 * dx);
        }
        else if (event->buttons() & Qt::RightButton) //右键按下,旋转
        {
            setXRotation(m_xRot + 8 * dy);
            setZRotation(m_zRot + 8 * dx);
        }
        else if (event->buttons() & Qt::MiddleButton) //中键按下,平移
        {
            // m_xTrans += float(8 * dx) / width();
            // m_yTrans -= float(8 * dy) / height();
    
            m_xTrans += float(dx) ;
            m_yTrans -= float(dy);
    
            // m_xTrans = float(8 * dx) / width();
            // m_yTrans = float(8 * dy) / height();
    
            update();
        }
    
        m_lastPos = event->position().toPoint();
    }
    
    //滚轮控制缩放,但是这个缩放是改变的倍数,并不是所需要的拉远或拉近镜头
    void GLWidget::wheelEvent(QWheelEvent *event)
    {
        QPoint numDegrees = event->angleDelta() / 8;
    
        m_zTrans += numDegrees.y(); //把原本的缩放倍数改成了z的平移,最后还是用作缩放
        // m_zTrans = numDegrees.y(); //把原本的缩放倍数改成了z的平移
        // if (numDegrees.y() > 0)
        // {
        //     m_scale += 0.1f;
        // }
        // else if (numDegrees.y() < 0)
        // {
        //     m_scale -= 0.1f;
        // }
        this->update();
        event->accept();
    }
    
    

    其他部分不变。

    相关文章

      网友评论

          本文标题:QOpenGLWidget 显示点云,含旋转,平移,缩放

          本文链接:https://www.haomeiwen.com/subject/qrnubrtx.html