7

I am trying to make an application in Qt-openGL. Here, I have to know the clicked object, based on the mouse click. My idea is storing the points(object's area in QWidget), and match the mouse click against these points. Can anybody say how to do this?, or Can any body show any other way?

prabhakaran
  • 5,126
  • 17
  • 71
  • 107

1 Answers1

16

This problem is usually known as "picking". OpenGL itself just draws things, there's no geometry object management to speak of (OpenGL has objects, but they are, what you'd normally call resources).

The usual way to implement OpenGL picking these days is retrieving the depth value at the click position (glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth)) and unproject it into world space (gluUnProject(...)). This gives you the (x,y,z) of the clicked point.

Since you'll usually manage your geometry in some spatial subdivision structure (BSP, Kd, etc.) by traversing the subdivision structure to the click coordinates you can retrieve the object that way.

Another method is projecting a ray that follows the click into the scene and do ray / bounding volume intersection tests.

I strongly discourage the use of the old OpenGL selection mechanism: It's slow and cumbersome to use.

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • Now that shaders are prevalent, isn't it easy to set an object id for each object and use the fragment shader to write that to an unblended hidden plane? Picking then becomes reading from that plane at the mouse coordinates. No need for unprojection or a geometry search. – Ben Voigt Jun 18 '11 at 22:04
  • 1
    @Ben Voigt: As long as you're interested in only the one object under the mouse pointer - of course this matches the unprojection method - then yes. If however you're interested in all the objects under the pointer, then you'll have to use the ray picking method, or use some depth peeling. However in most serious 3D applications the objects are manages using some spatial structure anyway, and having that a test against this is usually easier. – datenwolf Jun 18 '11 at 22:08
  • i do picking by using gluUnProject & glReadPixels, but the result is always the farest object instead of the nearest one, any reason why? – jondinham Aug 30 '11 at 17:03