# Depth sorting 2D textures in a batch with OpenGL ES 2.0

I have a combo of texture atlases and sprite batches in an OpenGLES 2.0 2D game I'm developing which is working well, but I have a problem with depth sorting.

I'm using atlases to reduce the number of texture bind operations, and sprite batches to reduce the number of draw calls and everything is rosy but I've hit a logical problem when it comes to how to arrange the sprites in the game.

Because the whole point of using the atlas together with the batch is to save on bind/draw calls I inherit a limitation that I can't draw sprites in the same batch which have textures across multiple atlases.

This means I have to think carefully about the z ordering of the 2D sprites. If sprite "A" should sit behind sprite "B" then I have to draw sprite A's batch first.. ok fine. The problem arises when there are three sprites, A,B and C where A is behind B and B is behind C but A and C are on the same atlas.

That is,

Atlas 1
---------
| A | C |
---------

Atlas 2
-----
| B |
-----

Scene
-----------------------
[CAMERA] -> C -> B -> A


Now obviously I could achieve this with multiple bind/batch operations but that kind of defeats the purpose of having it in the first place. Ideally I don't want to have to think about which sprite is on which atlas and just change the 'z' value for the sprite.

I experimented with enabling GL_DEPTH_TEST but most of my sprites use textures with some level of transparency so this won't work for me.

Is there a "standard" approach to this? Or have I painted myself into a corner I should never have?

• There is a similar problem with an answer here: gamedev.stackexchange.com/questions/40793/… but this won't work as I have transparency in the textures to the depth test will not work. – Jason Feb 11 '13 at 1:05
• "Now obviously I could achieve this with multiple bind/batch operations but that kind of defeats the purpose of having it in the first place." Depending on how many sprites you were drawing, 3 draw calls is still better than hundreds. Alternatively, put sprite "B" on the same atlas as A and C if possible. – Tetrad Feb 11 '13 at 17:35
• Yeah, I think I reached the same conclusion regarding multiple draw calls. I think I'll end up just coding it so it can deal with cross-atlas draws but log this event as an optimization opportunity. Thanks – Jason Feb 11 '13 at 18:27