Triplanar Shader, using World Normals & Bump Mapping: HELP!

I can’t seem to get a working shader that takes in 3 textures, 3 bump maps and successfully shades an object with triplanar shading. Anytime I write to o.Normal, my objects simply go black. To simplify things, I’m trying to just apply 1 bump map as follows to otherwise standard triplanar shader:

Shader "Tri-Planar World" {

    Properties {
        _Side("Side", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        _Bottom("Bottom", 2D) = "white" {}
        _BumpMap("BumpMap", 2D) = "bump" {}
    }

    SubShader {

        Tags {
            "Queue" = "Geometry"
            "IgnoreProjector" = "False"
            "RenderType" = "Opaque"
        }

        Cull Back
        ZWrite On

        CGPROGRAM

        #pragma surface surf Standard
        #pragma exclude_renderers flash
        #pragma shader_feature _NORMALMAP_ON

        sampler2D _Side, _Top, _Bottom, _BumpMap;

        struct Input {
            float3 worldPos;
            float3 worldNormal;
#if _NORMALMAP_ON
            INTERNAL_DATA
#endif
        };

        void surf(Input IN, inout SurfaceOutputStandard o) {
            float3 projNormal = saturate(pow(IN.worldNormal * 1.4, 4));

            // SIDE X
            float3 x = tex2D(_Side, frac(IN.worldPos.zy * 0.7)) * abs(IN.worldNormal.x);

            // TOP / BOTTOM
            float3 y = 0;
            float absny = abs(IN.worldNormal.y);
            float2 fraczx = frac(IN.worldPos.zx * 0.7);
            if (IN.worldNormal.y > 0) {
                y = tex2D(_Top, fraczx) * absny;
            }
            else {
                y = tex2D(_Bottom, fraczx) * absny;
            }

            // SIDE Z 
            float3 z = tex2D(_Side, frac(IN.worldPos.xy * 0.7)) * abs(IN.worldNormal.z);

#if _NORMALMAP_ON
            o.Normal = UnpackNormal(tex2D(_BumpMap, fraczx) * absny);
#endif
            o.Albedo = z;
            o.Albedo = lerp(o.Albedo, x, projNormal.x);
            o.Albedo = lerp(o.Albedo, y, projNormal.y);
        }

        ENDCG
    }
    Fallback "Diffuse"
}

If I comment out the o.Normal line, my stuff looks fine (but no bump mapping, as expected). If I set o.Normal to apparently anything, even (0,1,0) – things still go black.

Here is a shader that supposedly does what I want:

… but the “world normal” it calculated in the vertex shader didn’t seem stable… as I moved around the scene, the normals of my objects would go whack.

If I modify my shader to try calculating the world normal as the linked one above is doing:

Shader "Tri-Planar World" {

    Properties {
        _Side("Side", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        _Bottom("Bottom", 2D) = "white" {}
        _BumpMap("BumpMap", 2D) = "bump" {}
    }

    SubShader {

        Tags {
            "Queue" = "Geometry"
            "IgnoreProjector" = "False"
            "RenderType" = "Opaque"
        }

        Cull Back
        ZWrite On

        CGPROGRAM

        #pragma surface surf Standard vert:vertWorld
        #pragma exclude_renderers flash
        #pragma shader_feature _NORMALMAP_ON

        sampler2D _Side, _Top, _Bottom, _BumpMap;

        struct Input {
            float3 worldPos;
            float3 thisNormal;
//#if _NORMALMAP_ON
//            INTERNAL_DATA
//#endif
        };

        void vertWorld(inout appdata_full v, out Input o) {
            o.thisNormal = mul(unity_ObjectToWorld, float4(v.normal, 0.0f)).xyz;
        }

        void surf(Input IN, inout SurfaceOutputStandard o) {
            float3 projNormal = saturate(pow(IN.thisNormal * 1.4, 4));

            // SIDE X
            float3 x = tex2D(_Side, frac(IN.worldPos.zy * 0.7)) * abs(IN.thisNormal.x);

            // TOP / BOTTOM
            float3 y = 0;
            float absny = abs(IN.thisNormal.y);
            float2 fraczx = frac(IN.worldPos.zx * 0.7);
            if (IN.thisNormal.y > 0) {
                y = tex2D(_Top, fraczx) * absny;
            }
            else {
                y = tex2D(_Bottom, fraczx) * absny;
            }

            // SIDE Z 
            float3 z = tex2D(_Side, frac(IN.worldPos.xy * 0.7)) * abs(IN.thisNormal.z);

#if _NORMALMAP_ON
            o.Normal = UnpackNormal(tex2D(_BumpMap, fraczx) * absny);
#endif
            o.Albedo = z;
            o.Albedo = lerp(o.Albedo, x, projNormal.x);
            o.Albedo = lerp(o.Albedo, y, projNormal.y);
        }

        ENDCG
    }
    Fallback "Diffuse"
}

… all upward facing textures are smeared in one direction & the normals (as I said before) are not stable (because I notice flickering surfaces in relation to my directional light).

I’m pulling my hair out & I can’t seem to figure out how to write a triplanar shader, that uses the world normal to blend 3 textures, and then apply a bump map.

Any help is greatly appreciated!

What’s the #pragma shader_feature _NORMALMAP_ON in there for? I would remove that, it’s unnecessary in a surface shader and may even be part of the problem.

Additionally this is going to be very hard to get working in a surface shader as it expects the o.Normal to be a tangent space normal that matches the tangent space of the original mesh. That is to say you’re using a normal map that uses the exact same UVs as the model was saved with, and not the UVs you’re generating from the world position. Anything you pass to o.Normal is going to get transformed from the model’s tangent space to world space or whatever space it needs for lighting. That means to use a surface shader you have to transform your normal maps into the models tangent space from your custom UV tangent space which is possible, but means some additional math.

Thank you for the response!

I have _NORMALMAP_ON because some materials may not have a normal map set, so I want that section removed if that is the case.

Is there a better way to go about this that wouldn’t require significant math? I’m not sure how to go about tangent spaces (never really understood that part).

I wonder if that other shader I linked ever worked with world position UVs?

Triplanar texturing with bump maps seems like it’d be a common situation for procedural terrain…

Are you toggling the _NORMALMAP_ON from code yourself? If not then it’s likely never even turning on normal maps. The standard shader has a custom editor that toggles the keyword on and off, and you can write your own custom editor to do the same or add a [Toggle] _NormalMap (“Enable Normal Map”, Float) = 0 to your property block.

As for if the shader in that link ever worked, looking through there’s one shader that’ll do something, but it won’t be remotely correct in any way. It would probably have looked fine with a sufficiently noisy normal map. I’m pretty sure the one Farfarer linked probably works and is doing things more correct, but I’ve not looked at the shader in his package. Also he probably isn’t using a surface shader which makes this particular problem a bit easier to deal with.

The short version is normal maps require some amount of math per tangent space to transform the direction from tangent to world space, and with potentially 6 different tangent spaces (optimizable down to 3 at a time) that’s math you will have to do for a triplanar shader with normal maps. The problem with surface shaders is you are adding two more transforms that you cannot avoid as you have to convert from the triplanar tangent space to world space, back to the mesh’s tangent space so the surface shader can conver it back to world space. You can do some of that before hand in the vertex shader so you only have to do the transform from triplanar tangent space to mesh UVs tangent space once per side in the surface shader function, but it’s annoying and again way easier to just go straight to world in a vertex / fragment shader.

Yes, I am toggling the _NORMALMAP_ON keyword from code myself when a bump map gets set.

GOOD NEWS! I made some progress & I feel SOOOOO CLOSE, but it still isn’t working 100%. If I look mostly down at the surface, it works exactly as I want: I see the bumping on the top surface & it is using my world normals & world position as the UV maps. However, if I turn a certain way or look up, the bump map seems to disappear. It seems to disappear & reappear immediately, based on the angle / rotation I’m looking at the surface (it doesn’t fade in and out). Overall lighting doesn’t change – just the bump map’s visibility:

Shader "Tri-Planar World" {

    Properties {
        _Side("Side", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        _Bottom("Bottom", 2D) = "white" {}
        _BumpMap("NormalMap 1 (_Y_X)", 2D) = "bump" {}
    }

    SubShader {

        Tags {
            "Queue" = "Geometry"
            "IgnoreProjector" = "False"
            "RenderType" = "Opaque"
        }

        Cull Back
        ZWrite On

        CGPROGRAM

        #include "UnityCG.cginc"

        #pragma surface surf BlinnPhong vertex:vertWorld
        #pragma exclude_renderers flash
        #pragma shader_feature _NORMALMAP_ON

        sampler2D _Side, _Top, _Bottom, _BumpMap;

        struct Input {
            float3 worldPos;
            float3 thisNormal;
        };

        // Vertex program is determined in pragma above
        void vertWorld(inout appdata_full v, out Input o)
        {
            o.thisNormal = UnityObjectToWorldNormal(v.normal.xyz);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex);
        }

        void surf(Input IN, inout SurfaceOutput o) {
            float3 projNormal = saturate(pow(IN.thisNormal * 1.4, 4));

            // SIDE X
            float3 x = tex2D(_Side, frac(IN.worldPos.zy * 0.7)) * abs(IN.thisNormal.x);

            // TOP / BOTTOM
            float3 y = 0;
            float absny = abs(IN.thisNormal.y);
            float2 fraczx = frac(IN.worldPos.zx * 0.7);
            if (IN.thisNormal.y > 0) {
                y = tex2D(_Top, fraczx) * absny;
            }
            else {
                y = tex2D(_Bottom, fraczx) * absny;
            }

            // SIDE Z  
            float3 z = tex2D(_Side, frac(IN.worldPos.xy * 0.7)) * abs(IN.thisNormal.z);

#if _NORMALMAP_ON
            // Sample bump maps too, and generate bump vectors. (Note: this uses an oversimplified tangent basis.)
            // Using Unity packed normals (_Y_X), but we don't unpack since we don't need z.                  
            half2 bumpVec1 = tex2D(_BumpMap, fraczx).wy * 2 - 1;      // To use standard normal maps change wy to xy

            half3 bump1 = half3(0, bumpVec1.x, bumpVec1.y);

            o.Normal = normalize(half3(0, 0, 1) + bump1);
#endif

            o.Albedo = z;
            o.Albedo = lerp(o.Albedo, x, projNormal.x);
            o.Albedo = lerp(o.Albedo, y, projNormal.y);
        }

        ENDCG
    }
    Fallback "Diffuse"
}

That’ll get you something in the normals, but not what you really want. You’ll randomly get normals that are inverted, or flatten out depending on where on the model you’re looking.

Here’s a version of your shader with a bunch of stuff cleaned up, and “good enough” triplanar normals.

Shader "Tri-Planar World" {

    Properties {
        _Side("Side", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        [NoScaleOffset] _Bottom("Bottom", 2D) = "white" {}
        [NoScaleOffset] _BumpMap("NormalMap", 2D) = "bump" {}
    }

    SubShader {

        Tags {
            "Queue" = "Geometry"
            "IgnoreProjector" = "False"
            "RenderType" = "Opaque"
        }

        Cull Back
        ZWrite On

        CGPROGRAM

        #include "UnityCG.cginc"

        #pragma surface surf BlinnPhong vertex:vertWorld
        #pragma exclude_renderers flash
        #pragma target 3.0

        sampler2D _Side, _Top, _Bottom, _BumpMap;
        float4 _Side_ST, _Top_ST;

        struct Input {
            float4 worldToTangent0;
            float4 worldToTangent1;
            float4 worldToTangent2;
            float3 worldPos;
            INTERNAL_DATA
        };

        // Vertex program is determined in pragma above
        void vertWorld(inout appdata_full v, out Input o)
        {
            UNITY_INITIALIZE_OUTPUT(Input,o);

            // really shouldn't have to do this, but looks like surface shaders are bugged
            // and aren't passing the world normal to the surface shader with using:
            // struct Input { float3 worldNormal; }
            // luckily we have free float3 so we don't need another interpolator
            float3 worldNormal = UnityObjectToWorldNormal(v.normal);

            // unity macro for getting the object to tangent space matrix as var "rotation"
            TANGENT_SPACE_ROTATION;

            // calculate the full world to tangent matrix
            float3x3 worldToTangent = mul(rotation, (float3x3)unity_WorldToObject);
            o.worldToTangent0 = float4(worldToTangent[0], worldNormal.x);
            o.worldToTangent1 = float4(worldToTangent[1], worldNormal.y);
            o.worldToTangent2 = float4(worldToTangent[2], worldNormal.z);
        }

        void surf(Input IN, inout SurfaceOutput o) {
            // extract world normal from the unused w component of world to tangent matrix
            float3 worldNormal = float3(IN.worldToTangent0.w, IN.worldToTangent1.w, IN.worldToTangent2.w);
            float3 projNormal = saturate(pow(worldNormal * 1.4, 4));

            // "normalize" projNormal x+y+z to equal 1, ensures even blend
            projNormal /= projNormal.x + projNormal.y + projNormal.z;

            // SIDE X
            float xsign = sign(worldNormal.x);
            float2 zy = IN.worldPos.zy * float2(xsign, 1.0) * _Side_ST.xy + _Side_ST.zw;
            float3 xAlbedo = tex2D(_Side, zy);
            float3 xNorm = UnpackNormal(tex2D(_BumpMap, zy));
            // xNorm.z *= xsign; // flip normal based on +/- x

            // TOP / BOTTOM
            float ysign = sign(worldNormal.y);
            float2 zx = IN.worldPos.zx * _Top_ST.xy + _Top_ST.zw;
            float yAlbedo = ysign > 0 ? tex2D(_Top, zx) : tex2D(_Bottom, zx);
            float3 yNorm = UnpackNormal(tex2D(_BumpMap, zx));
            // yNorm.z *= ysign;

            // SIDE Z
            float zsign = sign(worldNormal.z);
            float2 xy = IN.worldPos.xy * float2(-zsign, 1.0) * _Side_ST.xy + _Side_ST.zw;
            float3 zAlbedo = tex2D(_Side, xy);
            float3 zNorm = UnpackNormal(tex2D(_BumpMap, xy));
            // zNorm.z *= zsign; // flip normal based on +/- z

            // use "UDN" style normal blending to wrap normal map to surface normal
            // prevents normals from just being on a "box"
            // world normal components are swizzled so their major axis is along "z", normal map-like
            xNorm = normalize(float3(xNorm.xy * float2(xsign, 1.0) + worldNormal.zy, worldNormal.x));
            yNorm = normalize(float3(yNorm.xy + worldNormal.zx, worldNormal.y));
            zNorm = normalize(float3(zNorm.xy * float2(-zsign, 1.0) + worldNormal.xy, worldNormal.z));

            // reorient normal maps to their world axis by swizzling the components
            xNorm = xNorm.zyx; // hackily swizzle channels to match unity "right"
            yNorm = yNorm.yzx; // hackily swizzle channels to match unity "up"
            zNorm = zNorm.xyz; // no swizzle needed!

            // blend normals together
            float3 wNorm = xNorm * projNormal.x + yNorm * projNormal.y + zNorm * projNormal.z;

            // transform world space normals back to tangent space so that the surface shader
            // can transform them back to world space.
            o.Normal = normalize(
                float3(
                    dot(wNorm, IN.worldToTangent0.xyz),
                    dot(wNorm, IN.worldToTangent1.xyz),
                    dot(wNorm, IN.worldToTangent2.xyz)
                    )
                );

            // blend albedos together
            o.Albedo = xAlbedo * projNormal.x + yAlbedo * projNormal.y + zAlbedo * projNormal.z;
        }

        ENDCG
    }
    Fallback "Diffuse"
}

Note: This is terrible and no one should use this.

There’s a ton of unnecessary computation being done just to work around surface shaders which is why when people do these kinds of shaders they don’t use surface shaders. Also, this still isn’t actually correct, but it’s close enough that it’s hard to tell it’s wrong.

3 Likes

If that is terrible & shouldn’t be done as a surface shader, how should it be done?

With a straight vertex fragment shader.

Most of that code is fine, hacky but fine. It’s a fairly decent approximation of world space triplanar normal maps and perfectly valid to use. The stuff that’s ugly are lines 53-59 and lines 108 - 114, they only exist to get stuff working in a surface shader.

One way you could go is to take that surface shader, select it in the editor, click on “show generated code” and cut that shader down. That can be kind of scary though as surface shaders generate some fairly dense and occasionally obtuse code. A better route would be to learn to write an equivalent shader from scratch, or close to.

This page is a great resource for understanding how shaders work. It starts a little scary looking, but work through it. All 5 parts.

And this page has most of the bits needed to make a shader that’s equivalent to the functionality of the surface shader, though not all in one shader and is missing deferred support which the surface shader does have.

I’ve written vertex and fragment shaders before for non-Unity titles. I had to do everything in those cases, like my own lighting. I want to leverage Unity’s automation wherever possible. I also want this to work with single-pass VR rendering. Would writing my own vertex and fragment shaders require getting my hands dirty in those areas?

Another thought… can I relatively easily detect when the normals would be flat or inverted in my version, and counteract it? Ultimately I don’t care how correct it is, I just want it to be applied somehow & stable (so my surfaces are not always flat).

Adding support for single pass rendering can be done in about 3 lines of shader code. Almost all of it is done in macros; a line in the v2f, a line in the vertex function, and a line in the fragment shader.

The way to detect if the normals are going to be flipped is by calculating the inverse tangent matrix, in which case it ends up being faster / cheaper / more accurate to just apply that rotation matrix than try decode it to see if it’ll be wrong with out it… which is exactly what that example shader does.

If you’re set on using surface shaders the code above does work, and can be used, but even if you were to write the shader out “from scratch” you would end up using a lot of built in functions and macros for the majority of the more complex bits of code so it’s not really from scratch, it’s more a case of knowing what to use. That example page is a great reference, as is looking at the generated shader code if for nothing else but seeing what it’s using if not trying to modify it.

All of this boils down to surface shaders expecting the value set on o.Normal to be in mesh UV tangent space, which it then transforms into world space before doing lighting. There’s no avoiding that, it’s just what surface shaders are going to do. This is unfortunate because it’s usually fairly easy to generate world space normals when doing world space triplanar mapping, so for example in that above shader by line 104 we already have the world space normal Unity wants for lighting.

Maybe you need to get your head around normal maps and tangent space for this to make sense.

Tangent space is just the surface normal (the direction a surface is facing) and the orientation of the texture UVs. If you were to draw a texture with a red arrow pointing to the right and a green arrow pointing up and applied that to a surface the direction the arrows point are literally the tangent and binormal (sometimes called bitangent) directions. A normal map is then storing how far left & right or up & down off from the surface normal direction, towards those red and green arrows, it should look like the surface is facing.

The math is minorly more complex than that, but only a little. The math for calculating those directions to begin with is more complex which is why it’s usually stored in the mesh as the normal and tangent values.

When you’re doing world space triplanar mapping because the UVs you’re generating don’t match the mesh’s original UVs usually you can just ignore them and the tangent directions that were calculated for those UVs. Because you’re working in world space you can fake the tangent and binormal directions by just using world space directions. The common thing to do then is to adjust the tangent and binormal by using some vector math (a couple of cross() calls), which will result in essentially perfect normal mapping, but I went with a normal blending technique that gets you 95% of the way with less math.

I am not set on using surface shaders, it is just what I tried to use first. If it is more efficient to use vertex and fragment shaders, then that is what I should use. A little disappointing, though, since one reason for switching to Unity was to avoid writing my own raw shaders.

Every example I’ve seen thus far has been of a surface shader. A bit daunting, and feeling like more uncharted area to delve into, to write straight vertex and fragment shaders with Unity.

I’d use your surface shader, but I’m worried it is inefficient… especially when I’m planning on bringing this title to VR.

Thank you for all of your help this far… was hoping this wasn’t going to be so complicated :-/

Surface shaders are great for a lot of things. You just picked one of the few things surface shaders aren’t great at.

@bgolus , I tried out your shader above & it suffered the same problem mine has been having: instability. As I turn around, the bumps on a surface will blink in & out. It also appears lighting is screwy, as when bumps blink in & out, the overall brightness of the surface changes. It seems to happen at specific rotations, either it will look good, flat or act like the normal is looking in a completely different direction. If it helps, I’m sharing the material across many different objects that are being resized & rotated – but isn’t that suppose to be the benefit of world positioning triplanar shaders, you can apply them to anything at any rotation?

That is … odd. Sounds like batching going wrong.

I do share the material on low-poly models next to eachother. I did this to hopefully & specifically benefit from dynamic batching. I’m heading to bed so I can’t test disabling that feature (player option, I think?) at the moment. Perhaps I should somehow statically batch my objects once I am done creating them? Any suggestions to get around this if batching is to blame? Disabling batching may bring a nasty performance hit…

Here’s that shader as a vertex / fragment shader (sans support for lightmaps or deferred lighting). It’s also just Lambert diffuse instead of Blinn Phong specular (but since your original shader wasn’t using Specular or Gloss values meant it was just Lambert anyway).

Curious if you still have problems with this code.

Shader "Triplanar Bumped"
{
    Properties {
        _Side("Side", 2D) = "white" {}
        _Top("Top", 2D) = "white" {}
        [NoScaleOffset] _Bottom("Bottom", 2D) = "white" {}
        [NoScaleOffset] _BumpMap("NormalMap", 2D) = "bump" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        CGINCLUDE
        #include "HLSLSupport.cginc"
        #include "UnityShaderVariables.cginc"  
        #include "UnityCG.cginc"
   
        sampler2D _Side, _Top, _Bottom, _BumpMap;
        float4 _Side_ST, _Top_ST;

        void GetTriplanarTextures(float3 worldPos, float3 worldNormal, out fixed4 albedo, out half3 normal)
        {
                // extract world normal from the unused w component of world to tangent matrix
                float3 projNormal = saturate(pow(worldNormal * 1.4, 4));

                // "normalize" projNormal x+y+z to equal 1, ensures even blend
                projNormal /= projNormal.x + projNormal.y + projNormal.z;
   
                // SIDE X
                float xsign = sign(worldNormal.x);
                float2 zy = worldPos.zy * float2(xsign, 1.0) * _Side_ST.xy + _Side_ST.zw;
                fixed4 xAlbedo = tex2D(_Side, zy);
                half3 xNorm = UnpackNormal(tex2D(_BumpMap, zy));
                // xNorm.z *= xsign; // flip normal based on +/- x
   
                // TOP / BOTTOM
                float ysign = sign(worldNormal.y);
                float2 zx = worldPos.zx * _Top_ST.xy + _Top_ST.zw;
                fixed4 yAlbedo = ysign > 0 ? tex2D(_Top, zx) : tex2D(_Bottom, zx);
                half3 yNorm = UnpackNormal(tex2D(_BumpMap, zx));
                // yNorm.z *= ysign;
   
                // SIDE Z
                float zsign = sign(worldNormal.z);
                float2 xy = worldPos.xy * float2(-zsign, 1.0) * _Side_ST.xy + _Side_ST.zw;
                fixed4 zAlbedo = tex2D(_Side, xy);
                half3 zNorm = UnpackNormal(tex2D(_BumpMap, xy));
                // zNorm.z *= zsign; // flip normal based on +/- z

                // use normal blending to wrap normal map to surface normal
                xNorm = normalize(half3(xNorm.xy * float2(xsign, 1.0) + worldNormal.zy, worldNormal.x));
                yNorm = normalize(half3(yNorm.xy + worldNormal.zx, worldNormal.y));
                zNorm = normalize(half3(zNorm.xy * float2(-zsign, 1.0) + worldNormal.xy, worldNormal.z));

                // reorient normals to their world axis
                xNorm = xNorm.zyx; // hackily swizzle channels to match unity "right"
                yNorm = yNorm.yzx; // hackily swizzle channels to match unity "up"
                zNorm = zNorm.xyz; // no swizzle needed

                // blend normals together
                normal = xNorm * projNormal.x + yNorm * projNormal.y + zNorm * projNormal.z;
   
                // blend albedos together
                albedo = xAlbedo * projNormal.x + yAlbedo * projNormal.y + zAlbedo * projNormal.z;
        }
        ENDCG

        Pass
        {
            Tags { "LightMode"="ForwardBase" }

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0
            #pragma multi_compile_fog
            #pragma multi_compile_fwdbase
            #include "Lighting.cginc"
            #include "AutoLight.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float3 worldNormal : NORMAL;
                float3 worldPos : TEXCOORD0;
                SHADOW_COORDS(1)
                UNITY_FOG_COORDS(2)
            };
          
            v2f vert (appdata v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                TRANSFER_SHADOW(o);
                UNITY_TRANSFER_FOG(o,o.pos);
                return o;
            }
          
            half4 frag (v2f i) : SV_Target
            {
                fixed4 albedo;
                half3 normal;
                GetTriplanarTextures(i.worldPos, i.worldNormal, albedo, normal);
              
                UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
                half3 lighting = saturate(dot(normalize(normal), _WorldSpaceLightPos0.xyz)) * _LightColor0.rgb * atten;
                lighting += ShadeSH9(half4(normal,1));

                half3 col = albedo.rgb * lighting;

                UNITY_APPLY_FOG(i.fogCoord, col);
                return half4(col, 1);
            }
            ENDCG
        }

        Pass
        {
            Tags { "LightMode"="ForwardAdd" }
            ZWrite Off Blend One One

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0
            #pragma multi_compile_fog
            #pragma multi_compile_fwdadd_fullshadows
            #include "Lighting.cginc"
            #include "AutoLight.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float3 worldNormal : NORMAL;
                float3 worldPos : TEXCOORD0;
                SHADOW_COORDS(1)
                UNITY_FOG_COORDS(2)
            };
          
            v2f vert (appdata v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                TRANSFER_SHADOW(o);
                UNITY_TRANSFER_FOG(o,o.pos);
                return o;
            }
          
            half4 frag (v2f i) : SV_Target
            {
                fixed4 albedo;
                half3 normal;
                GetTriplanarTextures(i.worldPos, i.worldNormal, albedo, normal);
              
                UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);

            #ifndef USING_DIRECTIONAL_LIGHT
                fixed3 lightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
            #else
                fixed3 lightDir = _WorldSpaceLightPos0.xyz;
            #endif
                half3 lighting = saturate(dot(normalize(normal), lightDir)) * _LightColor0.rgb * atten;

                half3 col = albedo.rgb * lighting;

                UNITY_APPLY_FOG(i.fogCoord, col);
                return half4(col, 1);
            }
            ENDCG
        }

        Pass
        {
            Tags {"LightMode"="ShadowCaster"}

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_shadowcaster
            #include "UnityCG.cginc"

            struct v2f {
                V2F_SHADOW_CASTER;
            };

            v2f vert(appdata_base v)
            {
                v2f o;
                TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
                return o;
            }

            float4 frag(v2f i) : SV_Target
            {
                SHADOW_CASTER_FRAGMENT(i)
            }
            ENDCG
        }
    }
}
1 Like

That one works & is stable! :smile:

I’m OK skipping gloss & specular, but I do want to make sure single-pass VR rendering will work. You mention it being done in a few lines. It doesn’t look like it is included yet? I presume there is an include & macro use somewhere…

In the v2f struct:
UNITY_VERTEX_OUTPUT_STEREO

In the vert function:
// at the start of the vert function
UNITY_SETUP_INSTANCE_ID(v);
…
// at the end of the vert function just before return o;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);

1 Like

Looks familiar :slight_smile: I wrote my own VR instancing library for jMonkeyEngine. I didn’t have to modify the fragment shaders & you didn’t mention a change required above. You did mention a line in the fragment shader a few posts back, though. Just to confirm, that is all that is needed are those vertex macros?

No, nothing needed in the fragment shader, just misremembering what was needed. (and I have done some custom shaders that do extra stuff in the fragment shader per eye).