glReadPixels in mousePressed

柔情痞子 提交于 2019-12-20 02:41:59

问题


I am trying to get the color of a pixel in JOGL when the user clicks on it. If I put the following code in the display method (coming from the GLEventListener), it works fine.

FloatBuffer buffer = FloatBuffer.allocate(4);

gl.glReadBuffer(GL3.GL_FRONT);
gl.glReadPixels(10, 10, 1, 1, GL3.GL_RGBA, GL3.GL_FLOAT, buffer);
float[] pixels = new float[3];
pixels = buffer.array();
float red = pixels[0];
float green = pixels[1];
float blue = pixels[2];
System.out.println(red + ", " + green + ", " + blue);

However, if I put my code in the mousePressed method, I get an invalid operation error when checking for success and the color returns black (0, 0, 0).

Is there a way to get this to work in my mousePressed method, or will I have to store the selected pixel, along with a boolean to indicate selection (so that I don't call glReadPixels every frame) and do the selection in the display method?

P.s. the (x,y) coords = (10,10) is just to make sure the selection is really inside my window (which it is, since the pixel color comes out correctly in the display method).


回答1:


An OpenGL context can only be active in a single thread at a time, if your event handling for mouse presses comes on a different thread, you won't be able to properly query information from OpenGL at that time. Generally speaking, I would err on the side of reading the pixel value in the display function. If you want to avoid reading pixels every frame, you could keep track of the last location you read from, and only call glReadPixels if the position to read from has changed.

As datenwolf mentions, it is possible to deactivate and activate your context to access it across multiple threads, if you need to do so.



来源:https://stackoverflow.com/questions/8329663/glreadpixels-in-mousepressed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!