Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by sgoodrow · May 17, 2013 at 09:36 PM · camerashadermaterialfogshader-replacement

Setting up a simple depth-based Shader Replacement material?

I have been trying to get a handle on the concept of Shader Replacement and am having a hard time getting things to work. The first goal is simply to render the difference in depth between a mesh's front faces and back faces; this is my first step toward volume fog.

Here is the code for the script which is attached to the main camera:

 using UnityEngine;
 using System.Collections;
 
 [ExecuteInEditMode]
 [RequireComponent(typeof(Camera))]
 public class VolumeFogRenderer : MonoBehaviour
 {
     public Shader m_BackFaceDepthsShader;
     public Shader m_FrntFaceDepthsShader;
     public Material m_VolumeFogMaterial;
     
     private GameObject _shaderReplacementCamera;
     
     void OnPreRender()
     {
         if (!enabled || !gameObject.activeSelf)
         {
             return;
         }
         
         if (!_shaderReplacementCamera)
         {
             _shaderReplacementCamera = new GameObject("CameraVolumeFog");
             _shaderReplacementCamera.hideFlags = HideFlags.HideAndDontSave;
             _shaderReplacementCamera.AddComponent<Camera>();
             _shaderReplacementCamera.camera.enabled = false;            
         }
         
         Camera cam = _shaderReplacementCamera.camera;
         cam.CopyFrom(camera);
         cam.backgroundColor = new Color(0, 0, 0, 0);
         cam.clearFlags = CameraClearFlags.SolidColor;
         
         RenderTexture backFaceDepthsRT = RenderTexture.GetTemporary(Screen.width, Screen.height, 16);        
         cam.targetTexture = backFaceDepthsRT;
         cam.RenderWithShader(m_BackFaceDepthsShader, "Fog");
         
         RenderTexture frntFaceDepthsRT = RenderTexture.GetTemporary(Screen.width, Screen.height, 16);
         cam.targetTexture = frntFaceDepthsRT;
         cam.RenderWithShader(m_FrntFaceDepthsShader, "Fog");
         
         m_VolumeFogMaterial.SetTexture("_BackFaceDepths", backFaceDepthsRT);
         m_VolumeFogMaterial.SetTexture("_FrntFaceDepths", frntFaceDepthsRT);
                 
         RenderTexture.ReleaseTemporary(backFaceDepthsRT);
         RenderTexture.ReleaseTemporary(frntFaceDepthsRT);
     }
 
     void OnDisable()
     {        
         if (_shaderReplacementCamera != null)
         {
             DestroyImmediate(_shaderReplacementCamera);
         }
     }
 }

This script requires 3 objects to be set up in the inspector: a back face depth shader, front face depth shader, and a composite material which renders the difference between the two RenderTextures produced from the first two shaders:

Here is the shader for the composite material:

 Shader "Custom/VolumeFog"
 {
     Properties
     {        
         _MainTex ("Base (RGB) Trans (A)", 2D) = "" {}
         _BackFaceDepths ("Back Face Depths", 2D) = "" {}
         _FrntFaceDepths ("Front Face Depths", 2D) = "" {}
 
     }
     
     SubShader
     {
         Tags
         {
             "Queue" = "Transparent-1"
             "RenderType" = "Fog"
             "IgnoreProjector" = "True"
         }
         
         Lighting Off
         ZWrite Off
         Fog { Mode Off }
         LOD 200
         
         CGPROGRAM
         #pragma surface surf Lambert alpha
                 
         sampler2D _MainTex;
         sampler2D _BackFaceDepths;
         sampler2D _FrntFaceDepths;
         
         struct Input
         {
             float2 uv_MainTex;
         };
         
         void surf (Input IN, inout SurfaceOutput o)
         {
             fixed4 bg = tex2D(_MainTex, IN.uv_MainTex);
             fixed4 b = tex2D(_BackFaceDepths, IN.uv_MainTex);
             fixed4 f = tex2D(_FrntFaceDepths, IN.uv_MainTex);
             
             fixed4 d = clamp(b - f, 0, 1);
             
             o.Albedo = d.rgb;
             o.Alpha = d.a;
         }
         
         ENDCG
     }
     
     FallBack Off
 }

And finally the two shaders used for replacement shading. First the back face depths:

 Shader "Custom/Back Face Depths"
 {
     SubShader
     {
         Tags
         {
             "RenderType" = "Fog"
         }
 
         Pass
         {
             Fog { Mode Off }
             Lighting Off
             Cull Front
             
             CGPROGRAM
             #pragma target 3.0
             #pragma vertex vert
             #pragma fragment frag
             #include "UnityCG.cginc"
             
             struct v2f
             {
                 float4 pos : POSITION;
                 float2 depth : TEXCOORD0;
             };
             
             v2f vert( appdata_base v )
             {
                 v2f o;
                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                 COMPUTE_EYEDEPTH(o.depth);
                 
                 return o;
             }
             
             float4 frag(v2f i) : COLOR
             {
                 half4 d = i.depth.x / 20;
                 
                 half4 c;
                 c.r = d;
                 c.g = d;
                 c.b = d;
                 c.a = d;
                 
                 return c;
             }
             
             ENDCG
         }
     }
 }

And now the front face depths:

 Shader "Custom/Front Face Depths"
 {
     SubShader
     {
         Tags
         {
             "RenderType" = "Fog"
         }
         
         Pass
         {
             Fog { Mode Off }
             Lighting Off
             Cull Back
             
             CGPROGRAM
             #pragma target 3.0
             #pragma vertex vert
             #pragma fragment frag
             #include "UnityCG.cginc"
             
             struct v2f
             {
                 float4 pos : POSITION;
                 float2 depth : TEXCOORD0;
             };
             
             v2f vert( appdata_base v )
             {
                 v2f o;
                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                 COMPUTE_EYEDEPTH(o.depth);
                 
                 return o;
             }
             
             float4 frag(v2f i) : COLOR
             {
                 half4 d = i.depth.x / 20;
                 
                 half4 c;
                 c.r = d;
                 c.g = d;
                 c.b = d;
                 c.a = d;
                 
                 return c;
             }
             
             ENDCG
         }
     }
 }

Now, this is just a very simplified form of my final goal. Ultimately I won't be unpacking the depth textures before passing them over to the composite material, but for now I wanted to see that they were set up properly, and they seem to be. I can verify this by creating materials for each of them and applying them to a mesh--voila, back and front face depths are rendered.

So what's wrong? I suspect it may be my UVs in the VolumeFog shader, as I don't fully understand how to set those up, or it could be something wrong with my script handling the pipeline/property setup, or maybe something else entirely.

For the record, the above code compiles just fine, though the result is a fully transparent mesh. When I play with the Albedo/Alpha settings and input the f or b pixels respectively, they seem to be completely empty...

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · May 17, 2013 at 09:59 PM 0
Share

Looks to me like you need to get the fragments screen position for the UV in the volume shader part I'd imagine. See this: http://answers.unity3d.com/questions/448711/getting-a-pixels-screen-space-coordinate-in-a-frag.html

avatar image sgoodrow · May 17, 2013 at 10:20 PM 0
Share

I was wondering if that's what was going wrong. So to do that I need to generate the screen space position... Is this right? It still produces black:

float3 uv = mul((float3x3)UNITY_$$anonymous$$ATRIX_$$anonymous$$VP, IN.worldPos);

I tried using IN.screenPos as suggested here: http://docs.unity3d.com/Documentation/Components/SL-SurfaceShaderExamples.html but also to no avail, just black.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Represent Land 3D Area End 0 Answers

Unity Sphere object not displaying proper color away from camera 0 Answers

Cubemaps using the camera 0 Answers

Fog/color tint shader for orthographic camera 0 Answers

LineRenderer not showing in certain angles 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges