简体   繁体   中英

How to cut an object using WebGL shaders?

I would like to cut an object (a box) in WebGL ( fragment shaders / vertex shaders ) without using Boolean operations (union, difference, etc..).

I want to use shaders to hide some part of the object (so it is therefore not really a "real cuts" since it simply hides the object).

EDIT

First, make sure that the vertex shader passes through to the fragment shader the position in world space (or rather, whichever coordinate space you wish the clipping to be fixed relative to). Example (written from memory, not tested):

varying vec3 positionForClip;
...
void main(void) {
    ...
    vec4 worldPos = modelMatrix * vertexPosition;
    positionForClip = worldPos.xyz / worldPos.w;  // don't need homogeneous coordinates, so do the divide early
    gl_Position = viewMatrix * worldPos;
}

And in your fragment shader, you can then discard based on an arbitrary plane, or any other kind of test you want:

varying vec3 positionForClip;
uniform vec3 planeNormal;
uniform float planeDistance;
...
void main(void) {
    if (dot(positionForClip, planeNormal) > planeDistance) {
        // or if (positionForClip.x > 10.0), or whatever
        discard;
    }
    ...
    gl_FragColor = ...;
}

Note that using discard may cause a performance reduction as the GPU cannot optimize based on knowing that all fragments will be written.

Disclaimer: I haven't researched this myself, and only just wrote down a possible way to do it based on the 'obvious solution'. There may be better ways I haven't heard of.


Regarding your question about multiple objects: There are many different ways to handle this — it's all custom code in the end. But you certainly can use a different shader for different objects in your scene, as long as they're in different vertex arrays.

    gl.useProgram(programWhichCuts);
    gl.drawArrays();
    gl.useProgram(programWhichDoesNotCut);
    gl.drawArrays();

If you're new to using multiple programs, it's pretty much just like using one program except that you do all the setup (compile, attach, link) once. The main thing to watch out for is each program has its own uniforms , so you have to initialize your uniforms for each program separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM