[gd_resource type="ShaderMaterial" load_steps=4 format=2]

[ext_resource path="res://addons/ref.png" type="Texture" id=1]
[ext_resource path="res://addons/matriax_light.png" type="Texture" id=2]

[sub_resource type="Shader" id=1]
code = "shader_type canvas_item;
uniform sampler2D color_palette;
uniform bool use_color_reference;
uniform sampler2D color_reference;

void fragment(){ 
	float mindiff = 10.0;
	vec3 adjust = vec3(0.3,0.59,0.11);
	vec3 c = textureLod( SCREEN_TEXTURE, SCREEN_UV, 0.0).rgb;
	vec3 shadow_treshold = texture(TEXTURE, UV, 0.0).rgb;
	vec3 color = vec3(1);
	int colors_in_palette = textureSize(color_palette, 0).x;
	if (use_color_reference){
		for (int i = 0; i < colors_in_palette; i++){
			vec3 reference = texture(color_reference, vec2(1.0/float(colors_in_palette)*(float(i) + 0.5) ,0.5)).rgb;
			vec3 lookup = texture(color_palette, vec2(1.0/float(colors_in_palette)*(float(i) + 0.5) ,0.5)).rgb;
			if (length((reference-c)*adjust) < mindiff){
				color = lookup;
				mindiff = length((reference-c)*adjust);
			}
		}
	}else{
		for (int i = 0; i < colors_in_palette; i++){
			vec3 lookup = texture(color_palette, vec2(1.0/float(colors_in_palette)*(float(i) + 0.5) ,0.5)).rgb;
			if (length((lookup-c)*adjust) < mindiff){
				color = lookup;
				mindiff = length((lookup-c)*adjust);
			}
		}
	}
	COLOR.rgb = color;
}"

[resource]
shader = SubResource( 1 )
shader_param/use_color_reference = true
shader_param/color_palette = ExtResource( 2 )
shader_param/color_reference = ExtResource( 1 )
