Skip to main content

Portal using Stencil

✍ Last Updated : October 26, 2022

🚪 Prequisite Knowledge (Optional)

Describe Initial Knowledge that reader need to know before reading this article

❓ Key Question / Problem / Issue

Describe what question / Problem / Issue this knowledge should answer

✅ Expected Output/Definition of Done

Define what information you really need and the definition of done

🎁 Resulting Solution

How stencil works

Stencil shader works by comparing the stencil reference with stencil buffer, if the comparison returns true, then the pass operation will be executed.

The default value in the stencil buffer is 0, to write value into stencil buffer, we can add this code into any shader

Stencil
{
	Ref [refID]  //reference ID to write into stencil buffer, int(0-255)
	Comp Always  //Ignore the comparison, so it Always execute Pass
	Pass Replace //Replace the stencil buffer value with Ref
}

When material with the shader above used to draw a cube, it will write into the stencil buffer

Red cube is using stencil shader material

Red cube is using stencil shader material

Stencil buffer after red cube is drawn.  White is refID.

Stencil buffer after red cube is drawn. White is refID.

After drawing into the stencil buffer, to utilize the buffer, we need to add another shader that compare the shader buffer with the refID.

Stencil
{
	Ref [refID]  //reference ID to write into stencil buffer, int(0-255)
	Comp Equal   //Check if stencil buffer equal to refID
}

Now any object that’s using the shader will only get drawn if the stencil buffer value is equal to refID (in short, inside the stencil)

Green sphere using standard shader

Green sphere using standard shader

Green sphere using stencil shader

Green sphere using stencil shader

ShaderLab command: Stencil

Portal setup