Per-Object Clipping Planes Shader in Unity3D 5

For a project of mine, I wanted to have custom clipping planes for objects, so that if an object is intersection with another, it would hide any part after the intersection.

It looks like this:

I decided to extend the Standard shader provided by Unity3D to achieve this effect.

If you do not care about the technical details, skip to the bottom!

Some Background

Warning, this post will get quite technical.

You can find the Unity3D shader sources from theΒ Unity3D Download Archive.

A clipping plane can be defined by 2 vectors, a position and a normal.

These two vectors can be used to check whether parts of shapes are in front or behind the plane. We keep the parts in front, and hide the parts behind.

Wolfram Mathworld describes the algorithm to get the distance of a point to a plane. Here it is in code:

In order to find which parts of the objects are to be clipped, we need to extract the world coordinate of all points to be rendered. This is already done for most of the standard shader’s vertex programs:

In the fragment programs, we can then use the clip function with the distance to the plane as the parameter. If the clip function is called with any number less than zero, it will discard the current pixel. This is perfect, because if the distance to the plane is less than zero, a point is behind the plane.

If you have more planes, you can call clip with float2, float3, float4 parameters, or call clip multiple times. For example:

All we need to do now is change all passes of the Standard shader and modify the vertex and fragment programs to call this function.

We will use Unity3D’s wonderful shader program variants feature for this, so that if we do not want any clipping planes it will not cause any performance hits as the code will just be eliminated in that case. The CLIP_TWO and CLIP_THREE definitions are produced by the shader variant system, because in each pass we will have this directive :

It basically tells Unity3D’s shader compiler to generate four variants of the shader, a variant with no clipping planes, a variant with one clipping plane, another variant with two clipping planes, and the last one with three. We can choose how many clipping planes we want to use, by for example enabling the CLIP_ONE keyword, or the CLIP_TWO keyword. The method to enable keywords is: Material.EnableKeyword.

Let’s go!

Create a new shader called StandardClippable.shader, and place it in your project’s Assets/Shaders directory. Copy the contents of the Standard.shader file in the builtin_shaders zip, which can be found inside the DefaultResourcesExtra directory. Paste into the StandardClippable.shader. Change the first line to be:

Shader "Custom/StandardClippable".

Add the properties for the plane positions and normals, so that the properties block will look like this:

We just added the lines after 41.

We will create a helper .cginc file named “plane_clipping.cginc”. Here is its contents:

The comments in the above file should explain what it is doing.

The next step is to use the PLANE_CLIP macro in the fragment programs of all passes.

The First Pass

Let’s look at the FORWARD pass for example:

The lines which are important are 28, 29 and 31. This pass uses the vertForwardBase vertex program, and the fragForwardBase fragment program. These programs are defined in the UnityStandardCore.cginc file.

So, find the UnityStandardCore.cginc file in the default shaders zip. Make a copy of it, and save it as standard_clipped.cginc next to our StandardClippable.shader file.

Change all references of “UnityStandardCore.cginc” to be “standard_clipped.cginc” instead.

Also, add the line
#pragma multi_compile __ CLIP_ONE CLIP_TWO CLIP_THREE
just above the include lines. The forward pass should now look like this:

And your Shaders folder should now have three files:

  • StandardClippable.shader
  • plane_clipping.cginc and
  • standard_clipped.cginc

Let’s open the standard_clipped.cginc file. Add this line to the top of the file:

#include "plane_clipping.cginc"

Place it just below the include for AutoLight.cginc. This now allows us to use the functions and macros defined in that file.

We will be editing the vertex program first. Here it is as copied from the file:

The vertex program will need to pass the world position to the fragment program. It currently does so only if UNITY_SPECCUBE_BOX_PROJECTION is defined (relevant lines in above snippet: 12 and 23).

Change the lines
to be:
There should be one inside the struct definition just above the function, and one within the function. This way, the posWorld vector will be passed onto the fragment shader to be used by plane clipping.

The next step is the fragment program:

This uses the FRAGMENT_SETUP macro:

Which uses the IN_WORLDPOS macro in order to get the world position if necessary.

The world position is acquired only if UNITY_SPECCUBE_BOX_PROJECTION (similar to above) is defined, so change the line
to be:

The lines up to FRAGMENT_SETUP should now look like:

And finally, let’s add the plane clipping to the fragment shader. Place this line
just below

Your fragment shader code should now look like this:

This fixes the FORWARD pass!

Other passes

The next pass is the FORWARD_ADD.

Let’s make the vertex shader pass the world position to the fragment shader:

Add these lines before the closing brace of the VertexOutputForwardAdd struct:

We use TEXCOORD9 because 8 was used just above it.

And in the vertForwardAdd function, add the lines

Just after this line:
float4 posWorld = mul(_Object2World, v.vertex);

The fragment shader uses the FRAGMENT_SETUP_FWDADD macro, which is defined just below FRAGMENT_SETUP.

Above the FRAGMENT_SETUP_FWDADD macro, add these lines:
#define IN_WORLDPOS_FWDADD(i) i.posWorld
#define IN_WORLDPOS_FWDADD(i) half3(0,0,0)

And use the newly created IN_WORLDPOS_FWDADD macro instead of the half3(0,0,0) as the last parameter for FragmentSetup. Here’s how the relevant lines should look:

And finally, you can now call the PLANE_CLIP(s.posWorld) macro right after FRAGMENT_SETUP_FWDADD(s) inside fragForwardAdd.

Here’s the code for the VertexOutputForwardAdd struct, vertForwardAdd function and fragForwardAdd function altogether:

And here’s what the pass definition in StandardClippable.shader should look like:

Shadow pass

The shadow pass uses another file, UnityStandardShadow.cginc. Make a copy of this file and save it as standard_shadow_clipped.cginc. In the shadow pass definition, include the standard_shadow_clipped.cginc instead of UnityStandardShadow.cginc, and don’t forget the #pragma declarations!

Inside standard_shadow_clipped.cginc, include plane_clipping.cginc as usual.

In some conditions, the shadow vertex shader does not use an output struct. We want to ensure that we have the output struct so that we can pass the world position. around line 27, change the code so that it looks like this:

Inside the VertexOutputShadowCaster struct (around line 50), add the posWorld parameter:

And finally, just after it, here’s the modified vertShadowCaster and fragShadowCaster functions:

Guess what we added πŸ˜‰

Deferred pass

The deferred pass is very similar to the forward pass. Try to do it yourself πŸ™‚ If you have any trouble, write a comment below, and I will help you!

Lod 150 passes

You just need to use the correct include files and the #pragma declarations in these passes.

An example script

Here’s an example that shows how to use the EnableKeyword method correctly and define the clipping planes for the shader.


The Result!

You can find all the code on Github, in Unity3D-Plane-Clipping project I created.

And here’s the unitypackage file.

73 thoughts on “Per-Object Clipping Planes Shader in Unity3D 5

  1. Hi,

    I’m total noob with shaders.
    thank you very much for sharing this. However, is there a way to adapt this to a very cheap and simple legacy vertexlit shader ?

    1. I can’t think why it shouldn’t work πŸ™‚ when I have some time I can take a look.

      1. Hi,

        don’t waste time with it ! I’ve managed to adapt it, thought I’m not very sure of what I did…

  2. Great work. Thanks for sharing.
    Would it be much work to adapt it to specular setup?
    The clipping seems not complete with specular shader and I guess the standard.clipping.cginc file requires some more editions for the specular setup, could you give a hint?

    1. Hi again, just took a look at it today, looks like there are some problems with the latest version of Unity and it doesn’t work very well, will do more tests and try to get it fixed.

    2. Hi Tomasz, I have updated the GitHub project to show how I have added specular setup support πŸ™‚ Check the latest few commits!

      1. Thanks a lot for the update. I have checked this and it works very well. I have duplicated the Custom/StandardClippable shader and changed it to specular and it also works very well.
        I also works on WebGL and Android because I have tried.

  3. Great thanks.
    The structure of included files has changed in recent versions.
    Now in place of UnityStandardCore.cgi – you have UnityStandardCoreForward.cgi, where the workflow splits between UnityStandardCore or UnityStandardCoreForwardSimple depending on #UNITY_STANDARD_SIMPLE keyword.
    This implies a simple update to your example files which I already have worked out, but I didn’t manage to find out how to support specular setup.

    1. Simple answer: try to pass the world position and call clip. Long answer: I’ll be able to give it another try soon

  4. Is there a way to possibly achieve this but with the terrain. I know it doesn’t have a MeshRenderer which right now seems to be a problem. Can you point me in the direction of any possible modifications I could make?

    1. If you’re able to modify the shader or apply a new one all it needs is to pass the world position and call clip πŸ™‚

  5. Hi,
    First of all, thanks for sharing this project, I’ve learned a lot from it.
    I have a couple of questions: is it possible to “fill”/cap the cut surface of the meshes using only shaders? If so, where do I begin?

    1. Yes, I believe so. However I’m not sure if it can be done through “only shader”… I’d start by googling for things like cap shader, clip fill shader, etc

  6. I don’t have too much experience with shaders in Unity, but I’ve worked with a few such projects. I was attempting to add a pass that renders the backfaces as a simple unlit color. I can get the coloring to work, but I the clipping isn’t working for this pass. Rather than posting my code, perhaps you’d have suggestions for doing this.

    1. Hi, sorry for the late reply. I’m afraid I am not very sure on how to approach that.

  7. hi , ty for your great work πŸ™‚
    i just want to know , is there a way to i make this shader transparent ?

  8. Hey,

    Thank you so much for putting this valuable resource online.

    I’ve been trying to figure out – is there a way to make the plane an intractable/movable object, and to clip through multiple meshes at the same time during a game? I appreciate your help.

    1. Yes, you can set these meshes with the same material and apply the material property block to them every time the clip object moves πŸ™‚

    1. More basic, I’m trying to clip an image that has an alpha background, which uses the default Unlit/Transparent Cutout shader. I can use either the Cutout or StandardClippable shaders, but when I select the Cutout shader, obviously it doesn’t provide clipping.

  9. Hey, could you update this for. Unity5.5?
    I have tried to do it myself, I have even managed to get it working for baked lighting, but failed for realtime. I guess this should be a matter of putting some more clip() or discard commands, but I do not know where.

  10. Thank you so much! I only used a bit of it to make a laser cut shader effect, but your explanation was really simple (as far as shaders go) and effective!

  11. This works great on Windows, but when I try to build for Android I get this error:

    Shader error in ‘Custom/StandardClippable’: invalid subscript ‘boxMax’ at Assets/PlaneClipping/Shaders/standard_clipped.cginc(250) (on d3d11)

    Compiling Vertex program with DIRECTIONAL

    I’m using Unity 5.5.0p4
    Any ideas?


    1. Hi, unfortunately the shaders have not really been tested for Android, and additionally there are more problems that needs to be resolved with 5.5. I will be taking a look today on getting them working on 5.5 πŸ™‚

      1. Seems to me that this component doesn’t work with any object that has a material! You look to replace the material/texture with your own that you then clip. Is it true that this only works with objects without a material/texture applied? If so, what is the use case? Even your animated images show only base objects being clipped.

        1. Yes this post shows how to add clipping support to the standard shader.

          For any other material you would need to implement the clipping method in its pixel shader. If you link a material as an example I could show how you can make it “clippable” as well πŸ™‚

  12. Amazing work!
    Is there anyway to set transparency(alpha channel) for the material?
    I’ve been trying to find out how to do so, but couldn’t figure it out.

  13. You don’t have to calculate the distance… All you have to do is the dot product between the vector coming from the plane’s center to the fragment and the normal vector, if the result is negative, then it is behind the plane.

  14. Hello,
    Wonderful job!
    IT works fine for me in unity but I can’t make it work when I deploy it to hololens. Do you know if it works for hololens or if I have to make some changes?

  15. I honestly think i love you… its been 5 days im trying to figure this out and im totally new to unity, you saved my life <3

  16. Hi,

    i tried the script , it is working but the plane is not on the object, is it far away, how do i fix the issue

    1. You may need to have a script that moves the plane as well πŸ™‚ What is it that you are trying to do? For example do you want to always cut an object at the same shape?

  17. Hi, Great works..can it be adapted with transparent/diffuse shader?..if yes then can you please guide me a little bit..

    1. Hi Sanidhya, yes it should still be able to work with a transparent shader as well πŸ™‚ The important part is to capture the world coordinates of the pixel and compare it with the plane, then it should work with any type of shader. I am thinking about rewriting this shader later on to be much simpler but I am unsure when I may be able to have time to do that unfortunately so it may be a long time before that.

  18. This works amazingly. I love how you taught us the way you did it, so that we can apply it to other shaders as well. Thanks so much.

  19. Thank you very much for this demo. I am gonna try it.
    I would suggest that the heart emoji to be removed tho. lol.
    Thank you again! πŸ™‚

    1. The one in “hosted with ❀ by GitHub”? That’s a GitHub thing, unsure if it can be removed, I’ll check πŸ™‚

  20. Hello there, and sorry for my english if I make any mistakes.
    Thanks for the scripts. It looks awesome, but because of my lack of knowledge in shaders I can’t do much on my own to improve them. I have just a few questions :

    – Is it possible to “re-shape” the planes, or to use more than 3 clip planes in order to create a pseudo clip mesh that could hide what’s inside of it (for example, the planes could be replaced by a sphere that could hide the cube) ? I don’t know how complicated this is, but if it is feasible, what would be the best approach to realize this effect, or at least fake it ? Or maybe there’s already a shader that does this job for us ?

    – Second question : This is once again more a matter of a lack of knowledge than a real issue with your shader, but how can I use my own material without assigning your shader to it ? I’ve seen in your C# script that you created a new material with your shader and immediately added it to the cube’s MeshFilter, but I would like to add my own material instead of the default white one, and mine already has a shader attached to it. Should I create submeshes and assign my different materials to them, or can I combine the effects of the different shaders (if that’s ever possible) ?
    I know it may sound like a silly question, but I’m kinda a noob with shaders, and the most complex thing I’ve ever made with them is a basic Color Correction shader with only a hue, saturation, brightness, contrast and global Color.

    – The last question has nothing to do with the topic, but… On your first gifs, at the top of your blog, what shader did you use to create that pixelated effect in your scene? Look at your plane and your sky, they both have that strange pixelated gradient that I’d really like to replicate in my game. If you are the one who made them, do you mind sharing a download link, or at least a tutorial on how to replicate this effect? Thanks a lot ^^

  21. Thanks a lot for this shader, works great!

    But actually I’ve got a problem in the last version of Unity, the 2018 1.0f2… the shader won’t compile because of an error in the file standard_clipped.gcing, at line 175. The error is this one:
    “FragmentSetup: cannot convert from half4[3] to float4[3]”.

    The faulty call is the macro FRAGMENT_SETUP_CLIP(s), which is defined like this:

    #define FRAGMENT_SETUP_CLIP(x) FragmentCommonData x = \
    FragmentSetup(i.tex, i.eyeVec, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndParallax, IN_WORLDPOS_CLIP(i));

    One of these parameters has to be changed, but I’ve no idea of which one. Also, in the release notes of this version of Unity I can’t find what was changed… any ideas?

  22. Hello, google brought me here. Thanks for your amazing work! I’ve tried it and it does clipped the object. But the problem is it’s not following the object. I want to make it child game object and make it follow it’s game object position. Since it’s AR it would be no use if it can’t follow the objects. I hope the script is updated soon. Thanks!

    1. Thank you for your comment. To use other GameObjects as cutters you can get their position and rotation every frame and apply the values into the behavior

  23. It only works with a material? What happens if I have a model with n quantity of materials? Is it possible to make the cut for more than one material?

    1. I solved it, what I had to do was create an array of materials and replace all the references of sharedMaterial with the array of materials


      case 0:
      case 1:
      case 2:
      case 3:


      case 0:
      case 1:
      case 2:
      case 3:

  24. Hye bro! here again, I am trying to add 3 new planes to the shader code, could you clarify guiat on where to insert the code of the new planes? It really makes me a little difficult to understand how the shaders work; I’m going down in the conditions of the CLIP and I’m doing adding the following

    #if (CLIP_FOUR)
    float4 _planePos4;
    float4 _planeNorm4;

    #if CLIP_FOUR
    clip (float3 (
    distanceToPlane (,, posWorld),
    distanceToPlane (,, posWorld),
    distanceToPlane (,, posWorld)
    distanceToPlane (,, posWorld)
    #else // CLIP_FOUR

    in plane_clipping.cginc and I add the references in StadardClippable.shader without having a functional result, because the material turns pink.

    Could you guide me a bit with the operation? Thank you.

    1. There were a few problems there. float3 can only accept three numbers, and you were missing a comma before the last parameter.

      You may need to do a `float4` instead of `float3`, e.g.

      clip (float4 (
      distanceToPlane (,, posWorld),
      distanceToPlane (,, posWorld),
      distanceToPlane (,, posWorld), // also you were missing a comma here
      distanceToPlane (,, posWorld)

      Here’s specifications for clip parameters:

      Or if float4 doesn’t work, you can do multiple clips (3 + 1)
      clip (float3 (
      distanceToPlane (,, posWorld),
      distanceToPlane (,, posWorld),
      distanceToPlane (,, posWorld)
      clip(distanceToPlane (,, posWorld))

      If you want to do 5 planes you will definitely need to do 2 clip methods, e.g. 4 + 1

      1. change float 3 by float4, the material does not turn pink, but to prepare the shader and the script to add a fourth plane, at the time of compiling this does not make the cut with the new plane


        in the shader code add planePos 4, planeNorm4 and in # pragma multicompile add CLIP_FOUR



  25. change float 3 by float4, the material does not turn pink, but to prepare the shader and the script to add a fourth plane, at the time of compiling this does not make the cut with the new plane


    in the shader code add planePos 4, planeNorm4 and in # pragma multicompile add CLIP_FOUR


    1. Ok that looks about right, so good progress! You will also need to modify the c# script too so it will know what parameters it has to work with πŸ™‚

  26. Well, this is how to write the code to adapt plans, remove the lines that were responsible for drawing the plans and add the calls to _planePos4 and _planeNorm4. Still not working πŸ™

    I add a gif of the result, the planes of green, red and blue color make the cuts less the plane of white color that is the new one that adds

    ClippableObject script:

    gif with the result:

    1. Can you please use pastebin or github gist to share the script? It will be easier to comment on it like that.

      Looks like you have made a few mistakes, for example you have “planeNorm4” instead of “_planeNorm4”, “CLIP_ THREE” instead of “CLIP_THREE” and so on.

  27. ClippableObject.cs:



    Listo, si, me di cuenta de esos errores y los corregi, pero ahora cuando corregi “CLIP_ THREE” surgio el siguiente error en el debug:

    Shader error in ‘Custom/StandardClippable’: undeclared identifier ‘_planePos2’

    1. In ClippableObject.cs I see you modified the switch to enable the clip planes for all cases, I recommend to revert that to the previous and only add the case for 4.

      For plane_clipping.cginc, you will need to change this:
      //at least two planes.
      #if (CLIP_TWO || CLIP_THREE)


      //at least two planes.

      similar with `#if (CLIP_THREE)` just below that to be `#if (CLIP_THREE || CLIP_FOUR)`

      Unfortunately material keywords are very tricky to deal with…

  28. It works well on the PC platform.
    However, it does not work on the Android platform.
    Is there an easy way to solve this?

Leave a Reply to Vice Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.