Skip to content

Instantly share code, notes, and snippets.

@lyuma
Created February 18, 2021 06:05
Show Gist options
  • Save lyuma/ff48f672a9c4abeb24fc131892e06a5e to your computer and use it in GitHub Desktop.
Save lyuma/ff48f672a9c4abeb24fc131892e06a5e to your computer and use it in GitHub Desktop.
Example Godot shader showing how writing to ALPHA can allow for a sort of light masking effect in 3D
shader_type spatial;
render_mode blend_mix,depth_draw_opaque,cull_back,diffuse_burley,specular_schlick_ggx;
uniform vec4 albedo : hint_color;
uniform sampler2D texture_albedo : hint_albedo;
uniform float specular;
uniform float metallic;
uniform float roughness : hint_range(0,1);
uniform float point_size : hint_range(0,128);
uniform vec3 uv1_scale;
uniform vec3 uv1_offset;
uniform float lightmask_min = 0.075;
uniform float lightmask_max = 0.1;
void vertex() {
UV=UV*uv1_scale.xy+uv1_offset.xy;
}
float SchlickFresnel(float u) { float m = 1.0 - u; float m2 = m * m; return m2 * m2 * m; }
void fragment() {
vec2 base_uv = UV;
vec4 albedo_tex = texture(texture_albedo,base_uv);
ALBEDO = albedo.rgb * albedo_tex.rgb;
METALLIC = metallic;
ROUGHNESS = roughness;
SPECULAR = specular;
ALPHA = 0.0;
}
void light() {
// Default Godot BRDF.
float NdotL = dot(NORMAL, LIGHT);
float cNdotL = max(NdotL, 0.0); // clamped NdotL
float NdotV = dot(NORMAL, VIEW);
float cNdotV = max(NdotV, 0.0);
vec3 H = normalize(VIEW + LIGHT);
float cNdotH = max(dot(NORMAL, H), 0.0);
float cLdotH = max(dot(LIGHT, H), 0.0);
float diffuse_brdf_NL; // BRDF times N.L for calculating diffuse radiance
{
float FD90_minus_1 = 2.0 * cLdotH * cLdotH * ROUGHNESS - 0.5;
float FdV = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotV);
float FdL = 1.0 + FD90_minus_1 * SchlickFresnel(cNdotL);
diffuse_brdf_NL = (1.0 / 3.1415926) * FdV * FdL * cNdotL;
}
DIFFUSE_LIGHT += 1.0 * LIGHT_COLOR * ALBEDO * diffuse_brdf_NL * ATTENUATION;
SPECULAR_LIGHT = vec3(0.0);
float dot_attenuation = diffuse_brdf_NL * length(vec3(ATTENUATION)) / length(vec3(1.0));
ALPHA = max(ALPHA, smoothstep(lightmask_min, lightmask_max, dot_attenuation));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment