shader_type spatial;
render_mode blend_mix,depth_draw_opaque,cull_disabled, unshaded;

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

uniform vec4 albedo_color : source_color;
uniform sampler2D albedo_texture : source_color;
uniform sampler2D normal_texture : source_color;

uniform bool use_normalmap = false;
uniform bool uncompressNormalMap = true;
uniform bool use_alpha_texture = false;

uniform bool useCustomNormals = true;
uniform float alpha_scissor_threshold :  hint_range(0,1);
uniform float normal_scale :  hint_range(-5,5) = 1;

uniform vec3 uv1_scale = vec3( 1, 1, 1 );
uniform vec3 uv1_offset;

varying vec3 vertexNormal;
varying vec3 vertexTangent;
varying vec3 vertexBinormal;

uniform float binormalMix:hint_range(0,1);

void vertex()
{
	UV = UV * uv1_scale.xy + uv1_offset.xy;
  vertexNormal = localToViewDirection( NORMAL, MODELVIEW_NORMAL_MATRIX );
  vertexTangent = localToViewDirection( TANGENT, MODELVIEW_NORMAL_MATRIX );
  vertexBinormal = cross( vertexNormal, vertexTangent );
  //NORMAL = localToViewDirection( NORMAL, MODELVIEW_NORMAL_MATRIX ); 
}

void fragment()
{
	vec2 base_uv = UV;
	vec4 albedo = texture( albedo_texture, base_uv ) * albedo_color;
	vec4 normal_tex = texture( normal_texture, base_uv );
  vec3 RENDER_NORMAL = useCustomNormals ? vertexNormal : NORMAL;
  
  if ( ! useCustomNormals && ! FRONT_FACING )
  {
    RENDER_NORMAL = - RENDER_NORMAL;
  }
  //ALBEDO = mix( vertexNormal, NORMAL, normalMix );
	// 0.5 + -1.0 == -1.0 + 0.5
	//ALBEDO = vec3(1.0 - NORMAL.y, 1.0 - NORMAL.x, - NORMAL.z)* 0.5;
	if ( use_normalmap )
	{
		vec3 normalmap;
    
    if ( uncompressNormalMap )
    {
      normalmap.xy = normal_tex.xy * 2.0 - 1.0;
		  normalmap.z = sqrt( max( 0.0, 1.0 - dot( normalmap.xy, normalmap.xy ) ) );
    }
    else
    {
      normalmap = normal_tex.xyz * 2.0 - 1.0;
    }
    
    vec3 textureNormal = vertexTangent * normalmap.x + 
                         vertexBinormal * normalmap.y + 
                         vertexNormal * normalmap.z;
                       

		RENDER_NORMAL = normalize( mix( RENDER_NORMAL, textureNormal, normal_scale ) );
    //NORMAL = textureNormal;
	}
  
  
  vec3 rn = vec3( RENDER_NORMAL.x, RENDER_NORMAL.y, RENDER_NORMAL.z ) * 0.5 + 0.5;
	ALBEDO = rn;

	if ( use_alpha_texture )
	{
		ALPHA = albedo.a;
		ALPHA_SCISSOR_THRESHOLD = alpha_scissor_threshold;
	}

}
