I've got simple cpp code. I would like to move QGraphicsScene with mouse move:
// MainWindow.cpp code ------------------------------
void MainWindow::initializeMainViewWidget() {
/* some code */
itemsFrame->setLayout(layout);
mView = std::make_unique<ui::MainView>();
layout->addWidget(mView.get());
mScene = std::make_unique<ui::MainScene>();
mView->setScene(mScene.get());
QObject::connect(mScene.get(), &ui::MainScene::openItem, this, &MainWindow::openUpdateItemDialog);
mView->show();
}
// MainView.cpp code -------------------------------
void MainView::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::RightButton) {
// Store original position.
mPos0 = event->position(); //mPos0 is QPointF
event->accept();
setCursor(Qt::ClosedHandCursor);
return;
} else if (event->button() == Qt::LeftButton) {
event->ignore();
}
QGraphicsView::mousePressEvent(event);
}
void MainView::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
event->ignore();
} else if (event->buttons() & Qt::RightButton) {
QPointF trans = event->position() - mPos0;
mPos0 = event->position();
event->accept();
translate(trans.x(), trans.y());
return;
}
QGraphicsView::mouseMoveEvent(event);
}
But when I add item by:
addItem(someQGraphicsItem);
Item is shown. I can drag it... but can't move scene with RMB and mouseMove.
I took my old sample from SO: Zoom functionality using Qt and added the code to pan the contents by mouse dragging:
#include <QtWidgets>
// class for widget to demonstrate zooming
class Canvas: public QGraphicsView {
// variables:
private:
// start position for pan
QPoint _posRMB;
// methods:
public:
// constructor.
Canvas() = default;
// destructor.
virtual ~Canvas() = default;
// disabled:
Canvas(const Canvas&) = delete;
Canvas& operator=(const Canvas&) = delete;
protected:
virtual void mousePressEvent(QMouseEvent *pQEvent) override
{
if (pQEvent->button() == Qt::RightButton) {
_posRMB = pQEvent->pos();
pQEvent->accept();
setCursor(Qt::ClosedHandCursor);
}
}
virtual void mouseMoveEvent(QMouseEvent *pQEvent) override
{
if (pQEvent->buttons() & Qt::RightButton) {
// pos() -> virtual canvas, _posRMB -> virtual canvas
QPointF delta = mapToScene(pQEvent->pos()) - mapToScene(_posRMB);
// modify transform matrix
translate(delta.x(), delta.y());
_posRMB = pQEvent->pos();
// force update
update();
pQEvent->accept();
}
}
virtual void mouseReleaseEvent(QMouseEvent *pQEvent)
{
if (pQEvent->button() == Qt::RightButton) {
unsetCursor();
}
}
virtual void wheelEvent(QWheelEvent *pQEvent) override
{
//qDebug() << "Wheel Event:";
// pos() -> virtual canvas
QPointF pos = mapToScene(pQEvent->pos());
// scale from wheel angle
float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
// modify transform matrix
QTransform xform = transform();
xform.translate(pos.x(), pos.y()); // origin to spot
xform.scale(delta, delta); // scale
xform.translate(-pos.x(), -pos.y()); // spot to origin
setTransform(xform);
// force update
update();
pQEvent->accept();
}
};
QRectF toScr(QWidget *pQWidget, float x, float y, float w, float h)
{
const int wView = pQWidget->width(), hView = pQWidget->height();
const int s = wView < hView ? wView : hView;
return QRectF(
(0.5f * x + 0.5f) * s, (0.5f * y + 0.5f) * s,
0.5f * w * s, 0.5f * h * s);
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
Canvas canvas;
canvas.setTransformationAnchor(QGraphicsView::NoAnchor);
canvas.setDragMode(QGraphicsView::NoDrag);
canvas.resize(256, 256);
canvas.show();
// prepare scene
QGraphicsScene qGScene;
qGScene.addRect(toScr(canvas.viewport(), -1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u));
qGScene.addRect(toScr(canvas.viewport(), -0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u));
qGScene.addRect(toScr(canvas.viewport(), -0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u));
qGScene.addRect(toScr(canvas.viewport(), -0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu));
qGScene.addRect(toScr(canvas.viewport(), 0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu));
qGScene.addRect(toScr(canvas.viewport(), 0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u));
canvas.setScene(&qGScene);
// runtime loop
return app.exec();
}
Output:
I struggled a while to get it running as expected until I realized that
QPointF delta = mapToScene(pQEvent->pos() - _posRMB); // Not working!
isn't the same as
QPointF delta = mapToScene(pQEvent->pos()) - mapToScene(_posRMB);
Additionally, it's important to disable the auto-fit-to-view of QGraphicsView:
canvas.setTransformationAnchor(QGraphicsView::NoAnchor);
While thinking again about OPs question, I became aware of another possible issue:
If the scene is smaller than the view, it's auto-aligned. (The QGraphicsView::alignment is involved.)
In my demo-session, I started with zoom-in, to prevent this issue.
Another option, to make the scene draggable even it's smaller than the view – the scene size can be tweaked by setting QGraphicsView::sceneRect explicitly.
While scrolling through the doc. of QGrapicsView I noticed:
QGraphicsView::dragMode
dragMode : DragMode
This property holds the behavior for dragging the mouse over the scene while the left mouse button is pressed.
This property defines what should happen when the user clicks on the scene background and drags the mouse (e.g., scrolling the viewport contents using a pointing hand cursor, or selecting multiple items with a rubber band). The default value, NoDrag, does nothing.
This behavior only affects mouse clicks that are not handled by any item. You can define a custom behavior by creating a subclass of QGraphicsView and reimplementing mouseMoveEvent().
which I found worth to mention.
Related
Current implementation, zooms towards the center of View so items present in the top left corner or the current mouse pointer is not visible when we Zoom it.
I want zoom functionality based on the current mouse pointer so items present on the current mouse pointer zoom towards the center of the view.
Code for Zoom base don center of view area
void csGuiView::wheelEvent(QWheelEvent *event)
{
if ((event->modifiers()&Qt::ControlModifier) == Qt::ControlModifier
&& event->angleDelta().x() == 0)
{
QPoint pos = event->pos();
QPointF posf = this->mapToScene(pos);
double angle = event->angleDelta().y();
double scalingFactor;
if(angle > 0)
{
scalingFactor = 1 + ( angle / 360 * 0.1);
}else if (angle < 0)
{
scalingFactor = 1 - ( -angle / 360 * 0.1);
} else
{
scalingFactor = 1;
}
m_pvtData->m_scale = scalingFactor;
this->scale(scalingFactor, scalingFactor);
double w = this->viewport()->width();
double h = this->viewport()->height();
double wf = this->mapToScene(QPoint(w-1, 0)).x()
- this->mapToScene(QPoint(0,0)).x();
double hf = this->mapToScene(QPoint(0, h-1)).y()
- this->mapToScene(QPoint(0,0)).y();
double lf = posf.x() - pos.x() * wf / w;
double tf = posf.y() - pos.y() * hf / h;
/* try to set viewport properly */
this->ensureVisible(lf, tf, wf, hf, 0, 0);
QPointF newPos = this->mapToScene(pos);
this->ensureVisible(QRectF(QPointF(lf, tf) - newPos + posf,
QSizeF(wf, hf)), 0, 0);
}
if ((event->modifiers()&Qt::ControlModifier) != Qt::ControlModifier) {
QGraphicsView::wheelEvent(event);
}
event->accept();
}
To zoom always centered at mouse pointer – the position of mouse pointer just has to become the origin of scaling.
It sounds that simple but I struggled a bit to prepare a demonstration. (I'm not that good in linear algebra, sorry.) However, I finally got it running.
My sample code testQWidget-Zoom.cc:
#include <vector>
#include <QtWidgets>
// class for widget to demonstrate zooming
class Canvas: public QWidget {
// types:
private:
struct Geo {
QRectF rect; QColor color;
Geo(const QRectF &rect, const QColor &color):
rect(rect), color(color)
{ }
};
// variables:
private:
bool _initDone : 1; // flag: true ... sample geo created
std::vector<Geo> _scene; // contents to render
QMatrix _mat; // view matrix
// methods:
public:
// constructor.
Canvas(): QWidget(), _initDone(false) { }
// destructor.
virtual ~Canvas() = default;
// disabled:
Canvas(const Canvas&) = delete;
Canvas& operator=(const Canvas&) = delete;
private:
// initializes sample geo
void init()
{
if (_initDone) return;
_initDone = true;
// build scene (with NDC i.e. view x/y range: [-1, 1])
_scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
_scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
_scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
_scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
_scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
_scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
// get initial scaling
const int wView = width(), hView = height();
_mat.scale(wView / 2, hView / 2);
_mat.translate(1, 1);
}
protected:
virtual void paintEvent(QPaintEvent *pQEvent) override
{
init();
// render
QPainter qPainter(this);
#if 0 // This scales line width as well:
qPainter.setMatrix(_mat);
for (const Geo &geo : _scene) {
qPainter.setPen(geo.color);
qPainter.drawRect(geo.rect);
}
#else // This transforms only coordinates:
for (const Geo &geo : _scene) {
qPainter.setPen(geo.color);
QRectF rect(geo.rect.topLeft() * _mat, geo.rect.bottomRight() * _mat);
qPainter.drawRect(rect);
}
#endif // 0
}
virtual void wheelEvent(QWheelEvent *pQEvent) override
{
//qDebug() << "Wheel Event:"
//qDebug() << "mouse pos:" << pQEvent->pos();
// pos() -> virtual canvas
bool matInvOK = false;
QMatrix matInv = _mat.inverted(&matInvOK);
if (!matInvOK) {
qDebug() << "View matrix not invertible!";
return;
}
QPointF posNDC
= QPointF(pQEvent->pos().x(), pQEvent->pos().y()) * matInv;
//qDebug() << "mouse pos (NDC):" << posNDC;
float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
//qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
//qDebug() << "scale factor:" << delta;
_mat.translate(posNDC.x(), posNDC.y()); // origin to spot
_mat.scale(delta, delta); // scale
_mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin
update();
pQEvent->accept();
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Canvas canvas;
canvas.resize(512, 512);
canvas.show();
// runtime loop
return app.exec();
}
and these three lines are the actual interesting ones (in Canvas::wheelEvent()):
_mat.translate(posNDC.x(), posNDC.y()); // origin to spot
_mat.scale(delta, delta); // scale
_mat.translate(-posNDC.x(), -posNDC.y()); // spot to origin
And this is how it looks:
The first image is a snapshot of the application just after starting it.
Then I pointed into the center of the red rectangle and turned the wheel slightly. The red rectangle grew around the mouse pointer as intended.
1st Update:
And, this is the updated version which uses screen coordinates directly (instead of converting everything to NDCs):
#include <vector>
#include <QtWidgets>
// class for widget to demonstrate zooming
class Canvas: public QWidget {
// types:
private:
struct Geo {
QRectF rect; QColor color;
Geo(const QRectF &rect, const QColor &color):
rect(rect), color(color)
{ }
};
// variables:
private:
bool _initDone : 1; // flag: true ... sample geo created
std::vector<Geo> _scene; // contents to render
QMatrix _mat; // view matrix
// methods:
public:
// constructor.
Canvas(): QWidget(), _initDone(false) { }
// destructor.
virtual ~Canvas() = default;
// disabled:
Canvas(const Canvas&) = delete;
Canvas& operator=(const Canvas&) = delete;
private:
// initializes sample geo
void init()
{
if (_initDone) return;
_initDone = true;
const int wView = width(), hView = height();
// build scene (with NDC i.e. view x/y range: [-1, 1])
_scene.emplace_back(Geo(QRectF(-1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u)));
_scene.emplace_back(Geo(QRectF(-0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u)));
_scene.emplace_back(Geo(QRectF(-0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u)));
_scene.emplace_back(Geo(QRectF(-0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu)));
_scene.emplace_back(Geo(QRectF(0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu)));
_scene.emplace_back(Geo(QRectF(0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u)));
// scale geometry to screen coordinates
QMatrix mat;
mat.scale(wView / 2, hView / 2);
mat.translate(1, 1);
for (Geo &geo : _scene) {
geo.rect = QRectF(geo.rect.topLeft() * mat, geo.rect.bottomRight() * mat);
}
}
protected:
virtual void paintEvent(QPaintEvent *pQEvent) override
{
init();
// render
QPainter qPainter(this);
qPainter.setMatrix(_mat);
for (const Geo &geo : _scene) {
qPainter.setPen(geo.color);
qPainter.drawRect(geo.rect);
}
}
virtual void wheelEvent(QWheelEvent *pQEvent) override
{
//qDebug() << "Wheel Event:";
//qDebug() << "mouse pos:" << pQEvent->pos();
float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
//qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
//qDebug() << "scale factor:" << delta;
_mat.translate(pQEvent->pos().x(), pQEvent->pos().y()); // origin to spot
_mat.scale(delta, delta); // scale
_mat.translate(-pQEvent->pos().x(), -pQEvent->pos().y()); // spot to origin
update();
pQEvent->accept();
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Canvas canvas;
canvas.resize(256, 256);
canvas.show();
// runtime loop
return app.exec();
}
The relevant three lines didn't change much – the mouse coordinates are applied directly to transformation.
Btw. I changed the rendering – it now scales line width as well as I used
qPainter.setMatrix(_mat);
in Canvas::paintEvent() instead of transforming all points "manually".
The snapshot shows the application after I pointed into the center of the blue rectangle and turned the mouse wheel:
2nd Update:
The suggested matrix manipulation works in a QGraphicsView as well:
#include <QtWidgets>
// class for widget to demonstrate zooming
class Canvas: public QGraphicsView {
// methods:
public:
// constructor.
Canvas() = default;
// destructor.
virtual ~Canvas() = default;
// disabled:
Canvas(const Canvas&) = delete;
Canvas& operator=(const Canvas&) = delete;
protected:
virtual void wheelEvent(QWheelEvent *pQEvent) override
{
//qDebug() << "Wheel Event:";
// pos() -> virtual canvas
QPointF pos = mapToScene(pQEvent->pos());
//qDebug() << "mouse pos:" << pos;
// scale from wheel angle
float delta = 1.0f + pQEvent->angleDelta().y() / 1200.0f;
//qDebug() << "angleDelta:" << pQEvent->angleDelta().y();
//qDebug() << "scale factor:" << delta;
// modify transform matrix
QTransform xform = transform();
xform.translate(pos.x(), pos.y()); // origin to spot
xform.scale(delta, delta); // scale
xform.translate(-pos.x(), -pos.y()); // spot to origin
setTransform(xform);
//qDebug() << "transform:" << xform;
// force update
update();
pQEvent->accept();
}
};
QRectF toScr(QWidget *pQWidget, float x, float y, float w, float h)
{
const int wView = pQWidget->width(), hView = pQWidget->height();
const int s = wView < hView ? wView : hView;
return QRectF(
(0.5f * x + 0.5f) * s, (0.5f * y + 0.5f) * s,
0.5f * w * s, 0.5f * h * s);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
// setup GUI
Canvas canvas;
canvas.setTransformationAnchor(QGraphicsView::NoAnchor);
canvas.resize(256, 256);
canvas.show();
// prepare scene
QGraphicsScene qGScene;
qGScene.addRect(toScr(canvas.viewport(), -1.0f, -1.0f, 2.0f, 2.0f), QColor(0x000000u));
qGScene.addRect(toScr(canvas.viewport(), -0.2f, -0.2f, 0.4f, 0.4f), QColor(0x00ff00u));
qGScene.addRect(toScr(canvas.viewport(), -0.8f, -0.8f, 0.4f, 0.4f), QColor(0xff0000u));
qGScene.addRect(toScr(canvas.viewport(), -0.8f, 0.4f, 0.4f, 0.4f), QColor(0x0000ffu));
qGScene.addRect(toScr(canvas.viewport(), 0.4f, 0.4f, 0.4f, 0.4f), QColor(0xff00ffu));
qGScene.addRect(toScr(canvas.viewport(), 0.4f, -0.8f, 0.4f, 0.4f), QColor(0xffff00u));
canvas.setScene(&qGScene);
// runtime loop
return app.exec();
}
Using a QGraphicsView simplifies code as no rendering code is needed – it's already built-in.
As I have not (yet) much experience with QGraphicsView, another issue hit me quite hard: The QGraphicsView is able to fix the view position automati[cg]ally after a transformation has been applied. In my case, this was rather counter-productive as obviously my transformation and the QGraphicsView seemed to "pull" in opposite directions.
Hence, I've learnt my lesson of the day: QGrapicsView::setTransformationAnchor(QGraphicsView::NoAnchor)
is necessary to switch off this (in my case not-intended) auto-centering.
The other detail I find worth to notice is QGraphicsView::mapToScene() which can be used to conveniently convert widget coordinates (e.g. mouse coordinates) to scene space.
I have done some research trough the different threads about PaintGL on SO, but I couldn't manage to find what I need to make it work / understand completely.
I am trying to draw a cube. EVerytime my pushbutton gets clicked the cube should rotate. (only when it gets clicked, no timers etc)
To determine the angle I use the variable xAngle. I am able to modify it trough the function setAngleCube(), but my cube doesn't seem to move. (I see the var 'i' being changed every time.)
why? How could I make it work?
To me it looks like the cube just keeps its value from the constructor and doesn't modiy them any more.
solution:
add this line in the slot of the pushbutton
ui->widget->setCubeAngle(ui->widget->getCubeAngle()+5);
credit to #Alexander Chernin
my code:
MyGLWidget::MyGLWidget(QWidget *parent)
: QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{
xRot = 0;
yRot = 0;
zRot = 0;
xAngle=15;
qDebug("constructor\n") ;
}
void MyGLWidget::setCubeAngle(int angle)
{
xAngle = angle;
qDebug("angle set\n");
}
int MyGLWidget::getCubeAngle()
{
return xAngle;
}
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
Glptr = new MyGLWidget();
}
void Widget::on_pushButton_clicked()
{
static int i;
i+=5;
Glptr->setCubeAngle(i);
update();
qDebug()<<i<<endl;
ui->widget->setCubeAngle(ui->widget->getCubeAngle()+5); //SOLUTION
}
void MyGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
qDebug("painting cube\n");
qDebug()<
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(getCubeAngle(),0.0,1.0,0.0); //rotate 30 degress around y-axis
glRotatef(5.0,1,0.0,0.0); //rotate 15 degress around x-axis
glBegin(GL_QUADS);
//back
glColor3f(1,0,0);
glVertex3f(-0.5, 0.2,-0.5 );
glVertex3f(-0.7, 0.2,-0.5);
glVertex3f(-0.7, -0.2,-0.5 );
glVertex3f(-0.5, -0.2,-0.5);
//some similar code to draw other sides of the cube
}
try to call updateGL() in MyGLWidget::setCubeAngle:
void MyGLWidget::setCubeAngle(int angle)
{
xAngle = angle;
qDebug("angle set\n");
updateGL();
}
I am trying to implement an arcball/trackball controller using Open GL and Qt. However, I am quite new to OpenGL. I am having a terrible, terrible, terrible time getting things to work.
I started by following this video: https://www.youtube.com/watch?v=3IQV65ApWGs
I am using Qt for my window, using their QtWidget class.
Basically, I have a cube around the origin. I want to orbit the camera around the cube with the mouse. Right now, when I drag the camera seems to stay put while the cube orbits around the sphere. Kind of the opposite of what I need.
I hope you guys can help. I feel like I've tried nearly everything here.
First my mouse handling:
void GLWidget::wheelEvent(QWheelEvent *e){
scrollDelta += e->delta() / 120;
}
void GLWidget::mousePressEvent(QMouseEvent *e){
rotate=false;
if(e->button() == Qt::LeftButton){
oldX = e->x(); // Set this to the mouse position
oldY = e->y(); // Set this to the mouse position
newX = e->x();
newY = e->y();
qDebug() << oldX << oldY << newX << newY;
rotate = true;
useArcBall = true;
}
}
void GLWidget::mouseMoveEvent(QMouseEvent *e){
if(e->buttons() & Qt::LeftButton){
//qDebug() << QString::number(e->x());
if(rotate){
newX = e->x();
newY = e->y();
updateMouse();
}
oldX = e->x();
oldY = e->y();
}
}
void GLWidget::mouseReleaseEvent(QMouseEvent *e){
if(e->button() == Qt::LeftButton)
useArcBall = false;
}
void GLWidget::updateMouse()
{
QVector3D v = getArcBallVector(oldX,oldY); // from the mouse
QVector3D u = getArcBallVector(newX, newY);
float angle = std::acos(std::min(1.0f, QVector3D::dotProduct(u,v)));
QVector3D rotAxis = QVector3D::crossProduct(v,u);
QMatrix4x4 eye2ObjSpaceMat = rotationMat.inverted();
QVector3D objSpaceRotAxis = eye2ObjSpaceMat * rotAxis;
qDebug() << 4 * qRadiansToDegrees(angle);
//modelview.rotate(4 * qRadiansToDegrees(angle), rotAxis);
//oldRot = newRot;
//oldX = newX;
//oldY = newY;
//qDebug() << objSpaceRotAxis.normalized();
if(true){
rotationMat.rotate(4 * qRadiansToDegrees(angle), objSpaceRotAxis);
}
}
Now the arcball related math:
QVector3D GLWidget::getArcBallVector(int x, int y)
{
QVector3D pt = QVector3D(2.0 * x / GLWidget::width() - 1.0, 2.0 * y / GLWidget::height() - 1.0 , 0);
pt.setY(pt.y() * -1);
// compute z-coordinates
float xySquared = pt.x() * pt.x() + pt.y() * pt.y();
if(xySquared <= 1.0)
pt.setZ(std::sqrt(1.0 - xySquared));
else
pt.normalize();
return pt;
}
And this is the part where I render everything:
void GLWidget::paintGL()
{
QMatrix4x4 modelview;
QPainter painter;
painter.begin(this);
painter.beginNativePainting();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFrontFace(GL_CW);
glCullFace(GL_FRONT);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
modelview.perspective(90.0f, 4.0f / 3.0f, 0.1f, 3000.0f);
modelview.lookAt(QVector3D(eyeX,eyeY,eyeZ), QVector3D(0,0,0), QVector3D(0,1,0));
// New Trackball code
modelview = rotationMat * modelview;
modelview.scale(1 - scrollDelta / 10);
What am I doing wrong?
Is my approach unsound?
update So I fixed some of the mouse handling. Now my issue is that cube is rotating around the surface of sphere, rather than the camera. Is this because I am using the lookat command?
Also, the cube is being occluded by background color as I turn it. Is this a projection problem?
looks like your matrices are applied in the wrong order
in paintGL you should do:
modelview *= rotationMat;
and in updateMouse you should do
QMatrix4x4 tmp;
tmp.rotate(4 * qRadiansToDegrees(angle), objSpaceRotAxis);
rotationMat = tmp * rotationMat;
I'm trying to port my height map visualization program written on c++, from SFML to Qt, so it can be shown on widget and controlled by the GUI elements.
The problem is that when I start an application, a camera starts to roll around its center very fast(actually, it looks like a terrain mesh flying around a camera, like an Earth around the Sun :), without any actions from my side(e.g moving mouse, pressing buttons).
Camera should move forward, back, left, right when I press w,a,s,d and look around when I move the mouse(Just typical FPS camera behavior).
I think that problem are in the program's main loop, because it's no standard while(true){ //do something// } approach in qt, and it's a little confusing.
Here's my code:
OGLWidget class(here I'm drawing stuff. Problem somewhere here I think) :
class OGLWidget :
public QGLWidget
{
Q_OBJECT
public:
OGLWidget(QWidget *parent = 0);
~OGLWidget(void);
public:
void paintGL();
void initializeGL();
void resizeGL();
public:
void updateCamera();
public slots:
void mainLoop();
protected:
void keyPressEvent(QKeyEvent *e);
void keyReleaseEvent(QKeyEvent *e);
private:
Terrain _terrain;
Camera _camera;
private:
int _keyPressed;
QTimer _timer;
QElapsedTimer _elapsedTimer;
float _simulationTime;
float _fps;
};
OGLWidget::OGLWidget(QWidget *parent) : QGLWidget(parent)
{
_terrain.loadHeightMap("normalHeightMap256_2.png");
_camera.setScreenDimension(this->width(), this->height());
//setting vertical sync
QGLFormat frmt;
frmt.setSwapInterval(1);
setFormat(frmt);
setMouseTracking(true);
setFocus();
_simulationTime = 0;
_fps = 1.f / 60.f;
connect(&_timer, SIGNAL(timeout()), this, SLOT(mainLoop()));
_timer.start();
_elapsedTimer.start();
}
OGLWidget::~OGLWidget(void)
{
}
void OGLWidget::mainLoop()
{
_simulationTime += _elapsedTimer.elapsed();
_elapsedTimer.restart();
while(_simulationTime > _fps)
{
_simulationTime -= _fps;
updateCamera();
}
updateGL();
}
void OGLWidget::updateCamera()
{
QPoint p = mapFromGlobal(QCursor::pos());
_camera.computeMatrices(p.x(), p.y(), _fps, _keyPressed);
glm::mat4 ViewMatrix = _camera.getViewMatrix();
glm::mat4 ProjectionMatrix = _camera.getProjectionMatrix();
glm::mat4 ModelMatrix = glm::mat4(1.0);
_terrain.setMvp(ProjectionMatrix * ViewMatrix * ModelMatrix);
QPoint center = mapToGlobal(QPoint(this->width() / 2, this->height() / 2));
QCursor::setPos(center);
}
void OGLWidget::initializeGL()
{
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
return;
}
glViewport(0, 0, this->width(), this->height());
_terrain.init();
}
void OGLWidget::paintGL()
{
_terrain.draw();
}
void OGLWidget::resizeGL()
{
glViewport(0, 0, this->width(), this->height());
}
void OGLWidget::keyPressEvent(QKeyEvent *e)
{
switch(e->key())
{
case Qt::Key::Key_Escape:
exit(0);
break;
case Qt::Key::Key_W:
_keyPressed = Key::KEY_PRESSED_UP;
break;
case Qt::Key::Key_S:
_keyPressed = Key::KEY_PRESSED_DOWN;
break;
case Qt::Key::Key_A:
_keyPressed = Key::KEY_PRESSED_LEFT;
break;
case Qt::Key::Key_D:
_keyPressed = Key::KEY_PRESSED_RIGHT;
break;
}
}
void OGLWidget::keyReleaseEvent(QKeyEvent *e)
{
if(e->key() == Qt::Key::Key_W ||
e->key() == Qt::Key::Key_S ||
e->key() == Qt::Key::Key_A ||
e->key() == Qt::Key::Key_D)
_keyPressed = KEY_RELEASED;
}
I'm absolutely sure that Terrain and Camera classes are working correct, because I haven't changed code since my SFML project(Except of using QImage instead of sf::Image, but it's working correct too)
*Camera main algorithm: *
void Camera::computeMatrices(int mouseXpos, int mouseYpos, float deltaTime, int keyPressed)
{
_horizontalAngle += _mouseSpeed * deltaTime * float(_screenWidth / 2 - mouseXpos);
_verticalAngle += _mouseSpeed * deltaTime * float(_screenHeight / 2 - mouseYpos);
_direction = glm::vec3
(
cos(_verticalAngle) * sin(_horizontalAngle),
sin(_verticalAngle),
cos(_verticalAngle) * cos(_horizontalAngle)
);
glm::vec3 right = glm::vec3
(
sin(_horizontalAngle - 3.14f/2.0f),
0,
cos(_horizontalAngle - 3.14f/2.0f)
);
glm::vec3 up = glm::cross( right, _direction );
switch(keyPressed)
{
case Key::KEY_PRESSED_UP:
_position += _direction * deltaTime * _speed;
break;
case Key::KEY_PRESSED_DOWN:
_position -= _direction * deltaTime * _speed;
break;
case Key::KEY_PRESSED_LEFT:
_position -= right * deltaTime * _speed;
break;
case Key::KEY_PRESSED_RIGHT:
_position += right * deltaTime * _speed;
break;
case Key::KEY_RELEASED:
break;
}
_projectionMatrix = glm::perspective(_initialFoV, 4.0f / 3.0f, 0.1f, 1000.0f);
_viewMatrix = glm::lookAt
(
_position, // Camera is here
_position+_direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
}
Help me fix this issue.
Ok, I figured out the problem with spinning camera. The cause of it was that I hardcoded an aspect ratio in Camera::computeMatrices, and used a resolution of my widget which doesn't match to it:
_projectionMatrix = glm::perspective
(
_initialFoV,
4.0f / 3.0f, //here it is
0.1f,
1000.0f
);
I changed 4.0f / 3.0f on (float)_screenWidth / (float)_screenHeight but it didn't help too.
So then I just changed a resolution of my widget to 800 x 600 and it helped.
The new problem is that it works only on 4/3 dimensions(e.g 800x600, 1024x768).
The best way to correct
_direction = glm::vec3
(
cos(_verticalAngle) * sin(_horizontalAngle),
sin(_verticalAngle),
cos(_verticalAngle) * cos(_horizontalAngle)
);
_direction.normalize();
...
I have an openGL widget, where I want to render a line which is dependent of mouse positions, as follows:
glPushMatrix();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(1, 0, 0, 0.1);
glScalef(a, b, 0);
glBegin(GL_LINES);
glVertex2f(pushedX, pushedY);
glVertex2f(currentX, currentY);
glEnd();
glFlush();
glDisable(GL_BLEND);
glPopMatrix();
where:
pushedX=buttonPressCoordinates.x();
pushedY=buttonPressCoordinates.y();
currentX=mouseCurrentPosition.x();
currentY=mouseCurrentPosition.y();
The rendering goes good, and the line is rendered as required when I move the mouse connecting with line the pushed and current coordinates.
BUT:
the issue is, that even when I press my mouse somewhere on the widget and don't move it, it generates randomly (as I think) some (x,y) and connects the it with a line with the coordinates of mouse pressed position. Though when I start moving my mouse it starts working fine.
Please, help to fix this bug.
EDIT
The code of assigning the current values of the mouse
void MainWindow::mouseMoveEvent(QMouseEvent *eventMove)
{
if(eventMove->buttons() & Qt::LeftButton)
{
GLWidget *widget = this->findChild<GLWidget *>("glwidget");
float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
float y_ = 1.0 - y;
mouseCurrentPosition.setX(x);
mouseCurrentPosition.setY(y_);
widget->setCurrentX(mouseCurrentPosition.x());
widget->setCurrentY(mouseCurrentPosition.y());
}
}
note: QPointF mouseCurrentPosition;, getNormalizedWidth(...) is my defined fundction which works perfect.
EDIT-2
The mouse click coordinates are updated as follows:
setMouseTracking(true);
m = true;
GLWidget *widget = this->findChild<GLWidget *>("glwidget");
float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
float y_ = 1.0 - y;
buttonPressCoordinates.setX(x);
buttonPressCoordinates.setY(y_);
qDebug() << buttonPressCoordinates.x() << buttonPressCoordinates.y();
widget->setQ(true);
widget->setPushedX(buttonPressCoordinates.x());
widget->setPushedY(buttonPressCoordinates.y());
One thing you can try is to update currentX and currentY in the mouseMoveEvent when LeftButton is not pressed:
void MainWindow::mouseMoveEvent(QMouseEvent *eventMove)
{
GLWidget *widget = this->findChild<GLWidget *>("glwidget");
float x = widget->getNormalizedWidth(widget->mapFromGlobal(QCursor::pos()).x());
float y = widget->getNormalizedHeight(widget->mapFromGlobal(QCursor::pos()).y());
float y_ = 1.0 - y;
if(eventMove->buttons() & Qt::LeftButton)
{
buttonPressCoordinates.setX(x);
buttonPressCoordinates.setY(y_);
widget->setPushedX(buttonPressCoordinates.x());
widget->setPushedY(buttonPressCoordinates.y());
}
else
{
mouseCurrentPosition.setX(x);
mouseCurrentPosition.setY(y_);
widget->setCurrentX(mouseCurrentPosition.x());
widget->setCurrentY(mouseCurrentPosition.y());
}
}