Hey folks,
Got a shader in one project at the moment that’s causing a bit of a pain. There are 3 images going into it, a diffuse texture, a lightmap texture, and a baked ambient occlusion texture. In trying to get the right look as close to the pre-rendered concepts as possible, I was looking at using an overlay function for the diffuse and lightmap. On pc and mac it looks good, However I soon found out that this wouldn’t run on device.
Here is the shader as it stands at the moment:
Shader "Custom/Crate Shader"
{
Properties
{
_Color("_Color", Color) = (1,1,1,1)
_MainTex ("Base (RGB) AO(A)", 2D) = "white" {}
_LightMap ("LightMap", 2D) = "white" {}
_AOTex ("Ao texture", 2D) = "white" {}
_AOStrength ("AO Strength", Range(0,1)) = 0
_LightMapStrength ("Light Map Strength", Range(0,1)) = 0
}
SubShader
{
Tags {"Queue"="Transparent" "RenderType"="Transparent"}
LOD 200
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float2 uv2 : TEXCOORD1;
};
struct appdata
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
sampler2D _MainTex;
sampler2D _LightMap;
sampler2D _AOTex;
float4 _MainTex_ST;
float4 _LightMap_ST;
float4 _AOTex_ST;
half _AOStrength;
half _LightMapStrength;
fixed4 _Color;
v2f vert(appdata v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.uv2 = TRANSFORM_TEX(v.texcoord1, _MainTex);
return o;
}
half Overlay(half a, half b)
{
if(a < 0.5)
return 2*a*b;
else
return 1-(2*(1-a)*(1-b));
}
fixed4 frag(v2f IN) : COLOR
{
fixed4 diffuse = tex2D (_MainTex, IN.uv);
fixed4 lightmap = tex2D (_LightMap, IN.uv2);
diffuse.r = Overlay(diffuse.r, lightmap.r);
diffuse.g = Overlay(diffuse.g, lightmap.g);
diffuse.b = Overlay(diffuse.b, lightmap.b);
diffuse *= 1 - (_AOStrength * (1 - (tex2D(_AOTex, IN.uv2))));
diffuse.a = 1;
return diffuse * _Color;
}
ENDCG
}
}
FallBack "Transparent/Diffuse"
}
Now when run like this on device, the mesh itself just disappears completely and the frame rate drops far below acceptable levels. However if i comment out just one of the lines that calls the overlay, regardless of which RG or B channel, the box draws (albeit with undesired colour) and the framerate is happy to sit back up at 30.
Now I’m no shader programmer, I get by with shaders just about. I’m hoping that someone will read this and be able to make a suggestion as to how to make the shader cheaper so it will run on device overlaying all 3 channels, or perhaps knows from experience that this wont work and have an alternative approach to suggest.
Note: I have tried removing the AO to see if that helps at all, but the behaviour is still the same, broken using 3 channels, and working when only using 2. And the strength values are only there for development, when we settle on values they will of course be baked into the shader.
Thanks.