0
\$\begingroup\$

I want to read a texture pixels from texture id (associated with some FBO) to bitmap object in opengl (opentk) in c#
But it throws an exception says:

System.AccessViolationException occurred
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=OpenTK

The code:

public Bitmap GetTexture(int AttachmentIndex)
        {
            if (AttachmentIndex > fbo_colorBuffer.Count - 1)
                throw new IndexOutOfRangeException();

            Bitmap bitmap = new Bitmap(width, height);
            BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            BindToRead(ReadBufferMode.ColorAttachment0 + AttachmentIndex);
            GL.ReadPixels(0, 0, width, height, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float, bits.Scan0);
            bitmap.UnlockBits(bits);

            return bitmap;
        }

public void BindToRead(ReadBufferMode Mode)
        {
            GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, fbo_id);
            GL.ReadBuffer(Mode);
        }
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You're attempting to write past the end of a buffer.

First of all, you're specifying your bitmap with PixelFormat.Format32bppRgb - this is a 32 bit-per-pixel format with 8 bits for each of R, G and B and the remaining 8 unused. Documentation link.

Then when you do the readback you read as PixelFormat.Rgb and PixelType.Float. This is a 96 bit-per-pixel format with each of R, G and B being a 32-bit float.

So the image data you read back overruns the buffer you have specified to read back into.

To fix, change one of them to use the same format as the other.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks, now I'm understanding the problem, but I'm storing the color data as RGB 32-bit floating point as an internal format for the texture, so what is the matching format for bitmap object? \$\endgroup\$
    – O-BL
    Commented Jun 17, 2017 at 20:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .