Shader: Two way through the Stencil Test

A long time ago, I used Stencil Test in a 3D sliding list. This review, I try to use it to make a double-sided through the door.

effect

principle

Write a value into Stencil Buffer. When rendering other tiles at the same location subsequently, if template testing is enabled, the preset value will be compared with the value in Stencil Buffer (i.e. Test). Based on the comparison results, operations such as removing tiles and changing buffer values will be performed.

Therefore, a Shader is used to write Stencil Buffer, the object behind the door is rendered later, and the template test is used to remove the pieces that are not in the range, so the effect can be completed.

The effect of this article is double-sided rendering, and the front and back side rendering is written into different Stencils. A C # script adjusts relevant parameters in real time according to the camera position, which is more troublesome than single side wall decals.

code

There are some differences between the Build in pipeline and the URP, which will be mentioned later.

“MASK” Shader

Add Stencil writing:

 Stencil { Ref [_Stencil]//Note that Stencil is the Int value defined in Properties. The value is (0-255) Comp Always Pass Replace Fail Keep ZFail Keep //CompBack Always //PassBack Replace //FailBack Keep //ZFailBack Keep //CompFront Always //PassFront Replace //FailFront Keep //ZFailFront Keep }

Turn off ZWrite so that the following objects can pass ZTest (StencilZFail is the operation of the template, which cannot save the chip):

 ZWrite Off

Change the Alpha Blend mode, and generally use Zero One.

As for whether to add a PS or VS color, it is generally meaningless depending on your needs.

object

Build in pipeline

Add template test code similar to the above for the object shader, change the Test method (Comp), and modify the Pass and Fail behaviors as appropriate.

The object rendering order is higher than the "Mask" Shader, that is, render after Stencil value is written.

URP

URP can use RenderObjects to control the rendering order and template testing, for example:

The above configuration is to make the opaque queue objects of StencilEnv layer render after other opaque objects are rendered, and apply the specified template test.

This is very convenient without changing the object shader.

Of course, in order to prevent StencilEnv from rendering in advance, you also need to cancel the StencilEnv layer in the top-level Filter:

Translucent queue objects are similar to them, but they are omitted.

other

If it is a Shader, you may encounter and Depth Priming Mode The next article will explain the problem in detail and provide solutions.

Zimiao haunting blog (azimiao. com) All rights reserved. Please note the link when reprinting: https://www.azimiao.com/10028.html
Welcome to the Zimiao haunting blog exchange group: three hundred and thirteen million seven hundred and thirty-two thousand

Comment

*

*