using glReadPixels with ByteBuffer

Started by ParticleSwarm, February 28, 2011, 03:07:55

Previous topic - Next topic

ParticleSwarm

UPDATE: The problem was two fold. First, the reason all the primitives were giving the same output was because I did not specify the buffer to read. I played with glReadBuffer and finally found out GL11.glReadBuffer(GL11.GL_FRONT) worked. Once I was getting meaningful responses, I had to fix the garbled output. The response by avm1979 solved that problem, as I was handling bits wrong. Thanks!

I've been banging my head over this. Any help would be greatly appreciated! I'm trying to get color picking to work with my project. It uses OpenGL in Java (lwjgl).

So I'm using a simple loop to give each new primitive rendered a unique color with:
glColorub(ubColor[0], ubColor[1], ubColor[2]) , where ubColor loops through 0-255 for each cell. I know this much is working correctly.

The problem arises when I try and read the ByteBuffer after calling glReadPixels. I get junk values, like 0, -52 and -1. They don't seem to change for any primitive I click either. I've included what I think is the important code below.

       GL11.glDisable(GL11.GL_TEXTURE_2D);
        GL11.glDisable(GL11.GL_FOG);
        GL11.glDisable(GL11.GL_LIGHTING);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

    	
    	int nWidth = 1; 
    	int nHeight = 1;
        ByteBuffer pRGB = ByteBuffer.allocateDirect(3);
    	
        ////Render Primitives here
        ColorPicking.renderSector(0);
        ////
        
        //Window height is 600
        // x and y are mouse location
	GL11.glReadPixels( x,600 - y, 1, 1, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pRGB);

	pRGB.rewind();
		
	System.out.print("Red:");
	System.out.print(pRGB.get());
	System.out.print("Green:");
	System.out.print(pRGB.get());
	System.out.print("Blue:");
	System.out.print(pRGB.get());
[/s]

avm1979

Part of the problem is bytes are always signed in java.  That's why you're getting negative values when you print them out - the bits in the byte are correct, they're just getting interpreted as a signed value when you print.

Try doing System.out.print((int)(pRGB.get() & 0xff)) - that should show you the actual unsigned values you're getting from glReadPixels.

ParticleSwarm

Quote from: avm1979 on February 28, 2011, 04:08:46
Part of the problem is bytes are always signed in java.  That's why you're getting negative values when you print them out - the bits in the byte are correct, they're just getting interpreted as a signed value when you print.

Try doing System.out.print((int)(pRGB.get() & 0xff)) - that should show you the actual unsigned values you're getting from glReadPixels.

See the update, Thanks!