碧血红天的HomePage

U3d杂谈 — 实现简单平面阴影

今天学会了如何通过Shader制作一个平面阴影。平面阴影顾名思义就是再一个平面上投影出影子。但是也只能投影再水平面上,如果周围存在物体和墙面就不能正常表现了。但是好处是效率高,消耗小,但是模型面试翻倍,视情况而定。对于完全在一个平面的上投影的游戏很合适。而且可以不用开启灯光和模型材质启用影子,完全通过模型计算的一个假影子。

思想原理

就是我们把模型的顶点投影在一个平面上,大部分是在一个Y=0的XZ平面上。我们在顶点着色器中计算出模型顶点投影到平面上的点。然后把这些点的颜色设置成影子颜色。我们需要开一个Pass专门来绘制这个影子。

计算的过程就是光照方向通过顶点的直线与平面交点。

如上图所示,红色是光线的方向上的射线。现在我们需要计算红色的先经过顶点在平面上的交点。蓝色线的方向我们是已知的,因为我们投影在XZ平面,所以蓝色线的方向就是(0,1,0).红色线的方向就是光线方向,也能在Shader中直接得到。蓝色线的高度就是顶点在世界空间下的Y的大小(如果是在Y=0的平面上的话)。红色线的长度的计算就是蓝色线的高度除以红色与蓝色线的Cos(夹角)。这是三角函数。那交点就是顶点沿红线方向移动红线的长度。计算影子投影点如下:

float3 ShadowProjectPos(float4 vertPos)
        {
            float3 shadowPos;

            //得到顶点的世界空间坐标
            float3 worldPos = mul(unity_ObjectToWorld , vertPos).xyz;

            //灯光方向
            float3 lightDir = normalize(_WorldSpaceLightPos0.xyz);

            //阴影的世界空间坐标(低于地面的部分不做改变)
            shadowPos.y = min(worldPos.y , _GroundHeight);
            float t = dot(lightDir, half3(0, 1, 0));
            if (t < 0)
            {
                shadowPos.xyz = float3(0, 0, 0);
            }
            else {
                shadowPos.xyz = worldPos.xyz - lightDir.xyz * max(0, worldPos.y - _GroundHeight) / t;
            }
            
            return shadowPos;
        }

上面我们判断了t是否是负数,来排除掉灯光朝上的时候,这时不能存在影子。

其它过程就是跟绘制一个模型一样,完整的Shader如下:

Shader "Custom/PlanarShadow"
{
    Properties
    {
    _GroundHeight("_GroundHeight", Float) = 0
    _ShadowColor("_ShadowColor", Color) = (0,0,0,1)
    }
        SubShader
    {
    
        // Planar Shadows平面阴影
        Pass
        {
            Name "PlanarShadow"
            Cull Off

        //透明混合模式
        Blend SrcAlpha OneMinusSrcAlpha

        //关闭深度写入
        ZWrite off

        //深度稍微偏移防止阴影与地面穿插
        Offset -1 , 0

        CGPROGRAM
        #include "UnityCG.cginc"

        #pragma vertex vert
        #pragma fragment frag

        float _GroundHeight;
        float4 _ShadowColor;

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float4 vertex : SV_POSITION;
            float4 color : COLOR;
            float2 uv : TEXCOORD0;
        };

        float3 ShadowProjectPos(float4 vertPos)
        {
            float3 shadowPos;

            //得到顶点的世界空间坐标
            float3 worldPos = mul(unity_ObjectToWorld , vertPos).xyz;

            //灯光方向
            float3 lightDir = normalize(_WorldSpaceLightPos0.xyz);

            //阴影的世界空间坐标(低于地面的部分不做改变)
            shadowPos.y = min(worldPos.y , _GroundHeight);
            float t = dot(lightDir, half3(0, 1, 0));
            if (t < 0)
            {
                shadowPos.xyz = float3(0, 0, 0);
            }
            else {
                shadowPos.xyz = worldPos.xyz - lightDir.xyz * max(0, worldPos.y - _GroundHeight) / t;
            }
            
            return shadowPos;
        }

        v2f vert(appdata v)
        {
            v2f o;

            //得到阴影的世界空间坐标
            float3 shadowPos = ShadowProjectPos(v.vertex);

            //转换到裁切空间
            o.vertex = UnityWorldToClipPos(shadowPos);

            //阴影颜色
            o.color = _ShadowColor;
            o.color.a = 1;

            o.uv = TRANSFORM_TEX(v.uv, _MainTex);

            return o;
        }

        fixed4 frag(v2f i) : SV_Target
        {
            return i.color;
        }
        ENDCG
    }
    }
        // FallBack "Diffuse"
}

URP中的写法如下:

 Pass {
                Name "PlanarShadow"
                Cull Off
                Blend SrcAlpha OneMinusSrcAlpha
                ZWrite off
                Offset -1, 0
                HLSLPROGRAM
                #pragma shader_feature _CLIPPING
                #pragma shader_feature _ALPHATEST_ON
                #pragma shader_feature _ALPHAPREMULTIPLY_ON

                #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
                #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
                #pragma vertex vert
                #pragma fragment frag
                
                float _GroundHeight;
            half4 _ShadowColor;

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float4 color : COLOR;
            };

            float3 ShadowProjectPos(float4 vertPos)
            {
                float3 shadowPos;
          
                //得到顶点的世界空间坐标
                float3 worldPos = mul(unity_ObjectToWorld, vertPos).xyz;

                //灯光方向
                Light mainLight = GetMainLight();
                float3 lightDir = normalize(mainLight.direction);
                // float3 lightDir = normalize(_LightDir.xyz);
                //float3 lightDir = normalize(_MainLightPosition.xyz);

                //阴影的世界空间坐标(低于地面的部分不做改变)
                shadowPos.y = min(worldPos.y, _GroundHeight);
                float t = dot(lightDir, half3(0, 1, 0));
                if (t < 0)
                {
                    shadowPos.xyz = float3(0, 0, 0);
                }
                else {
                    shadowPos.xyz = worldPos.xyz - lightDir.xyz * max(0, worldPos.y - _GroundHeight) / t;
                }


                return shadowPos;
            }

            v2f vert(appdata v)
            {
                v2f o;

                //得到阴影的世界空间坐标
                float3 shadowPos = ShadowProjectPos(v.vertex);

                //转换到裁切空间
                //o.vertex = UnityWorldToClipPos(shadowPos);
                o.vertex = TransformWorldToHClip(shadowPos);

                //阴影颜色
                o.color = _ShadowColor;
                o.color.a = 1;

                return o;
            }

            half4  frag(v2f i) : SV_Target
            {
                return i.color;
            }
                ENDHLSL
        }

60 评论

  1. I conceive other website proprietors should take this site as an model, very clean and wonderful user pleasant design.

  2. Very great visual appeal on this web site, I’d value it 10 10.

  3. hi opp ggeis 2022 ert go fi

  4. This web site is really a walk-through for all of the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll definitely discover it.

  5. In a particular embodiment, rebaudioside M is present in the cereal composition in an amount in the range of about 0 what are the side effects of tamoxifen Prat A, Galvan P, Jimenez B, Buckingham W, Jeiranian HA, Schaper C, et al

  6. Thanks – Enjoyed this article, how can I make is so that I receive an update sent in an email whenever you make a new update?

  7. I am glad for writing to let you know what a wonderful encounter our girl encountered viewing your site. She figured out some things, most notably how it is like to possess a wonderful helping heart to get certain people without problems know chosen impossible matters. You actually surpassed our own desires. Thank you for producing such productive, safe, informative and also easy thoughts on that topic to Janet.

  8. However, lentivirus ChP transduction is reported to be somewhat variable in adult mice 89 cheap valtrex pills 3 day delivery Examples of such therapeutic strategies include efforts to 1 expand effector T cells, natural killer NK cells and immunostimulatory dendritic cells DCs, 2 improve antigen presentation, and 3 decrease inhibitory cytokines, tumor associated M2 macrophages, regulatory T and B cells and myeloid derived suppressor cells MDSCs

  9. nolvadex The FDA released a statement in 2012 that a single dose of 32mg IV can prolong the QT interval and potentially cause torsades de pointes

  10. 2018; Zhou et al buy cialis Director Mogen can rest assured, hope so, Mogen stood foods lo lower blood pressure up and was about to leave, but he suddenly reminded Kevin, don t forget the Black Clothes Club

  11. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is valuable and all. But think of if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this website could definitely be one of the greatest in its field. Fantastic blog!

  12. My brother suggested I might like this web site. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  13. Exactly what I was looking for, thanks for putting up.

  14. Enjoyed reading through this, very good stuff, appreciate it.

  15. I?¦ve been exploring for a bit for any high quality articles or weblog posts on this sort of space . Exploring in Yahoo I eventually stumbled upon this web site. Reading this information So i am happy to convey that I have an incredibly good uncanny feeling I found out exactly what I needed. I such a lot definitely will make sure to don?¦t omit this website and give it a look regularly.

  16. Great tremendous issues here. I?¦m very satisfied to peer your article. Thank you so much and i am having a look ahead to touch you. Will you please drop me a e-mail?

  17. I?¦ve learn several good stuff here. Definitely worth bookmarking for revisiting. I wonder how so much attempt you place to create this kind of excellent informative website.

  18. Perfectly pent articles, appreciate it for selective information. “The earth was made round so we would not see too far down the road.” by Karen Blixen.

  19. Great – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Nice task..

  20. I simply wished to thank you so much once more. I’m not certain what I would’ve made to happen in the absence of the type of tips provided by you about such area of interest. Entirely was the frightful crisis in my opinion, however , being able to see the very expert style you solved it took me to weep with delight. I will be thankful for your guidance and thus believe you really know what a powerful job you happen to be getting into instructing most people by way of your blog. Probably you have never got to know any of us.

  21. I like this website so much, saved to bookmarks.

  22. Perfect piece of work you have done, this website is really cool with good info .

  23. Whoa! This blog looks exactly like my old one! It’s on a totally different subject but it has pretty much the same page layout and design. Outstanding choice of colors!

  24. I?¦m now not sure where you are getting your information, but great topic. I needs to spend a while studying more or working out more. Thanks for great information I used to be on the lookout for this info for my mission.

  25. buy cialis shipment to russia tadalafil online sublingual how long does it take for tadalafil to work

  26. where to get cheap viagra best site to buy viagra online need prescription for viagra

  27. cheap generic cialis canada where can i buy tadalafil erectivin vi non prescription tadalafil reviews

  28. cialis online safe cialis ed is generic cialis available

  29. pay cialis with paypal what is cialis where can i buy cialis over the counter

  30. pharmacy checker post haste pharmacy viagra best online pharmacy to buy vicodin

  31. promethazine with codeine online pharmacy costco pharmacy atorvastatin recall toronto pharmacy viagra

  32. canadian pharmacy price comparison lexapro indian pharmacy gabapentin canadian pharmacy

  33. mexican online pharmacy oxycodone Periactin hot canadian pharmacy review

  34. tramadol online canadian pharmacy pet pharmacy canada trusted online pharmacy viagra

  35. my canadian pharmacy rx amoxicillin lloyds pharmacy great lakes pharmacy tramadol

  36. See Methods for details on the re analysis of the experimental data from the literature ordering tamoxifen and clomid

  37. sildenafil for women viagra 25mg cost where can i buy over the counter sildenafil

  38. viagra online rx viagra 25 mg online purchase viagra without prescription

  39. where to buy female viagra uk generic viagra online usa how can you get viagra

  40. where to buy sildenafil online buy viagra generic how to get viagra in mexico

  41. buy cialis without doctor prescription unicure remedies tadalafil cialis cheap free shipping

  42. cialis generic vs brand free coupon for cialis order original cialis

  43. A distinctive subtype affecting armpits, groin and the sides of the neck has been described cialis coupons To understand molecular diversity among projection neurons, we developed Epi retro seq 45 which combines retrograde tracing and epigenomic profiling and applied it to mouse MOp neurons projecting to each of the eight selected brain regions receiving inputs from MOp Fig

  44. Review of hepatotoxicity of cardiovascular agents, mentions that thiazide diuretics can rarely cause cholestatic hepatitis but no mention of other types of diuretics cheap generic cialis

  45. cialis super active real online store what is tadalafil cialis con alimentos

  46. cialis canada purchase cialis edmonton what is cialis taken for

  47. is tadalafil as good as cialis how fast does tadalafil work does cialis work

  48. online viagra united states viagra 50mg price in india online viagra online with paypal

  49. Zhang Hai looked is 127 80 high blood pressure at Chen Qingshan and said lightly buy cialis 5mg daily use viagra pregabalin methylcobalamin capsules uses in hindi Al Shabab is warning Kenya could be hit by more bloodshed if its military isn t withdrawn from southern Somalia

  50. tadalafil 5 mg tablet where to buy generic cialis brand cialis no prescription

发表评论