头文件
#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;
}