0
\$\begingroup\$

I'm making a simple 2D renderer and I want to avoid redrawing as much as possible. My Vertex layout has the 2d position and a float depth value.

I want to assign a depth value to each of them after ordering to render them using depth testing and avoid overdraw.

So it will be like this:

  1. Order all the sprites to draw by Y order. (isometric game)
  2. Set a depth value to each of them (like an incrementing int)
  3. Render them.

How can I achieve that?

I read something about gl_FragDepth but I don't know the range of values that I have to set there. Is it from 0 to 1?

These are my vertex/fragment shaders:

#version 330
layout(location=0) in vec2 v_position;
layout(location=1) in vec4 v_color;
layout(location=2) in vec2 v_texcoord;
layout(location=3) in float v_depth;
out vec4 color;
out vec2 uv;
flat out float depth;
void main() {
  gl_Position = vec4(v_position,0,1);
  color = v_color;
  depth = v_depth;
  uv = v_texcoord;
}

#version 330
uniform sampler2D tex0;
flat in float depth;
in vec4 color;
in vec2 uv;
out vec4 out_color;
void main() {
   gl_FragDepth = depth;
   out_color = texture(tex0, uv) * color;
}
\$\endgroup\$
1
  • \$\begingroup\$ Why would you do this in the fragment shader if the depth is determined earlier in the process, at the y-sorting stage? Setting a depth value in the shader disables early z rejection and slows down your rendering, so this is likely not the right solution to your problem. Note that if your sprites have alpha translucency (like soft antialiased edges instead of hard stairstep jaggies along their outlines), that does not play well with z rejection, and can lead to visible fringing or occluded objects disappearing if you try to z-test against translucent occluders. \$\endgroup\$
    – DMGregory
    Commented Oct 31, 2023 at 18:05

0

You must log in to answer this question.

Browse other questions tagged .