Mesh intersection by using stencil buffer

The problem is that the sphere intersect of the other side of the cube is still drawn in the stencil buffer because the depth test is “greater or equal”, screwing up the stencil buffer.

One way to do it is to create 6 planes and handle the 6 planes with different values of the stencil buffer, so that handling a (plane + sphere intersect + sphere) of one side does not temper with any other sides.

In the PG below I have set the stencil values to 3/5/7/9/11/13 for the 6 planes because I have set the “stencil operation pass” function to “DECR”, meaning a value of 2/4/6/8/10/12 will be written to the stencil buffer where the “sphere intersect” is drawn. The important thing is that those values are different from the plane values, so it’s one way to do it. I had first tried to set the stencil mask to “1” when writing the “sphere intersect” objects, in the hope to get 1 into the stencil buffer (because 3 & 1=1, 5 & 1=1, etc) but it did not work for some reasons…

https://playground.babylonjs.com/#95RAN4#4

Last thing, I used hemispheres instead of full spheres as you don’t really need full spheres here (it saves some polys).

…and welcome aboard!

2 Likes