Search code examples
androidopengl-estexturesopengl-es-2.0android-bitmap

Load huge texture in parts in OpenGL ES 2.0


I'd like to load a huge bitmap as a texture into the graphics card's memory on Android, in OpenGL ES 2.0, to be used as a texture atlas, in the biggest size possible. My device has a maximum texture size of 8192x8192.

I know that I can load a bitmap as a texture the following way:

// create bitmap
Bitmap bitmap = Bitmap.createBitmap(8192, 8192, Bitmap.Config.ARGB_8888);
{ // draw something
    Canvas c = new Canvas(bitmap);
    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
    p.setColor(0xFFFF0000);
    c.drawCircle(4096, 4096, 4096, p);
}
// load as a texture
GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);

However, (not surprisingly) I get a java.lang.OutOfMemoryError when trying to create a bitmap of this size.

Is it possible to load it in parts? As it's a texture atlas, it could be assembled from smaller bitmaps. I looked at the texSubImage2D function, but I don't understand where you would initialize the full-sized texture, or provide the size of the full texture beforehand.


Solution

  • On the GL side you need to allocate the full storage, and then patch it.

    Allocate storage using glTexImage2D() with a null value for the data parameter. Upload patches using glTexSubImage2D().

    Note that this still requires 256MB of memory, so on many budget devices you'll still get an OOM ...