[SOLVED] GetData([...]) IndexOutOfRangeException on MonoGame.GL

Hi there - first of all I am new here so excuse me if this is the wrong place to ask or if i sound incoherent or overly confused :slight_smile:

I am trying to extract the Color[] data of a 512x512 texture on a Windows OpenGL Project and am running into an “IndexOutOfRange” - Exception.

My GetData call (not called every draw call, dont worry :wink: ) :

Rectangle extractRegion = new Rectangle(x, y, width, height);
Color[] rawData = new Color[width * height];
texture.GetData<Color>(0, extractRegion, rawData, 0, width * height);

The relevant code from Texture2D.OpenGL.cs { Line 284 }

var temp = new T[this.width * this.height];
GL.GetTexImage(TextureTarget.Texture2D, level, this.glFormat, this.glType, temp);
int z = 0, w = 0;

for (int y = rect.Value.Y; y < rect.Value.Y + rect.Value.Height; ++y)
{
    for (int x = rect.Value.X; x < rect.Value.X + rect.Value.Width; ++x)
    {
        data[z * rect.Value.Width + w] = temp[(y * width) + x];
        ++w;
    }
    ++z;
    w = 0;
}

My guess is this might be related to this old issue : https://github.com/MonoGame/MonoGame/issues/2958
It seems this might be due to the texture size (since smaller textures work fine) or rather the max index/length of the array…
Am I missing something incredibly obvious?

Are you sure the rectangle you want to extract is within the texture bounds? And is the surface format of the texture you’re extracting from Color? The MonoGame code should be fine except it doesn’t properly check the format against what you pass as the type parameter to GetData yet.

1 Like

Holy guacamole. I think you just pointed me into the right direction…
Turns out the texture i was extracting from was smaller than my target texture (due to being set to the size to the viewport which was 480 px in height)…

Ah well, sometimes it’s the obvious things - Still other problems, but at least it doesn’t seem like voodoo anymore. This I can work with! Thankyou very much kind sir!

1 Like

MG should throw a better exception in this case. I have an (unfinished) PR up that probably fixes this. Though I haven’t been able to contribute much lately…

1 Like

Either way, you are my hero. I probably would have conjured up some incredibly horrific work-around :wink:
BTW. Am i understanding things correctly that the whole GetData stuff still doesn’t work on IOS?

Edit: Nvm. Seems like some other genius did some magic since my last pull.

Glad I could help :slight_smile:

1 Like