This is my code that I use to get my mouse position in the 3d scene:
void GetOGLPos(int x, int y, GLdouble &pX, GLdouble &pY, GLdouble &pZ){
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)x;
winY = (float)viewport[3]-(float)y;
glReadPixels(x, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &pX, &pY, &pZ);
}
But I noticed a bad thing... 1-2 calls to that function per frame makes CPU usage 100%, 3 or more calls 200% CPU usage (I have 4 cores, 1-2 calls = 25%, 3 or more calls = 50%, I can't make it higher than 50% I think..)
Is there any other way to do this efficiently? I'm using 4 calls to that function every frame so I know which areas I should render for my scene (I take them from each screen corner).
Also I use this to know which place I am pointing with mouse, so I need it in real time, but I would like to use less CPU, because even just 1 call makes it 100% usage for single core systems.
EDIT
I've tried glPushName() method but its even slower, more likely slower in my GPU than in CPU. Also my CPU usage is only like 0-1% when I don't use a single glReadPixels() call in my program. Weird thing is that I get high CPU usage, but it doesn't make the program lag as you would expect with 100% usage... only problem comes when I use other programs while my program is on, then its laggy to use them.
It seems like you try to do picking in OpenGL.
Check out this tutorial, it should come with less performance penalty than your approach: http://gpwiki.org/index.php/OpenGL:Tutorials:Picking
This place mentions other ways of doing picking in OpenGL: http://www.opengl.org/resources/faq/technical/selection.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With