三维坐标系下 使用opengl拾取物件的操作【新浪博客迁移】
代码来自nehe opengl:
void select()
{
GLuintbuffer[512];
GLuinthits;
GLintviewPort[4];
glGetIntegerv(GL_VIEWPORT,viewPort);
glSelectBuffer(512,buffer);
(void)glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix((GLdouble)lmouseX,(GLdouble)(viewPort[3]- lmouseY),1.0,1.0,viewPort);
gluPerspective(45.0f,(GLfloat)(viewPort[2]-viewPort[0])/(GLfloat)(viewPort[3]- viewPort[1]),0.1f,50000.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
//矩阵变换函数
//绘制函数
//
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
hits =glRenderMode(GL_RENDER);
if(hits>0)
{
int choose =buffer[3]; // Make Our Selection The First Object
int depth =buffer[1]; // Store How Far Away It Is
for (int loop = 1; loop <(int)hits; loop++) // Loop Through All The Detected Hits
{
// If This Object Is Closer To Us Than The One WeHave Selected
if (buffer[loop*4+1] <GLuint(depth))
{
choose =buffer[loop*4+3]; // Select The Closer Object
depth =buffer[loop*4+1]; // Store How Far Away It Is
}
}
int k = 0;
}
}
1.插入相应的矩阵变换函数 矩阵变换函数相当重要 如果错误将会影响整个操作的执行
2.在绘制函数中有glloadname函数,注意glloadname函数不能放在glbegin和glend之间
GLuinthits;
GLintviewPort[4];
glGetIntegerv(GL_VIEWPORT,viewPort);
glSelectBuffer(512,buffer);
(void)glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix((GLdouble)lmouseX,(GLdouble)(viewPort[3]- lmouseY),1.0,1.0,viewPort);
gluPerspective(45.0f,(GLfloat)(viewPort[2]-viewPort[0])/(GLfloat)(viewPort[3]- viewPort[1]),0.1f,50000.0f);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
//矩阵变换函数
//绘制函数
//
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
hits =glRenderMode(GL_RENDER);
if(hits>0)
{
int choose =buffer[3]; // Make Our Selection The First Object
int depth =buffer[1]; // Store How Far Away It Is
for (int loop = 1; loop <(int)hits; loop++) // Loop Through All The Detected Hits
{
// If This Object Is Closer To Us Than The One WeHave Selected
if (buffer[loop*4+1] <GLuint(depth))
{
choose =buffer[loop*4+3]; // Select The Closer Object
depth =buffer[loop*4+1]; // Store How Far Away It Is
}
}
int k = 0;
}
}
1.插入相应的矩阵变换函数 矩阵变换函数相当重要 如果错误将会影响整个操作的执行
2.在绘制函数中有glloadname函数,注意glloadname函数不能放在glbegin和glend之间