#version 330

uniform vec4 lumpos;
uniform vec3 directional;
uniform int objectId;

uniform sampler2D myTexture;
uniform int hasTexture;
uniform vec4 diffuse_color;
uniform vec4 specular_color;
uniform vec4 ambient_color;
uniform vec4 emission_color;
uniform float shininess;

in vec2 gsoTexCoord;
in vec3 gsoNormal;
in vec4 gsoModPosition;
flat in float isGrass;
in float gHeight;
in vec2 grassUV;
out vec4 fragColor;

// Source - https://stackoverflow.com/q/12964279
// Posted by Grumdrig, modified by community. See post 'Timeline' for change history
// Retrieved 2026-05-07, License - CC BY-SA 3.0
float rand(in vec2 co){
  return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

void main(void) {
  /* fragColor = vec4(rand(gl_FragCoord.xy)); */
  /* //fragColor = vec4(grassUV, 0.0, 1.0); */
  /* return; */
  if(isGrass == 1.0){
    vec2 randCoord = floor(grassUV * 15.0)/15.0;
    if(rand(randCoord) < gHeight/20.0)
      discard;
  }
  vec3 Ld = normalize(directional);
  float diffuse = clamp(dot(-normalize(gsoNormal), Ld), 0.0, 1.0);
  
  vec4 specularReflection = specular_color * pow(max(0.0, dot(normalize(reflect(-Ld, gsoNormal)), normalize(vec3(-gsoModPosition)))), shininess);
  
  vec4 diffuseReflection = ambient_color * 0.5 + diffuse_color * diffuse;
  fragColor = diffuseReflection + specularReflection;
  if(hasTexture != 0)
    fragColor *= texture(myTexture, gsoTexCoord);
  if(isGrass != 0.0) {
    fragColor *= clamp((gHeight+5) / 25, 0.0, 1.0);
  }		
}
