'How I can apply antialiasing to a 2D grid on a shader?

I have the following fragment shader to draw a grid

#version 450 core

layout(location = 0) in vec2 position;

layout(location = 0) out vec4 fragColor;

layout(binding = 0) uniform ubo
{
  mat4 uCameraView;
  vec4 uGridColor;
  float uTileSize;
  float uGridBorderSize;
};

void main()
{
  vec2 uv = mod(position, uTileSize);
  vec2 border = mod(uv + (uGridBorderSize / 2.0), uTileSize);
  border -= mod(uv - (uGridBorderSize / 2.0), uTileSize);

  if (length(border) > uTileSize - uGridBorderSize)
  {
    fragColor = uGridColor;
  }
  else
  {
    fragColor = vec4(0.0);
  }
}

This works fine until I change the zoom, the issue appears when the camera gets far away and the uGridBorderSize is smaller than a pixel in the screen, then I get this ugly effect, where lines appear and disappear when the zoom changes.

enter image description here

So I wonder, is it possible to apply antialising to this lines so they appear consistently?



Solution 1:[1]

In the end I found this fragment shader that draws antialiased grid lines

void main()
{
  // https://madebyevan.com/shaders/grid/
  vec2 uv = fragCoord / uTileSize;
  vec2 grid = abs(fract(uv - 0.5) - 0.5) / fwidth(uv);
  float line = (min(grid.x, grid.y) * uGridBorderSize) / uScaleFactor;
  float color = 1.0 - min(line, 1.0);
  fragColor = uGridColor * color;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ellipticaldoor