#pragma language glsl3
#ifdef VERTEX

vec4 position(mat4 transform_projection, vec4 vertex_position) {
  return transform_projection * vertex_position;
}

#endif

#ifdef PIXEL


uniform sampler2D gbuffer_diffuse;
uniform sampler2D gbuffer_position;
uniform sampler2D gbuffer_normal;
uniform sampler2D gbuffer_probed;
uniform sampler2D gbuffer_depth;

uniform float ambientLight;
uniform vec3 ambientColor;
uniform float toon = 0;
uniform float toonWidth = 0;
mat4 bias = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0,
                 0.5, 0.5, 0.5, 1.0);
// Standard sample locations from Vulkan spec
    const vec2 samples[16] = vec2[16](
    vec2(.0625, .0625),
    vec2(-.0625, -.1875),
    vec2(-.1875, .125),
    vec2(.25, -.0625),
    vec2(-.3125, -.125),
    vec2(.125, .3125),
    vec2(.3125, .1875),
    vec2(.1875, -.3125),
    vec2(-.125, .3125),
    vec2(0, -.4375),
    vec2(-.25, -.375),
    vec2(-.375, .25),
    vec2(-.5, 0.),
    vec2(.4375, -.25),
    vec2(.375, .4375),
    vec2(-.4375, -.5)
    );
 
 uniform float zNear = 0.0001;
uniform float zFar = 4.0;
float linearDepth(float depthSample)
{
    depthSample = 2.0 * depthSample - 1.0;
    float zLinear = 2.0 * zNear * zFar / (zFar + zNear - depthSample * (zFar - zNear));
    return zLinear;
}
float depthSample(float linearDepth)
{
    float nonLinearDepth = (zFar + zNear - 2.0 * zNear * zFar / linearDepth) / (zFar - zNear);
    nonLinearDepth = (nonLinearDepth + 1.0) / 2.0;
    return nonLinearDepth;
}

vec4 effect(vec4 color, sampler2D gbuffer_light, vec2 textureCoords, vec2 screen_coords) {
  vec2 coord = screen_coords / love_ScreenSize.xy;
  vec4 position = Texel(gbuffer_position, textureCoords);
  vec4 diffuse = Texel(gbuffer_diffuse, textureCoords);
  vec4 probed= Texel(gbuffer_probed,   textureCoords);
  vec3 normal= Texel(gbuffer_normal,   textureCoords).xyz*2-vec3(1);
  float depth= linearDepth(Texel(gbuffer_depth,   textureCoords).r);
  vec3 light = Texel(gbuffer_light, textureCoords).rgb;

  float test_n = 0;
  float test_d = 0;
  vec2 offset = vec2(toonWidth*4+0.8) / love_ScreenSize.xy;
  for (int i = 0; i < 16; i++) {
    vec3 normal2 = Texel(gbuffer_normal, textureCoords+samples[i]*offset).xyz*2-vec3(1);
    test_n += (dot(normal,normal2));
    test_d += abs(depth-linearDepth(Texel(gbuffer_depth, textureCoords+samples[i]*offset).r));
  }
  // edge = edge>0.95 ? 1 : 0;
  float edge = ((1-test_d)*test_n)/16;
  edge = edge>0.95 ? 1 : 1-toon;
  if (diffuse.a == 0 && edge==1) {
    discard;
  }

  if (0<1){
      // return vec4(vec3(edge),1);
      // return vec4(color.rgb,(test/16.0));
  }
 
  vec4 result = vec4(edge * ambientLight * ambientColor * diffuse.rgb + diffuse.rgb * light , 1);
  return result;
}

#endif
