""" T O O N  S H A D E R
"""
import GameLogic
objects = GameLogic.getCurrentScene().getObjectList()

# -------------------------------------
# change these values to suite your needs
ShaderObjects = [ objects["OBBlendo"]]
MaterialIndexList = [ 0,1 ]
# [size, value] 
Cell1	= [0.9, 0.1] # adding first
Cell2	= [0.5, 0.9] # multiply
Cell3	= [0.3, 0.8] # ...
Cell4	= [0.2, 0.3] # ...
# -------------------------------------

VertexShader = """
varying vec3 light_vec[2];
varying vec4 diff[2];

varying vec3 normal_vec;
varying vec4 material_color;

void main(){
	vec3 vert =(gl_ModelViewMatrix * gl_Vertex).xyz;
	light_vec[0] = (gl_LightSource[0].position).xyz - vert;
	light_vec[1] = (gl_LightSource[1].position).xyz - vert;

	normal_vec = gl_NormalMatrix *gl_Normal;
	material_color = gl_Color;
	material_color *= gl_LightSource[0].diffuse;
	material_color *= gl_LightSource[1].diffuse;
	gl_Position = ftransform();
}
"""

FragmentShader = """
const vec4 cell_size = vec4(%f, %f, %f, %f);
const vec4 cell_value = vec4(%f, %f, %f, %f);

varying vec3 light_vec[2];
varying vec4 diff[2];

varying vec3 normal_vec;
varying vec4 material_color;

void main(){
	vec3 n = normalize(normal_vec);
	vec4 color = material_color;

	for(int i=0; i<2; i++) {
		vec3 l = normalize(light_vec[i]);
		float ndotl = clamp(dot(n,l), 0.0, 1.0);
		
		// cell 1  add for a brighter cell	
		if ( ndotl > cell_size[0] )
			color += cell_value[0];

		// cell 2  multiply for each cell.A darker cell 
		else if ( ndotl >cell_size[1] )
			color *= cell_value[1];

		// cell 3
		else if ( ndotl >cell_size[2] )
			color *= cell_value[2];
		// cell 4
		else 
			color *= cell_value[3];
	}
	
	gl_FragColor = color;
}
"""%(\
	Cell1[0], Cell2[0],Cell3[0],Cell4[0],\
	Cell1[1], Cell2[1],Cell3[1],Cell4[1],\
	)

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)

			mesh_index += 1
			mesh = obj.getMesh(mesh_index)


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