OpenGL:投影鼠标点击几何 [英] OpenGL: projecting mouse click onto geometry

查看:71
本文介绍了OpenGL:投影鼠标点击几何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个视图集:

  glMatrixMode(GL_MODELVIEW); //切换到图形透视图
glLoadIdentity(); //重新绘制透视图

我从鼠标单击中获得一个屏幕位置(sx,sy) 。



给定z的值,如何从sx和sy计算x和y的三维空间?

解决方案

您应该使用 gluUnProject 首先,计算对近平面unprojection:

  GLdouble modelMatrix [16]; 
GLdouble projMatrix [16];
GLint视口[4];

glGetIntegerv(GL_VIEWPORT,viewport);
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);

GLdouble x,y,z;
gluUnProject(sx,viewport [1] + viewport [3] - sy,0,modelMatrix,projMatrix,viewport,& x,& y,& z);

然后到达远处:

  //将上面的gluUnProject调用替换为
gluUnProject(sx,viewport [1] + viewport [3] - sy,1,modelMatrix,projMatrix,viewport,& x, & y,& z);

现在,您已经在世界坐标中有一条线,可以找出所有可能的点已被点击。所以现在你只需要插入:假设你得到了z坐标:

  GLfloat nearv [3],farv [ 3]; //已经如上计算

if(nearv [2] == farv [2])//这意味着我们没有解决方案
return;

GLfloat t =(nearv [2] - z)/(nearv [2] - farv [2]);

//所以这里是所需的(x,y)坐标
GLfloat x = nearv [0] +(farv [0] - nearv [0])* t,
y = nearv [1] +(farv [1] - nearv [1])* t;


I have this view set:

glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective
glLoadIdentity(); //Reset the drawing perspective

and I get a screen position (sx, sy) from a mouse click.

Given a value of z, how can I calculate x and y in 3d-space from sx and sy?

解决方案

You should use gluUnProject:

First, compute the "unprojection" to the near plane:

GLdouble modelMatrix[16];
GLdouble projMatrix[16];
GLint viewport[4];

glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);

GLdouble x, y, z;
gluUnProject(sx, viewport[1] + viewport[3] - sy, 0, modelMatrix, projMatrix, viewport, &x, &y, &z);

and then to the far plane:

// replace the above gluUnProject call with
gluUnProject(sx, viewport[1] + viewport[3] - sy, 1, modelMatrix, projMatrix, viewport, &x, &y, &z);

Now you've got a line in world coordinates that traces out all possible points you could have been clicking on. So now you just need to interpolate: suppose you're given the z-coordinate:

GLfloat nearv[3], farv[3];  // already computed as above

if(nearv[2] == farv[2])     // this means we have no solutions
   return;

GLfloat t = (nearv[2] - z) / (nearv[2] - farv[2]);

// so here are the desired (x, y) coordinates
GLfloat x = nearv[0] + (farv[0] - nearv[0]) * t,
        y = nearv[1] + (farv[1] - nearv[1]) * t;

这篇关于OpenGL:投影鼠标点击几何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆