Search code examples
glslgodot

How to get the resolution on godot spatial shader?


shader_type spatial;
void fragment ()

{
    vec2 i_resolution = 1.0 / SCREEN_PIXEL_SIZE ;

    ...
    //fragColor = ...; 
    COLOR = ...; 'Constants cannot be modified' And this is other problem on spatial shader
}

SCREEN_PIXEL_SIZE don't work on spatial shader? how to get the resolution?


Solution

  • As you have noticed SCREEN_PIXEL_SIZE does not exist in Spatial Shader (it exists in Canvas Shaders).

    The equivalent of SCREEN_PIXEL_SIZE for Spatial Shaders is 1.0/VIEWPORT_SIZE. That is, VIEWPORT_SIZE = 1.0/SCREEN_PIXEL_SIZE.

    Since 1.0/SCREEN_PIXEL_SIZE is what you want, you can use VIEWPORT_SIZE directly. It gives you size in pixels of the viewport (where the shader is being drawn, be it the screen, a window, or a texture).

    Furthermore, if you are going to do FRAGCOORD.xy/VIEWPORT_SIZE, you can use SCREEN_UV instead. That is SCREEN_UV = FRAGCOORD.xy/VIEWPORT_SIZE. As you would expect, FRAGCOORD is the fragment coordinates in pixels, while SCREEN_UV gives you normalized coordinates (0 to 1).

    By the way, if you don't want the material to depend on the position on screen, you may swap SCREEN_UV for UV.

    By the way yes, I know SCREEN_UV says "screen" and not "viewport". Some naming can be confusing.


    In your spatial shader you don't write to COLOR, you write ALBEDO and ALPHA instead. Godot will notice if you write to ALPHA or not, and take that into account for deciding render order (so potentially transparent materials are rendered after opaque ones).


    Speaking of confusing naming…

    mat4 ModelToWorld  = WORLD_MATRIX;              // Common name: Model Matrix
    mat4 WorldToModel  = inverse(WORLD_MATRIX);     // Common name: Inverse Model Matrix
    mat4 WorldToCamera = INV_CAMERA_MATRIX;         // Common name: View Matrix
    mat4 CameraToWorld = CAMERA_MATRIX;             // Common name: Inverse View Matrix
    mat4 ModelToCamera = MODELVIEW_MATRIX;          // Common name: View Model Matrix
    mat4 CameraToModel = inverse(MODELVIEW_MATRIX); // Common name: Inverse View Model Matrix
    mat4 CameraToClip  = PROJECTION_MATRIX;          // Common name: Projection Matrix
    mat4 ClipToCamera  = INV_PROJECTION_MATRIX;      // Common name: Inverse Projection Matrix
    

    Please refer to Spatial Shaders, for the list of built-ins (including those mentioned above) and render modes.