Switching Shaders - Painter's Algorithm

Hello there,

I’m using libGdx but feel free to answer generally.

Let’s say you have a 2D game where sprites are sorted by their y-coordinate, so sprites with a lower y-coordinate are “in the foreground” and get rendered over sprites with a higher y-coordinate. (assuming the y-coordinate is pointing upward)

Now let’s say i want to render trees in two steps, first i render the stump and then the leaves on top of it with both of these sprites having their separate shaders (let’s call it stumpShader and leaveShader). Now in a 3D environment this wouldn’t be an issue: First i bind the stumpShader and render all the stumps, and then i bind the leaveShader and render all the leaves. Because of these neat thing called z-buffer i don’t need to worry about my trees being rendered in a wrong “order”.

But in a 2D environment where i just “paint” trees over other trees i do have to worry about that, because if i render all the stumps first, and then the leaves on the stumps, some leaves will be rendered over stumps that they should actually be behind of. So that way i’m forced to render stump, leaves, stump, leaves, stump, leaves… and constantly switch between stumpShader and leaveShader.

As far as i know switching shaders is pretty costly and you should do it as sparingly as possible, so this is obviously not an option.

So my question is what do i do in this scenario?
Can i somehow utilize the z-buffer in this kind of 2D setup?
I guess i could write one shader that takes care of both things, but I’ve also heard that if statements should be avoided in glsl.

Thanks!