
#ifndef MAPPING_TRIPLANAR_H
#define MAPPING_TRIPLANAR_H

vec4 mapping_triplanar(sampler2D sampler, vec3 p, vec3 n, float scale)
{
	vec3 coords = p;
	vec3 blending = abs(n);
	blending = normalize(max(blending, 0.00001)); // Force weights to sum to 1.0
	float b = (blending.x + blending.y + blending.z);
	blending /= vec3(b);

	vec4 xaxis = texture(sampler, coords.yz * scale);
	vec4 yaxis = texture(sampler, coords.xz * scale);
	vec4 zaxis = texture(sampler, coords.xy * scale);
	vec4 tex = xaxis * blending.x + yaxis * blending.y + zaxis * blending.z;
	return tex;
}

vec3 mapping_triplanar_normal(sampler2D sampler, vec3 p, vec3 n, float scale)
{
	vec3 coords = p;
	vec3 blending = abs(n);
	blending = normalize(max(blending, 0.00001)); // Force weights to sum to 1.0
	float b = (blending.x + blending.y + blending.z);
	blending /= vec3(b);

	vec3 axis_sign = sign(n);

	vec3 xaxis = texture(sampler, coords.zy * scale).rgb * 2.0 - 1.0;
	vec3 yaxis = texture(sampler, coords.xz * scale).rgb * 2.0 - 1.0;
	vec3 zaxis = texture(sampler, coords.xy * scale).rgb * 2.0 - 1.0;
	
	xaxis.z *= axis_sign.x;
	yaxis.z *= axis_sign.y;
	zaxis.z *= axis_sign.z;

	vec3 tex = normalize(xaxis.zyx * blending.x + yaxis.xzy * blending.y + zaxis.xyz * blending.z);
	return tex;
}

#endif