Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Weird pixel position calculation

Discussion in 'Shaders' started by zhutianlun810, Aug 30, 2019.

  1. zhutianlun810

    zhutianlun810

    Joined:
    Sep 17, 2017
    Posts:
    165
    I found a project online and there is a line computing pixels' size:
    Code (CSharp):
    1. float4 vPostion = UnityObjectToClipPos(vert);
    2.  
    3. float2 pixelSize = vPosition.w;
    4.  
    5. pixelSize /= abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy))
    6.  
    7. //pixelSize = 1.0/_ScreenParams.xy
    _ScreenParams.xy is the size of my window, like 1920*1080. Normally I use the line commented to calculate the pixelSize. What does this magic code actually do?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    It seems like that’s calculating the size of a pixel in view space at the depth of that vertex, vs in screen UV space.
     
  3. zhutianlun810

    zhutianlun810

    Joined:
    Sep 17, 2017
    Posts:
    165
    Sorry, what is size of a pixel in view space at the depth of that vertex? I can't understand "at the depth of that vertex".
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    I’ll rephrase it this way.

    It’s how many world units wide a pixel covers at a certain distance from the camera.

    The W value of a clip space position is that position’s distance from the camera along the forward view direction. The 2x2 of the projection matrix (UNITY_MATRIX_P) holds the horizontal and vertical fov factors. Alone they can tell you how much something needs to be scaled to stay a constant screen size. The mul of the resolution just means it’s scaling that to a constant pixel size.