# Drawing a grid over a terrain using a mesh - Shader Depth and Z-Buffer

What I'm trying to achieve is rendering a (huge) tile grid over a terrain. For that I'm using a generated mesh of quads, one for every tile, whose vertices Y value is the same of the terrain to "shape" this mesh like the terrain.

My problem is that this mesh should be rendered always over the terrain, keeping every other object rendered on top of this grid. As you should guess I'm a beginner in shader programming. So here are some caps:

Rendering the mesh with simple unlit transparent shader (with ZTest, ZWrite and Cull values):

As you can see there are problems with the z-fighting, when the grid should always be drawn on top. Rising the terrain won't solve it, since the terrain have lots of "peaks" and the quads should be planes with lots of vertex to be able to follow the terrain (or rising a lot the grid which will cause it to float over the terrain).

Changing the ZTest to Always:

Here I've the problem that the tiles behind the mountains are still drawn when they shouldn't, which make sense since it's ignoring z-ordering, and therefore rendering over other objects too.

I've tried using a another shader pass to first write to the z buffer to avoid rendering the tiles behind the mountains with no success. I guess I'm missing something related to the terrain shader, but I have no clue what it may be.

Any help will be much appreciated.

You can use a pixel shader for this.

Pass the size of a single grid square and the radius of a circle to the shader, divide it by the gridSize, round it then multiply by gridSize to get the closest grid point. If the distance between the current fragment and the closest point is less than or equal to the radius, then it's inside the circle:

gX = round(fragX / gridSize) * gridSize
gY = round(fragY / gridSize) * gridSize
d = sqrt((x - gX)^2 + (y - gY)^2)