<FORWARD>
struct ShaderArgs
{
	float highlightAlpha;
	uint showVisibleOnly;
	float2 padding;
	float4 lowerColorLevel;
	float4 upperColorLevel;
};

constexpr sampler maskIdSampler ( mag_filter::nearest, min_filter::nearest );
constexpr sampler maskStateSampler ( mag_filter::nearest, min_filter::nearest );
constexpr sampler maskColorSampler ( mag_filter::nearest, min_filter::nearest );
</FORWARD>

<FRAGMENT>
  <ARGUMENTS>constant ShaderArgs& shaderArgs [[buffer(2)]], texture2d<uint> maskTexture [[texture(1)]], texture2d<uint> maskSelectionTexture [[texture(2)]], texture2d<float> maskColorTableTexture [[texture(3)]]</ARGUMENTS>
  <BODY>
  //float4 texColor = Texture.sample( Sampler, IN.texCoord );
  if( texColor.r == 0 && texColor.g == 0 && texColor.b == 0 )
		discard_fragment();

	if( OUT.r < shaderArgs.lowerColorLevel.r || shaderArgs.upperColorLevel.r <= shaderArgs.lowerColorLevel.r )
		OUT.r = 0;
	else if( OUT.r > shaderArgs.upperColorLevel.r )
		OUT.r = 1;
	else
		OUT.r = (OUT.r - shaderArgs.lowerColorLevel.r) / (shaderArgs.upperColorLevel.r - shaderArgs.lowerColorLevel.r);
	if( OUT.g < shaderArgs.lowerColorLevel.g || shaderArgs.upperColorLevel.g <= shaderArgs.lowerColorLevel.g )
		OUT.g = 0;
	else if( OUT.g > shaderArgs.upperColorLevel.g )
		OUT.g = 1;
	else
		OUT.g = (OUT.g - shaderArgs.lowerColorLevel.g) / (shaderArgs.upperColorLevel.g - shaderArgs.lowerColorLevel.g);
	if( OUT.b < shaderArgs.lowerColorLevel.b || shaderArgs.upperColorLevel.b <= shaderArgs.lowerColorLevel.b )
		OUT.b = 0;
	else if( OUT.b > shaderArgs.upperColorLevel.b )
		OUT.b = 1;
	else
		OUT.b = (OUT.b - shaderArgs.lowerColorLevel.b) / (shaderArgs.upperColorLevel.b - shaderArgs.lowerColorLevel.b);

	if( shaderArgs.highlightAlpha != 0 || shaderArgs.showVisibleOnly != 0 )
	{
		//uint w = maskTexture.get_width(), h = maskTexture.get_height();
        //ushort2 maskPixelCoord = ushort2( IN.texCoord.x * w, IN.texCoord.y * h );
		//uint maskId = maskTexture.read( maskPixelCoord ).r;
		uint maskId = maskTexture.sample( maskIdSampler, IN.texCoord ).r;
		if( maskId != 0 )
		{
			ushort2 maskPixelCoord = ushort2(maskId & 0xffU, maskId >> 8U);
			//uint objectState = maskSelectionTexture.read( maskPixelCoord ).r;
			float2 maskPixelCoordF = float2(float(maskPixelCoord.x) / maskSelectionTexture.get_width(), float(maskPixelCoord.y) / maskSelectionTexture.get_height());
			uint objectState = maskSelectionTexture.sample( maskStateSampler, maskPixelCoordF ).r;
			if( shaderArgs.showVisibleOnly != 0 && (objectState & 2) == 0 )
				discard_fragment();
			if( objectState & 4 )
			{
				//float3 highlightColor = maskColorTableTexture.read( maskPixelCoord ).rgb;
				float3 highlightColor = maskColorTableTexture.sample( maskColorSampler, maskPixelCoordF ).rgb;
				OUT.rgb = OUT.rgb * (1 - shaderArgs.highlightAlpha) + highlightColor * shaderArgs.highlightAlpha;
			}
		}
	}
</BODY>
</FRAGMENT>
