What could cause the stencil func to flip?

I’m using clipping and stencilling to slice a model. This is the model for context:

This is the model after slicing… So far so good.

My issue is that the stencil func seems to flip based on the camera position. For example, this is when the camera is a bit closer to the model:

And if I move the camera slightly, it flips!:

These are the values on the shader:

// clone the object material to use on the plane
const planeMat = objectMaterial.clone();
   // darken the color
   const color = (planeMat as THREE.MeshStandardMaterial).color;
   let hsl = { h: 0, s: 0, l: 0 };
   color.getHSL(hsl);
   hsl.l = a3dMath.Bias(hsl.l, 0.2);
   hsl.s = a3dMath.Bias(hsl.s, 0.3);
   color.setHSL(hsl.h, hsl.s, hsl.l);

   // add stencilling to this new plane material
   (planeMat as THREE.MeshPhysicalMaterial).setValues({
     clipIntersection: true,
     clippingPlanes: [],
     stencilWrite: true,
     stencilRef: 0,
     stencilFunc: THREE.NotEqualStencilFunc,
     stencilFail: THREE.ReplaceStencilOp,
     stencilZFail: THREE.ReplaceStencilOp,
     stencilZPass: THREE.ReplaceStencilOp,
     stencilFuncMask: 0xff,
     side: THREE.DoubleSide,
   });

My stencil function is THREE.NotEqualStencilFunc. When the issue happens, it looks how it would look if the stencil func was THREE.EqualStencilFunc.

The flipping isn’t totally an on/off operation. If I move the camera very slowly I can see an edge swipe across the plane as it flips, but I can’t manage to capture that in a screen grab.

I have tried making the camera near clip plane very very small and it has no effect, so I don’t think it is related to the near clip plane.

I’m not interacting with the shader at all when the camera is moving. I have no idea why there is an apparent relationship between the camera position and the stencil func on that plane!

I managed to catch the edge moving across the plane mentioned earlier:


(The diagonal line going from the middle left to the top right of the frame)