Qt+OpenGL——模型控制类实现

头文件

#ifndef GLMODELCTRL_H
#define GLMODELCTRL_H

#include <QVector2D>
#include <QVector3D>
#include <QMatrix4x4>
#include <QObject>

class GLModelCTRL : public QObject
{
    Q_OBJECT
public:
    explicit GLModelCTRL(QObject *parent = nullptr);
    ~GLModelCTRL();

    void translate(const float &x,const float &y,const float &z);
    void scale(const float &fScale);
    void rotate(const float &xMouseOffset,const float &yMouseOffset);

    void setRotateSpeed(const float &speed = float(2.0f));

    void resetModel();
    QMatrix4x4 getModel();

private:
    QMatrix4x4 m_mat4Model;
    QVector3D m_v3Translate = QVector3D(0.0f,0.0f,0.0f);
    float m_fScale = 1.0f;
    float m_fRotateSpeed = 2.0f;
};

#endif // GLMODELCTRL_H

源文件

#include "glmodelctrl.h"
#include <QtMath>

GLModelCTRL::GLModelCTRL(QObject *parent) : QObject(parent)
{

}

GLModelCTRL::~GLModelCTRL()
{

}

void GLModelCTRL::translate(const float &x, const float &y, const float &z)
{
    m_v3Translate += QVector3D(x,y,z);
    m_mat4Model.translate(m_v3Translate);
}

void GLModelCTRL::scale(const float &fScale)
{
    m_fScale *= fScale;
    m_mat4Model.scale(fScale);
}

void GLModelCTRL::rotate(const float &xMouseOffset, const float &yMouseOffset)
{
    double dDeltaX = xMouseOffset;
    double dDeltaY = -yMouseOffset;

    double dCosTheta = dDeltaX / qSqrt(qPow(dDeltaX,2) + qPow(dDeltaY,2));
    double dSinTheta = dDeltaY / qSqrt(qPow(dDeltaX,2) + qPow(dDeltaY,2));

    QVector3D axis(-dSinTheta,dCosTheta,0);

    double dAngle = sqrt(pow(dDeltaX,2) + pow(dDeltaY,2));
    QVector4D axis_2;
    QMatrix4x4 inverseModel = m_mat4Model.inverted();
    axis_2 = inverseModel * QVector4D(axis,0);
    m_mat4Model.rotate(qDegreesToRadians(dAngle * m_fRotateSpeed),axis_2.x(),axis_2.y(),axis_2.z());

}

void GLModelCTRL::setRotateSpeed(const float &speed)
{
    m_fRotateSpeed = speed;
}

void GLModelCTRL::resetModel()
{
    m_mat4Model = QMatrix4x4();
    m_fScale = 1.0f;
    m_v3Translate = QVector3D(0.0f,0.0f,0.0f);
}

QMatrix4x4 GLModelCTRL::getModel()
{
    return m_mat4Model;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值