webGl中实现clipplane

webGl中实现clipplane

参考:调用glClipPlane()函数所执行的裁剪是在视觉坐标中完成的,而不是在裁剪坐标中进行的https://blog.csdn.net/shengwenj/article/details/51019299

使用framgentshader在webGl中实现裁剪

https://stackoverflow.com/questions/22628186/glclipplane-is-there-an-equivalent-in-webgl

Unfortunately in the OpenGL-ES specification against which WebGL has been specified there are no clip planes and the vertex shader stage lacks the gl_ClipDistance output, by which plane clipping is implemented in modern OpenGL.

However you can use the fragment shader to implement per-fragment clipping. In the fragment shader test the position of the incoming fragment against your set of clip planes and if the fragment does not pass the test discard it.

Update

Let's have a look at how clip planes are defined in fixed function pipeline OpenGL:

void ClipPlane( enum p, double eqn[4] );

The value of the first argument, p, is a symbolic constant,CLIP PLANEi, where i is an integer between 0 and n − 1, indicating one of n client-defined clip planes. eqn is an array of four double-precision floating-point values. These are the coefficients of a plane equation in object coordinates: p1, p2, p3, and p4 (in that order). The inverse of the current model-view matrix is applied to these coefficients, at the time they are specified, yielding

p' = (p'1, p'2, p'3, p'4) = (p1, p2, p3, p4) inv(M)

(where M is the current model-view matrix; the resulting plane equation is unde- fined if M is singular and may be inaccurate if M is poorly-conditioned) to obtain the plane equation coefficients in eye coordinates. All points with eye coordinates transpose( (x_e, y_e,z_e, w_e) ) that satisfy

(p'1, p'2, p'3, p'4)   x_e  ≥ 0
                      y_e 
                      z_e 
                      w_e 

lie in the half-space defined by the plane; points that do not satisfy this condition do not lie in the half-space.

So what you do is, you add uniforms by which you pass the clip plane parameters p' and add another out/in pair of variables between the vertex and fragment shader to pass the vertex eye space position. Then in the fragment shader the first thing you do is performing the clip plane equation test and if it doesn't pass you discard the fragment.

In the vertex shader

in  vec3 vertex_position;
out vec4 eyespace_pos;
 
uniform mat4 modelview;
 
void main()
{
    /* ... */
    eyespace_pos = modelview * vec4(vertex_position, 1);
    /* ... */
}

In the fragment shader

in vec4 eyespace_pos;
 
uniform vec4 clipplane;
 
void main()
{
    if( dot( eyespace_pos, clipplane) < 0 ) {
        discard;
    }
    /* ... */
}
posted on 2018-12-28 11:16  3D入魔  阅读(1475)  评论(0编辑  收藏  举报