I've spent the past couple days trying to recreate a water shader I found online, but I'm struggling to get it work correctly.
https://alexanderameye.github.io/notes/stylized-water-shader/
More specifically, I've been trying to implement the depth fade effect that is shown since I have not found any similar ones in Godot. The one in the article is done using the Unity shader graph, but I've tried my best to recreate it.
My code so far:
shader_type spatial;
uniform sampler2D DEPTH_TEXTURE : hint_depth_texture, repeat_disable, filter_nearest;
uniform float depth_distance = 2.0;
uniform vec3 shallow_color : source_color = vec3(1);
uniform vec3 deep_color : source_color = vec3(0);
void fragment()
{
// Linearized scene depth
float depth = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).r;
vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
vec4 upos = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
upos.xyz /= upos.w;
float linear_depth = -upos.z;
// "World space water position"
vec3 frag_position_world = (INV_VIEW_MATRIX * vec4(VERTEX, 0.0)).xyz;
// float view_length = distance(frag_position_world, CAMERA_POSITION_WORLD);
// "World space scene position"
vec3 view_vector = -(INV_VIEW_MATRIX * vec4(VIEW, 1.0)).xyz; // i think this is the problem, but not sure
view_vector = view_vector / FRAGCOORD.z;
view_vector = view_vector * linear_depth;
vec3 scene_position_world = view_vector + CAMERA_POSITION_WORLD;
// "Depth fade"
vec3 water_view_depth = frag_position_world - scene_position_world;
float water_depth = -water_view_depth.y;
water_depth = exp(water_depth / depth_distance);
water_depth = clamp(water_depth, 0.0, 1.0);
vec3 color_out = mix(deep_color, shallow_color, water_depth);
ALBEDO = color_out;
}
How it looks in game:
It looks like to me the issue might be that the VIEW vector is normalized by default, and I can't figure out a way to get the full vector? I've probably made some other mistakes as well, but I'm very new to shaders so I don't really know what I'm doing. If anyone could provide any guidance or help me figure out what the problem with it is then I would appreciate it.