Search Unity

Please explain how it works

Discussion in 'Shaders' started by shlakva, May 26, 2021.

  1. shlakva

    shlakva

    Joined:
    Oct 15, 2017
    Posts:
    15
    Hello

    I'm new to shader's logic in unity and currently I'm learning GrabPass.

    I saw several implementations of GrabPass and they contained this code:

    Code (CSharp):
    1. v2f vert(appdata_t v) {
    2. v2f o;
    3. ...
    4. o.vertex = UnityObjectToClipPos(v.vertex);
    5. o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y) + o.vertex.w) * 0.5;
    6. ...
    7. }
    Could someone please explain, why after applying MVP matrix we do some calculations on X and Y of uvgrab? And of course explain this math.

    Thanks!

    P.S. Why no tutorial explain math of shader they using?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Clip space is a type of screen space coordinate system. The range of clip.xy for what appears on screen is values between -clip.w and +clip.w. If you want to understand why, look up “homogeneous clip space coordinates”.

    The short version is if you’re using an orthographic camera, the w value is always 1.0. So the above code is taking x and y, and rescaling a -1.0 to 1.0 range to a 0.0 to 1.0 range. But in a way that’ll only work with an orthographic camera.

    With a perspective camera, w is the world scale view depth. So the above code without also passing the clip space w value and dividing the xy in the fragment by that w value will at worst produce complete junk, or at best a warped image. Again, look up “homogeneous coordinates” to find out why.

    The short version: Just use the example code in Unity’s documentation.
    https://docs.unity3d.com/Manual/SL-GrabPass.html
     
  3. shlakva

    shlakva

    Joined:
    Oct 15, 2017
    Posts:
    15
    First of all, @bgolus I want to say thanks to you , because I'm learning shaders logic surfing this forum and reading your comments.

    Second, I know homogeneous coordinates and thats why I asked this question. Several tutorials used line 5 in their code with perspective camera, looks like without understanding what they are doing. This broke my brain.

    Why do we need to rescale -1..1 to 0..1 in the shader context? Where the profit is?
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    Unless there's a bit of code also passing the w component, yeah, it's broken.

    If it is passing the w component, then it's fine.

    It's rescaling to 0.0 to 1.0 because it's a UV for sampling the grab pass texture, which is a copy of the render target.