How to render caps like webgl_clipping_stencil?

Hi. I’m new to THREE and discourse.threejs. I’m trying to clip and cap threejs objects that have been rendered so I can move the helperPlane back and forth through the object to see inside it. There might be rendered objects inside it. What I’m looking to do is similar to this description of advanced clipping techniques in OpenGL here: More OpenGL Game Programming - Bonus - Advanced Clip Planes. So, if this can be done in OpenGL, there must be some way to do it in WebGL too?

I adapted the clipping_stencil example ( three.js webgl - clipping stencil ), and everything looks right as long as I don’t move the helperPlanes. When the helperPlanes are moved, some of the cap faces of the larger mesh disappear, there’s some rendering artifacts and the caps might not be rendered in the desired position.

I looked at some of the posts in the forum. One about renderingOrder was very helpful for getting the inner mesh to be visible: Capping two clipped geometries using two planes which are negated to each other. My problem seemed similar to another post, Clipping geometry made from merged faces. Stenciled cap face not aligning properly, but the geometries aren’t the same, and I don’t think the solution applies to my code.

Everything is on a JSFiddle:

Any help would be greatly appreciated! Thanks in advance!


UPDATE - 2022-04-12
I had some success with what I set out to do. This is an updated JSFiddle. I was able to implement capping an object inside another object with clipping and stencils. I included drag and orbit controls and gui to select the plane (x,y,z) to section along. I noticed some strange behaviour in rendering the caps depending on the object position and the rotation of the camera.

  1. I needed to move the object further away from the camera to see the caps rendered when sectioning in the x and y planes, but not z
  2. The caps seemed to disappear like a sliding door if I rotated the camera from positive x to negative x
    So, I think the caps are rendering in the same place as the clipping plane and depth testing can’t discriminate between the two at some camera points. UPDATE I found that this code is needed in the animate function for everything to go smoothly! (the example on does this!)
						cap.position.x - clipPlane.normal.x,
						cap.position.y - clipPlane.normal.y,
						cap.position.z - clipPlane.normal.z,

I also tried implementing the drag controls for the helperPlane like @Mugen87 's response in this post, but the sensitivity was really bad.