How to decode directional light map?

I want to access the light direction from a directional light map in a shader I am writing. I have hardly been able to find any information or example on how to do so.

I tried doing it the same way as a regular light map:

v2f vert (appdata_full v)
{
v2f o;
o.lmap = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;

fixed4 frag(v2f i) : COLOR
{
fixed3 lmColor = DecodeLightmap(tex2D(unity_Lightmap, i.lmap));
fixed3 lmDirection = DecodeLightmap(tex2D(unity_LightmapInd, i.lmap));

But it’s not giving me the results I would expect. I’m guessing I can’t go ahead and just treat lmDir like a direction vector at this point?

Thanks for your help.

There is an example in the docs using surface shaders. In the section “Decoding Lightmaps”. Hope that helps.

http://docs.unity3d.com/Documentation/Components/SL-SurfaceShaderLighting.html

You haven’t been able to find any information, because what you want to do isn’t how lightmaps tend to work. Lightmaps usually store light contribution data for a given surface and know nothing about the lights affecting said surface - they have no concept of the direction from which the light is coming from (if they did, they probably wouldn’t be much cheaper than dynamic lights), ergo, you cannot get it.

@ambershee

I’m under the impression that is exactly what a “directional lightmap” is. One map is the light contribution data for a given surface as you say, and the other map is direction information stored as a color. Am I misunderstanding something?

@jRocket

That would be helpful but I am trying to avoid using surface shaders. I want to know exactly what my shader is doing, and surface shaders seem to do a lot of mysterious things behind the scenes. There are lots of examples of decoding regular lightmaps in vert/frag shaders… I didn’t think this information would be so hard to come by…

It is possible to take a look at the vertex and fragment shaders created by surface shaders using #pragma debug. It isn’t always easy to read, but majority of the time, the information you need is there.

In case anyone else wants to do this, this works…

fixed3 lmDir = DecodeLightmap(tex2D(unity_LightmapInd, i.lmap));
float3x3 _DirBasis = float3x3(
float3( 0.81649658, 0.0, 0.57735028),
float3(-0.40824830, 0.70710679, 0.57735027),
float3(-0.40824829, -0.70710678, 0.57735026)
);
lmDir = normalize (lmDir.x * _DirBasis[0] + lmDir.y * _DirBasis[1] + lmDir.z * _DirBasis[2]);

I pulled it out of some other built in shaders and UnityCG.cginc

1 Like