Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Visualizing Collision Detection Through Shaders?

Discussion in 'Shaders' started by cuddlepunk, Oct 15, 2015.

  1. cuddlepunk

    cuddlepunk

    Joined:
    Apr 9, 2014
    Posts:
    18


    Good morning, afternoon and (possibly) night.

    I suppose I'm merely here because I've discovered myself with a rather peculiar shader wish.
    Since, I've been attempting to design a shader that's capable of detecting intersecting meshes, and also able to procedurally add in a line around the collision area, similar to foam around the shoreline of a sea.

    The right-most image most depicts what I've sort of been looking for, and I suppose I was only wondering whether anyone may be able to assist, or at the least be able to point me in the right direction.

    Many thanks in advance :)

    Edit
    The question has since been answered and the code to the shader can be discovered below, so merely rest assured you're more than welcome to use towards your own endeavours too!
     
    Last edited: Oct 19, 2015
  2. varfare

    varfare

    Joined:
    Feb 12, 2013
    Posts:
    227
    It's totally doable. You can download Unity's built-in shaders and take a look at how soft particles feature is implemented. "Soft particle" compares mesh depth values with camera's depth map values. If these values are within specified threshold you know that your mesh is intersecting with another :) The same technique was described in "Effects with Depth" slide that you can download here: http://blogs.unity3d.com/2011/09/08/special-effects-with-depth-talk-at-siggraph/

    Result can be seen here:


    I am using this technique to create water foam in regions that are intersecting with terrain.
     
    solkar and cuddlepunk like this.
  3. cuddlepunk

    cuddlepunk

    Joined:
    Apr 9, 2014
    Posts:
    18
    Thank you, that's actually been really rather beneficial and insightful!

    I've since been doing a little reading, and I think I'm quietly coming to terms with Depth Buffering.
    However, I kind of have this peculiar issue where I'm not too certain whether it's actually reading the depth texture values.

    I've attempted to use the following shader (which supposedly visualizes depth buffer values), except it's rendering out black, as if the values are defaulting to zero. The Camera has been set to deferred, and I guess the only issue I can identify is that I'm using a Mac, which apparently has a few peculiar quirks when it comes to rendering

    Edit
    depth buffering only seemingly appears to work with perspective cameras (possibly), and if you're still suffering with black renders, this may well be because your far clipping plane is too massive, and may need to be shrunk a little


    Code (csharp):
    1.  
    2. Shader "Render Depth" {
    3. SubShader {
    4.     Tags { "RenderType"="Opaque" }
    5.     Pass {
    6. CGPROGRAM
    7.  
    8. #pragma vertex vert
    9. #pragma fragment frag
    10. #include "UnityCG.cginc"
    11.  
    12. struct v2f {
    13.     float4 pos : SV_POSITION;
    14.     float2 depth : TEXCOORD0;
    15. };
    16.  
    17. v2f vert (appdata_base v) {
    18.     v2f o;
    19.     o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
    20.     UNITY_TRANSFER_DEPTH(o.depth);
    21.     return o;
    22. }
    23.  
    24. half4 frag(v2f i) : SV_Target {
    25.     UNITY_OUTPUT_DEPTH(i.depth);
    26. }
    27. ENDCG
    28.     }
    29. }
    30. }
     
    Last edited: Oct 19, 2015
    pixpusher2 likes this.
  4. cuddlepunk

    cuddlepunk

    Joined:
    Apr 9, 2014
    Posts:
    18


    The final shader, as witnessed within the unity build


    As it were,
    I've since figured this out and have discovered a fair bit about Depth Textures in the process too.
    So if you happen to be an internet stranger wandering by with similar qualms, please don't hesitate to ask , as I would be more than pleased to ease you through such peculiar issues too

    Thank you so much Varfare for reaching out and for guiding me along too - much appreciated!
     
    solkar and varfare like this.
  5. pixpusher2

    pixpusher2

    Joined:
    Oct 30, 2013
    Posts:
    121
    Very nice effect! Does it work well in orthographic camera too?
    I've tried something similar but the result wasn't too good.
     
  6. cuddlepunk

    cuddlepunk

    Joined:
    Apr 9, 2014
    Posts:
    18
    Mmm,
    From what little I've messed with it doesn't appear to work within orthographic, possibly because you simply need that perspective depth range to detect the appropriate mesh intersections (which orthographic may not offer).

    Though you're more than welcome to mess around with the code yourself, since it seems you've been making some pretty nifty breakthroughs in that others shader of yours too, and I would kind of love to see this effect become more easily accessible amongst us developers too!

    Code (CSharp):
    1.  
    2.  
    3. Shader "Custom/Intersection"
    4. {
    5.  
    6.     Properties
    7.     {  
    8.        
    9.          // Color Utilized When Not Intersecting
    10.         _RegularColor("Main Color", Color) = (1, 1, 1, .5)
    11.      
    12.          // Color Utilized When Intersecting
    13.         _HighlightColor("Highlight Color", Color) = (1, 1, 1, .5)
    14.        
    15.          // Maximum Difference Between Intersections
    16.         _HighlightThresholdMax("Highlight Threshold Max", Float) = 1
    17.  
    18.          // Defines The Blurrines Quality Of The Intersections
    19.         _Quality ("Quality", Float) = 0.5
    20.     }
    21.  
    22.  
    23.  
    24.     SubShader
    25.     {
    26.  
    27.        
    28.         Tags { "Queue" = "Transparent" "RenderType"="Transparent"  }
    29.        
    30.         Pass
    31.         {
    32.      
    33.      
    34.             Blend SrcAlpha OneMinusSrcAlpha
    35.             ZWrite Off
    36.             Cull Off
    37.             CGPROGRAM
    38.             #pragma target 3.0
    39.             #pragma vertex vert
    40.             #pragma fragment frag
    41.             #include "UnityCG.cginc"
    42.  
    43.        
    44.             uniform sampler2D _CameraDepthTexture; //Depth Texture
    45.             uniform float4    _RegularColor;
    46.             uniform float4    _HighlightColor;
    47.             uniform float     _HighlightThresholdMax;
    48.             uniform float     _Quality;
    49.  
    50.  
    51.             struct v2f
    52.             {
    53.                 float4 pos : SV_POSITION;
    54.                 float4 projPos : TEXCOORD1; //Screen position of pos
    55.             };
    56.        
    57.             v2f vert(appdata_base v)
    58.             {
    59.                 v2f o;
    60.                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    61.                 o.projPos = ComputeScreenPos(o.pos);
    62.                 return o;
    63.             }
    64.             half4 frag(v2f i) : COLOR
    65.             {
    66.          
    67.      
    68.                 // Defines All Necessiary Attributes
    69.                 float4 finalColor = _RegularColor;
    70.              
    71.                 // Recieves The Camera Distance From The Depth Buffer
    72.                 float sceneZ = LinearEyeDepth (tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD (i.projPos) ).r);
    73.                                                        
    74.          
    75.                 // Calculates Genuine Distance To Camera
    76.                 float partZ = i.projPos.z;
    77.            
    78.                 // If Similarites Are Discovered Between Intersecting Points Within The "Threshold" Parameters
    79.                 float diff = (abs(sceneZ - partZ)) / _HighlightThresholdMax;
    80.      
    81.                 // Gives Intersecting Edges A Rather Charming Visual Aesthetic
    82.                 if (diff <= _Quality)
    83.                 finalColor = lerp( _HighlightColor,  _RegularColor, float4(diff, diff, diff, diff));
    84.                                
    85.              
    86.        
    87.                 // Defines The Shader Texture That'll Be Released To The Camera Render
    88.                 half4 c;
    89.                 c.r = finalColor.r;
    90.                 c.g = finalColor.g;
    91.                 c.b = finalColor.b;
    92.                 c.a = finalColor.a;
    93.                 return c;
    94.             }
    95.             ENDCG
    96.         }
    97.     }
    98.  
    99.  
    100.     // Reverts To A Classic "VertexLit" Shader If The Defined Shader Doesn't Compute
    101.     FallBack "VertexLit"
    102. }
     
    pixpusher2 likes this.
  7. pixpusher2

    pixpusher2

    Joined:
    Oct 30, 2013
    Posts:
    121
    @Tuurtledove Thanks! Didn't know how I missed your reply. I'll try fiddling with your shader when I have the chance :)
     
  8. Serejka

    Serejka

    Joined:
    Oct 20, 2015
    Posts:
    6
    Does it work with Unlit shaders?
     
  9. cuddlepunk

    cuddlepunk

    Joined:
    Apr 9, 2014
    Posts:
    18
    Mmm, I wouldn't see why it wouldn't. It's effectively unlit from a visual perspective anyway.
    I'm going to be meddling with a code a little this week as it were, so I'll be sure to let you know what I discover