3

After hours of Google, copy-pasting codes and playing around, I still could not find a solution to my problem.

I try to write a postprocessing shader using the vertex and fragment functions. My problem is that I do not know how to compute the radial distance of the current vertex to the camera position (or any other given position) in world coordinates.

My goal is the following:

Consider a very big 3D plane where the camera is on top and looks exactly down to the plane. I now want a postprocessing shader that draws a white line onto the plane, such that only those pixels that have a certain radial distance to the camera are painted white. The expected result would be a white circle (in this specific setup).

I know how to do this in principal, but the problem is that I cannot find out how to compute the radial distance to the vertex.

The problem here might be that this is a POSTPROCESSING shader. So this shader is not applied to a certain object. If I would do so, I could get the world coordinates of the vertex by using mul(unity_ObjectToWorld, v.vertex), but for postprocessing shaders this gives a nonsense value.

This is my debug code for this issue:

Shader "NonHidden/TestShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent-1"}
        LOD 100

        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;
            uniform float4 _MainTex_TexelSize;

            // V2F
            struct v2f {
                float4 outpos  : SV_POSITION;
                float4 worldPos : TEXCOORD0;
                float3 rayDir : TEXCOORD1;
                float3 camNormal : TEXCOORD2;
            };


            // Sample Depth
            float sampleDepth(float2 uv) {
                return Linear01Depth(
                        UNITY_SAMPLE_DEPTH(
                            tex2D(_CameraDepthTexture, uv)));
            }


            // VERTEX
            v2f vert (appdata_tan v)
            {
                TANGENT_SPACE_ROTATION;

                v2f o;
                o.outpos = UnityObjectToClipPos(v.vertex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex);
                o.rayDir = mul(rotation, ObjSpaceViewDir(v.vertex));
                o.camNormal = UNITY_MATRIX_IT_MV[2].xyz;
                return o;
            }

            // FRAGMENT
            fixed4 frag (v2f IN) : SV_Target
            {
                // Get uv coordinates
                float2 uv = IN.outpos.xy * (_ScreenParams.zw - 1.0f);

                // Flip y if necessary
                #if UNITY_UV_STARTS_AT_TOP
                if (_MainTex_TexelSize.y < 0)
                {
                    uv.y = 1 - uv.y;
                }
                #endif

                // Get depth
                float depth = sampleDepth(uv);

                // Set color
                fixed4 color = 0;
                if(depth.x < 1)
                {
                    color.r = IN.worldPos.x;
                    color.g = IN.worldPos.y;
                    color.b = IN.worldPos.z;
                }

                return color;
            }       
            ENDCG
        }
    }
}

CurrentState

This image shows the result when the camera looks down on the plane: Image 1: Actual result The blue value is (for whatever reason) 25 in every pixel. The red and green areas reflect the x-y coordinates of the screen.

Even if I rotate the camera a little bit, I get the exact same shading at the same screen coordinates: Image 2: Actual result with rotated camera

That shows me that the computed "worldPos" coordinates are screen coordinates and have nothing to do with the world coordinates of the plane.

Expected Result

The result I expect to see is the following:

Image 3: Expected result

Here, pixels that have the same (radial) distance to the camera have the same color.

How do I need to change the above code to achieve this effect? With rayDir (computed in the vert function) I tried to get at least the direction vector from the camera center to the current pixel, such that I could compute the radial distance using the depth information. But rayDir has a constant value for all pixels ...

At this point I also have to say that I don't really understand what is computed inside the vert function. This is just stuff that I found on the internet and that I tried out.

4
  • 1
    Please read how to create a minimal, complete, verifiable example and add the missing information to your Post by editing it :) If you haven't read [how to ask ](stackoverflow.com/help/how-to-ask) yet i recommend to do so :) I highly recommend to follow the 2 guides i linked as the people on SO are more likely to answer questions when the posts follow these guides. What i'm missing in particular is - What have u tried so far? What errors/problems do you face? Do you may have codesnippets that help understand your question? Welcome to StackOverflow Dec 29, 2017 at 13:12
  • 1
    @Tobias: good advice. One of the links got a bit broken above - you may be interested to know you can use [ask] and [mcve] in comments, and it will auto-expand to those links.
    – halfer
    Dec 30, 2017 at 1:25
  • 1
    @halfer yeah i know that the link is broken - but i cannot edit this comment anymore. And i always linked them the complicated way. That is the best advice i've got in years! I bet i can find a list of these "shortcuts" anywhere :D Dec 30, 2017 at 1:28
  • @Tobias: I think I have seen them documented in the Help Centre, but you really have to search for it ;-)
    – halfer
    Dec 30, 2017 at 1:33

1 Answer 1

1

Alright, I found some solution to my problem, since I found this video here: Shaders Case Study - No Man's Sky: Topographic Scanner

In the video description is a link to the corresponding GIT repository. I downloaded, analyzed and rewrote the code, such that it fits my purpose, is easier to read and understand.

The major thing I learned is, that there is no built-in way to compute the radial distance using post-processing shaders (correct me if I'm wrong!). So in order to get the radial distance, the only way seems to be in fact to use the direction vector from the camera to the vertex and the depth buffer. Since the direction vector is also not available in a built-in way, a trick is used:

Instead of using the Graphics.Blit function in the post-processing script, a custom Blit function can be used to set some additional shader variables. In this case, the frustum of the camera is stored in a second set of texture coordinates, which are then available in the shader code as TEXCOORD1. The trick here is that the according shader variable automatically contains an interpolated uv value, that is identical to the direction vector ("frustum ray") I was looking for.

The code of the calling script now looks as follows:

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class TestShaderEffect : MonoBehaviour
{

    private Material material;
    private Camera cam;

    void OnEnable()
    {
        // Create a material that uses the desired shader
        material = new Material(Shader.Find("Test/RadialDistance"));

        // Get the camera object (this script must be assigned to a camera)
        cam = GetComponent<Camera>();

        // Enable depth buffer generation#
        // (writes to the '_CameraDepthTexture' variable in the shader)
        cam.depthTextureMode = DepthTextureMode.Depth;
    }

    [ImageEffectOpaque] // Draw after opaque, but before transparent geometry
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Call custom Blit function
        // (usually Graphics.Blit is used)
        RaycastCornerBlit(source, destination, material);
    }


    void RaycastCornerBlit(RenderTexture source, RenderTexture destination, Material mat)
    {

        // Compute (half) camera frustum size (at distance 1.0)
        float angleFOVHalf = cam.fieldOfView / 2 * Mathf.Deg2Rad;
        float heightHalf = Mathf.Tan(angleFOVHalf);
        float widthHalf = heightHalf * cam.aspect;      // aspect = width/height

        // Compute helper vectors (camera orientation weighted with frustum size)
        Vector3 vRight = cam.transform.right * widthHalf;
        Vector3 vUp = cam.transform.up * heightHalf;
        Vector3 vFwd = cam.transform.forward;


        // Custom Blit
        // ===========

        // Set the given destination texture as the active render texture
        RenderTexture.active = destination;

        // Set the '_MainTex' variable to the texture given by 'source'
        mat.SetTexture("_MainTex", source);

        // Store current transformation matrix
        GL.PushMatrix();    

        // Load orthographic transformation matrix
        // (sets viewing frustum from [0,0,-1] to [1,1,100])
        GL.LoadOrtho();     

        // Use the first pass of the shader for rendering
        mat.SetPass(0);

        // Activate quad draw mode and draw a quad
        GL.Begin(GL.QUADS);
        {

            // Using MultiTexCoord2 (TEXCOORD0) and Vertex3 (POSITION) to draw on the whole screen
            // Using MultiTexCoord to write the frustum information into TEXCOORD1
            // -> When the shader is called, the TEXCOORD1 value is automatically an interpolated value

            // Bottom Left
            GL.MultiTexCoord2(0, 0, 0);
            GL.MultiTexCoord(1, (vFwd - vRight - vUp) * cam.farClipPlane);
            GL.Vertex3(0, 0, 0);

            // Bottom Right
            GL.MultiTexCoord2(0, 1, 0);
            GL.MultiTexCoord(1, (vFwd + vRight - vUp) * cam.farClipPlane);
            GL.Vertex3(1, 0, 0);

            // Top Right
            GL.MultiTexCoord2(0, 1, 1);
            GL.MultiTexCoord(1, (vFwd + vRight + vUp) * cam.farClipPlane);
            GL.Vertex3(1, 1, 0);

            // Top Left
            GL.MultiTexCoord2(0, 0, 1);
            GL.MultiTexCoord(1, (vFwd - vRight + vUp) * cam.farClipPlane);
            GL.Vertex3(0, 1, 0);

        }
        GL.End();   // Finish quad drawing

        // Restore original transformation matrix
        GL.PopMatrix();
    }
}

The shader code looks like this:

Shader "Test/RadialDistance"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct VertIn
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float4 ray : TEXCOORD1;
            };

            struct VertOut
            {
                float4 vertex : SV_POSITION;
                float2 uv : TEXCOORD0;
                float4 interpolatedRay : TEXCOORD1;
            };


            // Parameter variables
            sampler2D _MainTex;

            // Auto filled variables
            float4 _MainTex_TexelSize;
            sampler2D _CameraDepthTexture;


            // Generate jet-color-sheme color based on a value t in [0, 1]
            half3 JetColor(half t)
            {
                half3 color = 0;
                color.r = min(1, max(0, 4 * t - 2));
                color.g = min(1, max(0, -abs( 4 * t - 2) + 2));
                color.b = min(1, max(0, -4 * t + 2));
                return color;
            }


            // VERT
            VertOut vert(VertIn v)
            {
                VertOut o;

                // Get vertex and uv coordinates
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv.xy;

                // Flip uv's if necessary
                #if UNITY_UV_STARTS_AT_TOP
                if (_MainTex_TexelSize.y < 0)
                    o.uv.y = 1 - o.uv.y;
                #endif              

                // Get the interpolated frustum ray
                // (generated the calling script custom Blit function)
                o.interpolatedRay = v.ray;

                return o;
            }


            // FRAG
            float4 frag (VertOut i) : SV_Target
            {
                // Get the color from the texture
                half4 colTex = tex2D(_MainTex, i.uv);

                // flat depth value with high precision nearby and bad precision far away???
                float rawDepth = DecodeFloatRG(tex2D(_CameraDepthTexture, i.uv));

                // flat depth but with higher precision far away and lower precision nearby???
                float linearDepth = Linear01Depth(rawDepth);

                // Vector from camera position to the vertex in world space
                float4 wsDir = linearDepth * i.interpolatedRay;

                // Position of the vertex in world space
                float3 wsPos = _WorldSpaceCameraPos + wsDir;

                // Distance to a given point in world space coordinates
                // (in this case the camera position, so: dist = length(wsDir))
                float dist = distance(wsPos, _WorldSpaceCameraPos);

                // Get color by distance (same distance means same color)
                half4 color = 1;
                half t = saturate(dist/100.0);
                color.rgb = JetColor(t);

                // Set color to red at a hard-coded distance -> red circle
                if (dist < 50 && dist > 50 - 1 && linearDepth < 1)
                {
                    color.rgb = half3(1, 0, 0);
                }

                return color * colTex;
            }
            ENDCG
        }
    }
}

I'm now able to achieve the desired effect:

Image

But there are still some questions I have and I would be thankful if anyone could answer them for me:

  • Is there really no other way to get the radial distance? Using a direciton vector and the depth buffer is inefficient and inaccurate
  • I don't really understand the content of the rawDepth variable. I mean yes, it's some depth information, but if you use the depth information as texture color, you basically get a black image if you are not ridiculously close to an object. That leads to a very bad resolution for objects that are further away. How can anyone work with that?
  • I don't understand what exactly the Linear01Depth function does. Since the Unity documentation sucks in general, it also doesn't offer any information about this one as well
1
  • Could you perhaps do something with UVs? Maybe something along the lines of taking the length of the vector that the UVs make, then remapping that? Idk I'm no shader expert haha :)
    – Clonkex
    Feb 9, 2020 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.