######################################################
#
# BGE_NMap.py Blender 2.45
#
# Clark R Thames
# Released under Creative Commons License
#
# Tutorial for using this shader can be found at
#
# www.tutorialsforblender3D.com
#
######################################################
# define the main program
def MainProgram():
# Get the current controller
controller = GameLogic.getCurrentController()
# get the object
obj = controller.getOwner()
# get first mesh
index = 0;
mesh = obj.getMesh(index)
# can be more than one mesh on object.
while mesh != None:
# can be more than one material on mesh
for mat in mesh.materials:
# 'Use Blender Materials' checked?
if hasattr( mat, 'getMaterialIndex') == True:
#Get shader envelope
shader = mat.getShader()
# shader envelope created?
if shader != None:
# set the shader
shader.setSource(VertexProgram, FragmentProgram, True)
# set NormalMap and ColorMap
shader.setSampler('NormalMap', 0)
shader.setSampler('ColorMap', 1)
# change Blender matrix to OpenGl
shader.setUniformDef('mvi', GameLogic.MODELVIEWMATRIX_INVERSE)
# look for another mesh
index = index + 1
mesh = obj.getMesh(index)
################ End Main Program
###################### OpenGL glsl shader
VertexProgram = """
// from main program
uniform mat4 mvi;
// pass to FragmentProgram
varying vec3 lightVec;
varying vec3 viewVec;
void main()
{
// mvi--major row to major column. Use point light
lightVec = vec3((mvi * gl_LightSource[0].position).xyz - gl_Vertex.xyz);
// TBN Matrix--converting to tangent space
vec3 tangent = vec3(1.0, 0.0, 0.0);
vec3 binormal = vec3(0.0, 1.0, 0.0);
mat3 TBNMatrix = mat3(tangent, binormal, gl_Normal);
// Convert lightVec to tangent space.
lightVec = normalize(lightVec * TBNMatrix);
// get viewVec
viewVec = normalize(-gl_Vertex.xyz);
// OpenGL glsl stuff
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = ftransform();
}
"""
FragmentProgram = """
// from main program
uniform sampler2D ColorMap;
uniform sampler2D NormalMap;
// from VertexProgram
varying vec3 lightVec;
varying vec3 viewVec;
void main()
{
// Get color from color map
vec3 color = (texture2D(ColorMap, gl_TexCoord[0].st).xyz);
// get normals from normal map
vec3 normals = (texture2D(NormalMap, gl_TexCoord[0].st).xyz);
// fix normals
normals = normalize((normals - 0.5) * 2.0);
// get reflect vector
vec3 reflectVec = reflect(-lightVec, normals);
// get diffuse
float diffuse = max(dot(lightVec, normals), 0.0);
float spec = 0.0;
// spec only on lit parts
if (diffuse > 0.0)
{
// get spec
float spec = max(dot(reflectVec, viewVec), 0.0);
// spec highlights size
spec = pow(spec, 10.0);
}
// set diffuse and spec strength
float diffuseStrength = 0.7;
float specStrength = 0.2;
// get light intensity
float intensity = diffuseStrength * diffuse + specStrength * spec;
// set color intensity and add ambient light of 0.2
vec3 texture = vec3(color * intensity) + vec3(color * 0.2);
// Use it
gl_FragColor = vec4(texture, 1.0);
}
"""
################### Run Program
MainProgram()