""" S P L A T  S H A D E R
The purpose of this shader is blend two textures based on
red,green,or blue vertex color channel(not the color).
It accepts two textures to blend, and a detail texture.
which is multiplied over the blend.
Add a material to a game object and set three textures,
the first two to blend and the third to be the detail.
The lighter the vertex color is, the more the second texture will blend through.
"""
import GameLogic
objects = GameLogic.getCurrentScene().getObjectList()

# -------------------------------------
ShaderObjects = [objects['OBBase'], objects['OBTop'], objects['OBLand']]
MaterialIndexList = [0]
splat_1 = ['splat_1',0]
splat_2 = ['splat_2',1]
splat_d = ['splat_d',2]
channel = 0
# -------------------------------------

VertexShader = """
varying vec4 splat_val;
varying vec2 texco;

void main(){
	splat_val = gl_Color;
	texco = gl_MultiTexCoord0.st;
		
	gl_Position = ftransform();
}
"""

FragmentShader = """
varying vec4 splat_val;
varying vec2 texco;

const int channel = %i;

uniform sampler2D splat_1;
uniform sampler2D splat_2;
uniform sampler2D splat_d;

void main(){
	vec4 s1 = texture2D(splat_1, texco);
	vec4 s2 = texture2D(splat_2, texco);
	vec4 d  = texture2D(splat_d, texco*4.0);
	vec4 f;
	
	if(channel == 0) // r
		f = mix(s1, s2, abs(splat_val.r));

	if(channel == 1) // g
		f = mix(s1, s2, abs(splat_val.g));
	
	if(channel == 2) // b
		f = mix(s1, s2, abs(splat_val.b));

	gl_FragColor = d*f;
}
"""%channel

def MainLoop ():
	# for each object
	for obj in ShaderObjects:

		mesh_index = 0
		mesh = obj.getMesh(mesh_index)

		while mesh != None:

			for mat in mesh.materials:
				
				# regular TexFace materials do NOT have this function
				if not hasattr(mat, "getMaterialIndex"):
					return
				
				mat_index = mat.getMaterialIndex()

				# find an index				
				found = 0
				for i in range(len(MaterialIndexList)):
					if mat_index == MaterialIndexList[i]:
						found=1
						break
				if not found: continue

				shader = mat.getShader()
				if not shader.isValid():

					shader.setSource(VertexShader, FragmentShader,1)
					shader.setNumberOfPasses(1)
				shader.setSampler(splat_1[0],splat_1[1])
				shader.setSampler(splat_2[0],splat_2[1])
				shader.setSampler(splat_d[0],splat_d[1])
				
			mesh_index += 1
			mesh = obj.getMesh(mesh_index)


# -------------------------------------
MainLoop()
# -------------------------------------