
// This is the last step of the distance transform.
// The red channel returns the same as in the input tex_0
// The green channel returns the distance transform.
// The blue and alpha channels returns the pixel coordinate of the closest obstacle.
// The input for tex_0 is generated by PE_DistanceTransform_Reset from the red channel.

// The pixel offset must be stored before given to the length function because of a bug in the HLSL compiler
#define SAMPLE_MIN(X,Y) \
	Offset = float2(X,Y); \
	NewPixel = tex_0.Sample( samClampedConstant, (PixelPos + Offset) / Dimensions ); \
	NewDistance = NewPixel.g + length(Offset); \
	if (NewDistance < BestDistance) { \
		BestDistance = NewDistance; \
		ClosestObstacle = NewPixel.ba; \
	}

float4 PS( VS_to_PS input) : SV_Target {
	float4 Original = tex_0.Sample( samClampedConstant, PixelPos / Dimensions );
	float4 NewPixel;
	float2 Offset;
	float BestDistance = Original.g;
	float NewDistance;
	float2 ClosestObstacle = Original.ba;
	
	//  xxx
	// xxxxx
	// xx xx
	// xxxxx
	//  xxx
	SAMPLE_MIN(-2.0f,-1.0f)
	SAMPLE_MIN(-2.0f,0.0f)
	SAMPLE_MIN(-2.0f,1.0f)
	SAMPLE_MIN(-1.0f,-2.0f)
	SAMPLE_MIN(-1.0f,-1.0f)
	SAMPLE_MIN(-1.0f,0.0f)
	SAMPLE_MIN(-1.0f,1.0f)
	SAMPLE_MIN(-1.0f,2.0f)
	SAMPLE_MIN(0.0f,-2.0f)
	SAMPLE_MIN(0.0f,-1.0f)
	SAMPLE_MIN(0.0f,1.0f)
	SAMPLE_MIN(0.0f,2.0f)
	SAMPLE_MIN(1.0f,-2.0f)
	SAMPLE_MIN(1.0f,-1.0f)
	SAMPLE_MIN(1.0f,0.0f)
	SAMPLE_MIN(1.0f,1.0f)
	SAMPLE_MIN(1.0f,2.0f)
	SAMPLE_MIN(2.0f,-1.0f)
	SAMPLE_MIN(2.0f,0.0f)
	SAMPLE_MIN(2.0f,1.0f)
	
	return float4(Original.r,BestDistance,ClosestObstacle);
}
