Vertex lighting while preserving vertex colours

Is there a way to get the vertex colours before they are lit in a fragment shader? I’ve painted vertex colours in maya to indicate blending between textures but I want the shader to be vertex lit. When I turn on vertex lighting the vertex colours are overwritten by the lights so I can’t quite use the vertex colours this way. Here’s what I’ve got so far:

Shader "Vertex Blended/Vertex Lit Diffuse"  {

Properties {
    _SpecColor ("Spec Color", Color) = (1,1,1,1)
    _Emission ("Emmisive Color", Color) = (0,0,0,0)
    _Shininess ("Shininess", Range (0.01, 1)) = 0.7
    
    _Diffuse1 ("Diffuse 1 (RGB)", 2D) = "white" {}
    _Diffuse2 ("Diffuse 2 (RGB)", 2D) = "white" {}
    _MixControl ("Mix Control (A)", 2D) = "gray" {}
}
 
Category {
    Blend AppSrcAdd AppDstAdd
    Fog { Color [_AddFog] }
 
    // ------------------------------------------------------------------
    // ARB fragment program
   
    SubShader {
        // Pixel lights
        Pass {
            Name "PPL"
            Tags { "LightMode" = "Pixel" }
            //Lighting On
            Material {
                Specular [_SpecColor]
                Emission [_Emission]
                Diffuse (1,1,1,1)
            } 
CGPROGRAM
#pragma fragment frag
#pragma fragmentoption ARB_fog_exp2
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile_builtin
 
#include "UnityCG.cginc"
#include "AutoLight.cginc"

struct v2f_vertex_blended {
    float2 uv1  : TEXCOORD0;
    float2 uv2  : TEXCOORD1;
    float2 uv3  : TEXCOORD2;
    float4 color  : COLOR;
    float4 diff   : COLOR0;
    float4 spec   : COLOR1;
};
 
uniform sampler2D _Diffuse1;
uniform sampler2D _Diffuse2;
uniform sampler2D _MixControl;
 
float4 frag (v2f_vertex_blended i) : COLOR
{
    half4 col1 = tex2D(_Diffuse1,i.uv1);
    half4 col2 = tex2D(_Diffuse2,i.uv2);
    half4 texcol = lerp(col1, col2, i.color.r);
    return texcol;
    return i.spec;
    half4 c;
	c.xyz = ( texcol.xyz * i.diff.xyz + i.spec.xyz * texcol.a ) * 2;
	c.w = texcol.w * i.diff.w;
	return c;
}
ENDCG             
        }
    }
}
 
FallBack "VertexLit"
 
}

You seem to be expecting three vertex colours: specular and diffuse lighting, as well as baked vertex colour. I think you’ll find that you are only getting one out of the vertex lighting you’ve set up.

I tried playing around with your shader and was able to get separate specular and non-specular colours per-vertex using almost the same method you did. This was news to me, as I thought the reason for lighting and vertex colours’ mutual exclusivity was that there was only one colour per vertex when using fixed function vertex programs. However, I haven’t managed to get baked colours out separately. I don’t know if this is a Shaderlab limitation, or just a limitation of the fixed function pipeline.

The two major things I had to change in your shader to get the right result were adding “SeparateSpecular” and changing “LightMode” to “Vertex”. Vertex lighting doesn’t get set up properly when you try and do it in a Pixel pass.

Shader "VertexLit SeparateSpecular"	{

	Properties {
		_Color ("Main Color", Color) = (1, 1, 1, 1)
		_SpecColor ("Spec Color", Color) = (1,1,1,1)
		_Shininess ("Shininess", Range (0.01, 1)) = 0.7
	}
	SubShader {
		Blend AppSrcAdd AppDstAdd
		Fog { Color [_AddFog] }
		// Vertex lights
		Pass {
			Tags { "LightMode" = "Vertex" }
			Lighting On
			SeparateSpecular On
			Material {
				Diffuse [_Color]
				Ambient [_Color]
				Specular [_SpecColor]
				Shininess [_Shininess]
			}
			CGPROGRAM
				#pragma fragment frag
				#pragma fragmentoption ARB_fog_exp2
				#pragma fragmentoption ARB_precision_hint_fastest

				struct v2f_vertex_blended {
					float4 diff	  : COLOR0;
					float4 spec	  : COLOR1;
				};

				float4 frag (v2f_vertex_blended i) : COLOR
				{
					return (i.spec + i.diff) * 2.0;
				}
			ENDCG
		}
	}
	FallBack "VertexLit"
}

To clarify, when vertex lighting is enabled, and SeparateSpecular is off, you get:

COLOR is all vertex lighting
COLOR0 is all vertex lighting
COLOR1 is black

When SeparateSpecular is on, you get:

COLOR is all non-specular lighting
COLOR0 is all non-specular lighting
COLOR1 is specular lighting only

Turning lighting off is the only way to get access to pure vertex colours (using BindChannels):

COLOR is baked vertex colour
COLOR0 is baked vertex colour
COLOR1 is black

Thanks for those pointers Daniel. I was wondering if there’s some magic invocation we could call from a vertex shader to calculate the vertex lighting taking into account all the lights in the scene.

Unfortunately not that I know of. Perhaps Aras will drop in and confirm.

Hmm I sucked it up and just did the vertex lighting calculations myself by following the tree shader, though I think this is limited to the nearest 4 lights.

That sounds unnecessarily complicated. Are you sure it’s not worth a second pass to do lighting?

How would you do a second pass for lighting? I’m not very familiar with the shaderlab syntax. I tried putting in a second pass and removing my lighting calculation in the previous pass but all I got was my unshaded first pass. I’m not sure I’ll be doing it the 2 pass way though, it seems like a bad way to use my draw calls.

If your first pass just writes the base colour using vertex colours and the two textures, your second pass can use multiplicative blending, and just output the lighting result.

Thanks for the idea. That did it, saves me the trouble for now of figuring out whats going wrong with my specular term. I might eventually have to drop down to writing the vertex lighting shader myself again if the extra draw call isn’t acceptable but at least it buys me time!

Can I ask why you’re worried about draw calls? What are you doing, and what platforms are you targeting?

The environments the shader will be used on are pretty high poly so keeping the draw count down might help in the long run.

Comparing my own vertex lighting with the lighting the multipass shader is making me scratch my head though. What’s the proper way to get the position of the light in terms of model space?

Based on the tree shader this is how I’m attempting to get the light position in model space:

L.xyz = mul ( glstate.light[i].position.xyz, (float3x3)glstate.matrix.invtrans.modelview[0]);
float diffuseLight;
diffuseLight = dot(L.xyz, v.normal);
diffuseLight = max(diffuseLight, 0);
diffuse += glstate.light[i].diffuse * diffuseLight; // * att;

But it doesn’t really seem to work. Which space is glstate.light*.position.xyz in? World, view or model?*
It might help if I posted the whole shader:
```
/
This shader blends two diffuse maps based on the vertex colour and a mixmap. Lights using vertex lighting.
*/

Shader “Vertex Blended/Vertex Lit Diffuse” {

Properties {
_SpecColor (“Spec Color”, Color) = (1,1,1,1)
_DiffuseColor (“Diffuse Color”, Color) = (1,1,1,1)
_Shininess (“Shininess”, Range (0.01, 1)) = 0.7

_Diffuse1 ("Diffuse 1 (RGB) Spec (A)", 2D) = "white" {}
_Diffuse2 ("Diffuse 2 (RGB) Spec (A)", 2D) = "white" {}
_UseMix ("Use Mix Control", Range(0,1)) = 0
_MixControl ("Mix Control (A)", 2D) = "gray" {}

}

Category {
Blend AppSrcAdd AppDstAdd
Fog { Color [_AddFog] }

// ------------------------------------------------------------------
// ARB fragment program

SubShader {
    Pass {
        Tags { "LightMode" = "Vertex" }
        //SeparateSpecular on

CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_fog_exp2
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile_builtin

#include “UnityCG.cginc”
#include “AutoLight.cginc”

struct appdata {
float4 vertex : POSITION;
float4 tangent : TANGENT;
float3 normal : NORMAL;
float2 texcoord : TEXCOORD;
float4 color : COLOR;
};

struct v2f_vertex_blended {
float4 position : POSITION;
float fog : FOGC;
float2 uv[3] : TEXCOORD2 ;
float4 diff : TEXCOORD0;
//float4 spec : TEXCOORD1;
float4 color : COLOR ;
};

float4 _Diffuse1_ST, _Diffuse2_ST, _MixControl_ST;

uniform float _Shininess;
uniform float4 _DiffuseColor;
uniform float4 _SpecColor;

float attenuation (float3 len, int lightNum)
{
float d = length(len); //distance(position, glstate.light[lightNum].position);
float3 lightAtt = glstate.light[lightNum].attenuation;
return 1 / (lightAtt.x + lightAtt.y * d + lightAtt.z * d * d);
}

v2f_vertex_blended vert (appdata v)
{
v2f_vertex_blended o;

o.position = mul(glstate.matrix.mvp, v.vertex);
o.fog = o.position.z;

float4 lightColor = glstate.lightmodel.ambient;
float3 eyeView = normalize(ObjSpaceViewDir(v.vertex)); // Eye position
float4 diffuse = lightColor;
float4 specular = lightColor;

float4 L;
L.w = 1;
for (int i = 0; i < 4; i++) {
    
    // Calculate the diffuse
    L.xyz = mul ( glstate.light[i].position.xyz, (float3x3)glstate.matrix.invtrans.modelview[0]);
    float att = attenuation(L.xyz, i);
    
    float diffuseLight;
    diffuseLight = dot(L.xyz, v.normal);
    diffuseLight = max(diffuseLight, 0);
    diffuse += glstate.light[i].diffuse * diffuseLight * att;
    
    // Calculate the spec
    float3 vTerm = normalize(eyeView - v.vertex.xyz);
    float3 hTerm = normalize(L.xyz + vTerm);
    float specLight = dot(v.normal, hTerm);
    specLight = max(specLight, 0);
    specLight = pow(specLight, _Shininess);
    specular += glstate.light[i].diffuse * specLight;
}
o.diff = _DiffuseColor * diffuse;
//o.spec = _SpecColor * specular;// * att;

o.color = v.color;
o.uv[0] = TRANSFORM_TEX(v.texcoord, _Diffuse1);
o.uv[1] = TRANSFORM_TEX(v.texcoord, _Diffuse2);
o.uv[2] = TRANSFORM_TEX(v.texcoord, _MixControl);

return o;

}

uniform sampler2D _Diffuse1;
uniform sampler2D _Diffuse2;
uniform sampler2D _MixControl;
uniform float _UseMix;

float4 frag (v2f_vertex_blended i) : COLOR
{
//return i.diff;
float4 col1 = tex2D(_Diffuse1, i.uv[0]);
float4 col2 = tex2D(_Diffuse2, i.uv[1]);
float4 texcol;
if (_UseMix < 1) {
texcol = lerp(col1, col2, i.color.r);
texcol = (texcol * i.diff);// + i.spec;
return texcol;
}

float4 mix = tex2D(_MixControl, i.uv[2]);
if (mix.r < i.color.r)
{
    texcol = col2;
}
else
{
    texcol = col1;
}
return texcol;

}
ENDCG
}
}
}

FallBack “VertexLit”

}*
```