2D Shader - How to map SCREEN_UV to Sprite's UV?

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

Starting my exploration of Shaders a bit. I’m trying to work out a water reflection, but I got stuck. After reading the documentation several times and looking over various examples for a few hours, I’m still missing something.

I’m applying a CanvasItemShader to a Sprite, that has a 1x1 white Texture. What I would like to do is take a cut out some rectangle part of the screen texture behind that node. Then take those pixels, invert the Y, and map them to Sprite’s UV.

I’m having difficulty with the shading language, it escapes me how to extract and mix together these bits of UV and Texture.

There is texscreen(SCREEN_UV) that returns a Color with the screen information, but I can’t seem to do much with it from there. Then I’ve tried out tex(TEXTURE, UV), but I get an initializer error.

Appreciate any pointers.

:bust_in_silhouette: Reply From: mollusca

To read and flip the screen directly under a Sprite you can use this fragment shader:

uniform float screen_h = 600;
uniform float sprite_h = 256;
float sprite_uv_h = sprite_h / screen_h;
vec2 flipped_screen_uv = vec2(SCREEN_UV.x, SCREEN_UV.y - sprite_uv_h * (1 - 2 * UV.y));
COLOR = vec4(texscreen(flipped_screen_uv), 1.0);

For a water reflection it might be handier to read the screen area just above the Sprite by offsetting the UV:

vec2 flipped_screen_uv = vec2(SCREEN_UV.x, SCREEN_UV.y - sprite_uv_h * (1 - 2 * UV.y) + sprite_uv_h);

Many thanks. I see so it is all done via texscreen(some_uv).

Now that I have a working example, I can better wrap my head around it.

avencherus | 2017-11-03 13:37