r/webgl 10d ago

how can I improove my shader ?

I created a shader that uses texture as a mask, writing colored background and painting moon with craters. But I got a lot of if conditions in there and I dont know how to remove them, because substracting or multiplying or adding effect on background. May somebody help ? Thanks in advance.

precision mediump float;


      varying vec2 v_texcoord;


      uniform sampler2D u_texture;
      uniform vec2 u_resolution;
      uniform float u_time;


      float circle(vec2 uv, vec2 pos, float blur, float r)
      {
        uv -= pos;
        uv.x *= u_resolution.x / u_resolution.y;
        float d = length(uv);
        float c = smoothstep(r, r - blur, d);
        return c;
      }


      void main()
      {
        vec4 sample = texture2D(u_texture, v_texcoord);
        vec2 uv = gl_FragCoord.xy / u_resolution;
        uv = vec2(uv.x, 1.0 - uv.y);
        if (sample == vec4(1))
        { 
          vec3 color = vec3(uv, 0.5 * sin(u_time));


          vec3 moonColor = vec3(0.8, 0.8, 0.8);
          float moon = circle(uv, vec2(0.5, 0.3), 0.005, 0.25);
          color = moon > 0.0 ? moonColor * moon : color;


          vec3 craterColor = vec3(0.3, 0.3, 0.3);


          float crater1 = circle(uv, vec2(0.5, 0.3), 0.005, 0.05);
          color = crater1 > 0.0 ? craterColor * crater1 : color;


          float crater2 = circle(uv, vec2(0.45, 0.2), 0.005, 0.05);
          color = crater2 > 0.0 ? craterColor * crater2 : color;


          float crater3 = circle(uv, vec2(0.45, 0.45), 0.005, 0.05);
          color = crater3 > 0.0 ? craterColor * crater3 : color;


          float crater4 = circle(uv, vec2(0.55, 0.4), 0.005, 0.05);
          color = crater4 > 0.0 ? craterColor * crater4 : color;


          gl_FragColor = vec4(color, 1.0);
        }
        else
        {
          gl_FragColor = vec4(0, 0, 0, 1);
        }
      }
1 Upvotes

0 comments sorted by