Using GLSL to Make a Smooth Reference Mesh on a Plane

I am trying to write a GLSL fragment shader that displays a reference mesh on a flat ground plane. I am using BabylonJS to build a WebGL application.

The code can be seen here:

http://www.babylonjs.com/cyos/#IBHRN#2

#extension GL_OES_standard_derivatives : enable

precision highp float;

varying vec2 vUV;

void main(void) {
    float divisions = 10.0;
    float thickness = 0.01;
    float delta = 0.05 / 2.0;

    float x = fract(vUV.x / (1.0 / divisions));
    float xdelta = fwidth(x) * 2.5;
    x = smoothstep(x - xdelta, x + xdelta, thickness);

    float y = fract(vUV.y / (1.0 / divisions));
    float ydelta = fwidth(y) * 2.5;
    y = smoothstep(y - ydelta, y + ydelta, thickness);

    float c = clamp(x + y, 0.1, 1.0);

    gl_FragColor = vec4(c, c, c, 1.0);
}

      

The result is not very smooth and I'm wondering how I can get rid of the ridges in the lines and end up with excellent, smooth lines.

GLSL fragment shader result

+3


source to share


1 answer


This piece of shader code should work as expected:

#extension GL_OES_standard_derivatives : enable

precision highp float;

varying vec2 vUV;

void main(void) {
    float divisions = 10.0;
    float thickness = 0.04;
    float delta = 0.05 / 2.0;

    float x = fract(vUV.x * divisions);
    x = min(x, 1.0 - x);

    float xdelta = fwidth(x);
    x = smoothstep(x - xdelta, x + xdelta, thickness);

    float y = fract(vUV.y * divisions);
    y = min(y, 1.0 - y);

    float ydelta = fwidth(y);
    y = smoothstep(y - ydelta, y + ydelta, thickness);

    float c =clamp(x + y, 0.0, 1.0);

    gl_FragColor = vec4(c, c, c, 1.0);
}

      

I added the expression



x = min(x, 1.0 - x);

      

so that the x (and also y) values ​​are symmetric around the centers of the edges. Since the original code directly used the output of the "fract" function, it jumped between high and low values ​​around the center of the edges, which created sharp corners.

+2


source







All Articles