Search code examples
camerathree.jswebglshadervertex

WebGL and/or Three.js: Remove non rendered faces


With a given mesh at a given position, is there an fast and easy way (with vertexShader, fragmentShader or something else) to identify/remove from the mesh all the faces/vertices that are not rendered on the camera screen (hidden behind other faces, outside the view fustrum, etc.)?


Solution

  • If you mean remove in terms of not rendering them this is accomplished by having backface culling enabled(as it is by default).

    Detecting Backfaces on the CPU

    If you want to remove them from the geometry itself you would need to iterate over the faces and calculate the dot product between the face normal and your lookat/camera direction vector, then compose new geometry buffers containing only the faces where the dot product was positive.

    Detecting Occluded Faces on the CPU

    Detecting hidden/occluded faces could be done by iterating over the faces and building three planes using the triangle edges extruded along the lookat vector by the far clipping distance, and use the flipped normal of the face itself the 'front plane'. By that you would get an open ended prism type of shape. Then use that volume(its technically not a volume as its not closed) to cull the vertices of the remaining faces, when all vertices of a face lie whithin all planes(assuming your plane normals point inside) the face in question is occluded and can be removed.

    Even when using acceleration structures like a Bounding Volume Hierarchy this will not be realtime compatible.

    Detecting Occluded Faces on the GPU/CPU

    Another easier and probably faster approach would be to assign a unique color representing an ID to each face, render the geometry to a framebuffer, iterating over that pixel data, bitshifting the colors back into their respective ID and build a list of visible faces that way.

    Further Information

    While its usually not done on a geometry level read the wikipedia article on occlusion culling for further information.