Obtaining the world space normal with a light shader

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ugly_cat
:warning: Old Version Published before Godot 3 was released.

I’m trying to figure out how to get the world space normal with the light shader. I know there is documentation about obtaining the world space normal in the fragment shader, but there doesn’t seem to be a way to do that easily in the light shader. Anybody now?

I see you can pass parameters between vertex and fragment shaders using VAR1 and VAR2, however I don’t see such variables in LightMaterial…

Zylann | 2016-09-23 19:07

:bust_in_silhouette: Reply From: GlaDOSik

Do you need normal in view space? If not, you can compute world space normal in vertex shader, pass it to fragment shader using VAR1 or VAR2 and pass it to LIGHT part in NORMAL. Do you need specular color? If not, you can use SPECULAR to pass the normal. Another way would be to calculate inverse camera matrix and world matrix inside the script and use uniform matrix in LIGHT. Using them, you could compute world normal from view space normal.

Awesome! Combined with the example in the docs:

vec4 invcamx = INV_CAMERA_MATRIX.x;
vec4 invcamy = INV_CAMERA_MATRIX.y;
vec4 invcamz = INV_CAMERA_MATRIX.z;
vec4 invcamw = INV_CAMERA_MATRIX.w;

mat3 invcam = mat3(invcamx.xyz, invcamy.xyz, invcamz.xyz);

vec3 world_normal = NORMAL * invcam;
vec3 world_pos = (VERTEX - invcamw.xyz) * invcam;

And the knowledge that setting the NORMAL variable carries to the Lighting shader helped to make a shader that casts light on top of the model regardless of the orientation of the camera:
Fragment:

NORMAL = world_normal;

and the Lighting shader:

LIGHT = vec3(dot(NORMAL, vec3(0,1,0)));

ugly_cat | 2016-09-24 21:31