In this post we will make a shader that displays a texture. We will pass the texture information from the Unity Editor to the shader via shader properties and a special type of glsl variables, uniforms.
The first thing to do is to add an option to select a texture from Inspector view. To do so, we will modify the Properties code from the previous post. It will become
Properties
{
// This allows to choose the texture from the Editor
_MainTex ("Base (RGB)", 2D) = "white" {}
}
Ok,now if we select the shader in the inspector, we can choose a texture. The necessary info to display a texture is the texture itself and uv coordinates of each vertice. To inform the shader about the relation between texture coordinates and vertices uv we will change the Vertex shader code as follows :
#ifdef VERTEX
// varying is a special type of variable in glsl
// that lets you pass data from the Vertex to
// the Fragment shader
varying vec2 the_uv;
void main()
{
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
// Access the first texture unit and retrieve the texture coordinates
// that correspond to the uv coordinates of the given vertice
the_uv = gl_MultiTexCoord0.st;
}
#endif
Now we should pass the texture and the texture coordinates to the Fragment shader. Modify the Fragmentshader as follows :
#ifdef FRAGMENT
// Receive texture data from Unity Editor
uniform sampler2D _MainTex;
// Receive data from the Vertex to
// the Fragment shader
varying vec2 the_uv;
void main()
{
// The pixel color will correspond
// to the uv coords of the texture
// for the given vertice, retrieved
// by the
gl_FragColor = texture2D(_MainTex, the_uv);
}
#endif
So the complete code of the shader will be :
Shader "simple_Texture_Shader"
{
Properties
{
// This allows to choose the texture from the Editor
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader
{
Tags { "Queue" = "Geometry" }
Pass
{
GLSLPROGRAM
#ifdef VERTEX
// varying is a special type of variable in glsl
// that lets you pass data from the Vertex to
// the Fragment shader
varying vec2 the_uv;
void main()
{
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
// Access the first texture unit and retrieve the texture coordinates
// that correspond to the uv coordinates of the given vertice
the_uv = gl_MultiTexCoord0.st;
}
#endif
#ifdef FRAGMENT
// Receive texture data from Unity Editor
uniform sampler2D _MainTex;
// Receive data from the Vertex to
// the Fragment shader
varying vec2 the_uv;
void main()
{
// The pixel color will correspond
// to the uv coords of the texture
// for the given vertice, retrieved
// by the Vertex shader through varying vec2 the_uv
gl_FragColor = texture2D(_MainTex, the_uv);
}
#endif
ENDGLSL
}
}
}
And that is all ! References from the first part still apply.