BufferOverflowException

So I’ve been following SHC’s OpenGL tutorials and I’m currently on the tutorial concerning textures. The exception occurs at the first buffer.put() call.

[quote]Exception in thread “main” java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Unknown Source)
at java.nio.DirectByteBuffer.put(Unknown Source)
at ffpBasicIntro.Texture.create(Texture.java:48)
at ffpBasicIntro.textures.TexturedRectangle.initialize(TexturedRectangle.java:34)
at ffpBasicIntro.textures.TexturedRectangle.gameLoop(TexturedRectangle.java:41)
at ffpBasicIntro.textures.TexturedRectangle.(TexturedRectangle.java:20)
at ffpBasicIntro.textures.TexturedRectangle.main(TexturedRectangle.java:119)
[/quote]
The docs say:

[quote]Throws:
BufferOverflowException - If this buffer’s current position is not smaller than its limit
[/quote]
I debugged it and the limit is 10000 (100 x 100 image). I tried using both buffer.clear() and buffer.rewind() to reset the position to 0, but neither worked. My code:


int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(),
		null, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(pixels.length);

for (int x = 0; x < image.getWidth(); x++) {
	for (int y = 0; y < image.getHeight(); y++) {
		int pixel = pixels[y * image.getWidth() + x];
		buffer.put((byte) ((pixel >> 16) & 0xFF));
		buffer.put((byte) ((pixel >> 8) & 0xFF));
		buffer.put((byte) (pixel & 0xFF));
		buffer.put((byte) ((pixel >> 24) & 0xFF));
	}
}

buffer.flip();

That’s because you didn’t copy the pixels into the pixel array. Swap your pixels array for this line:

bimg.getRGB(0, 0, bimg.getWidth(), bimg.getHeight(), pixels, 0, bimg.getWidth());

And for the two for loops, the y axis should be first. Really you should just be copying his tutorial word for word, the code works because I’ve used it before.

Also, you should be using power of two textures, yours isn’t.

Oh yeah thanks. The problem was the pixels array. I read somewhere that if the rgbarray was null that it would create a new array, and that is the case, but I didn’t notice that it had to be 4x the size.

Yeah, it has to be 4x the size because you have to hold four components of every pixel; the red green blue and alpha of the pixel.