shader_type spatial;
render_mode blend_mix, depth_draw_never, cull_back, diffuse_burley, specular_schlick_ggx;

#include "res://addons/rokojori_action_library/Runtime/Shading/Library/Transform.gdshaderinc"
#include "res://addons/rokojori_action_library/Runtime/Shading/Library/Math.gdshaderinc"

uniform vec4 albedo : source_color;
uniform sampler2D albedoTexture: source_color, filter_linear_mipmap, repeat_enable;
uniform float albedoUV;
uniform float albedoFadeDistance;

uniform sampler2D opacity : filter_linear_mipmap, repeat_enable;
uniform float opacityVarianceScale = 1.0;
uniform float opacityScale = 1.0;
uniform float opacityTreshold = 0.5;

uniform float opacityVarianceScale2 = 1.0;
uniform float opacityScale2 = 1.0;
uniform float opacityTreshold2 = 0.5;
uniform float opacity2Amount: hint_range( 0.0, 1.0 ) = 0.5;

uniform float roughness : hint_range( 0.0, 1.0 );
uniform float specular : hint_range( 0.0, 1.0 );
uniform float metallic : hint_range( 0.0, 1.0 );

uniform sampler2D texture_normal : hint_roughness_normal, filter_linear_mipmap, repeat_enable;
uniform float normal_scale : hint_range(0, 2);
uniform float normal_uv = 1.0;

uniform vec2 mapSize;
uniform vec2 mapCenter;

uniform float fadeOutMax;
uniform float fadeOutStart;

varying vec2 positionUV;

void vertex() 
{  
  VERTEX += CAMERA_POSITION_WORLD * vec3( 1.0, 0.0, 1.0);

  positionUV = UV;

	UV = worldUVfromLocalXZ( VERTEX, mapCenter, mapSize, MODEL_MATRIX ); 
}

void fragment()  
{
	vec2 uv = UV;

  float d = length( positionUV - vec2( 0.5, 0.5 ) );
  float fading = 1.0 - clamp01( d / 0.5 );
  float albedoFading = 1.0 - clamp01( d / albedoFadeDistance );
  vec4 sampledAlbedo = texture( albedoTexture, uv * albedoUV );
	ALBEDO = albedo.rgb * mix( vec3( 1, 1, 1 ), sampledAlbedo.rgb, albedoFading );

	METALLIC = metallic;
	SPECULAR = specular;
	ROUGHNESS = roughness;
  
  float sampledOpacity = texture( opacity, uv * opacityVarianceScale ).r;
  sampledOpacity = ( sampledOpacity - opacityTreshold ) * opacityScale + opacityTreshold;
  sampledOpacity = clamp01( sampledOpacity );
  
  float sampledOpacity2 = texture( opacity, uv * opacityVarianceScale2 ).r;
  sampledOpacity2 = ( sampledOpacity2 - opacityTreshold2 ) * opacityScale2 + opacityTreshold2;
  sampledOpacity2 = mix( 1, clamp01( sampledOpacity2 ), opacity2Amount );
  
  
  
	NORMAL_MAP = texture( texture_normal, uv * normal_uv ).rgb;
	NORMAL_MAP_DEPTH = normal_scale;

	ALPHA *= albedo.a * sampledOpacity * sampledOpacity2 * mix( 1, sampledAlbedo.a, albedoFading ) * fading;
}
