How to clip only intersection (not union) of clipp

2019-07-12 14:17发布

问题:

In OpenGL/JOGL, when using more than one clipping plane, the union of all clipping planes appears to be applied. What I want is instead the intersection of all clipping planes to be applied. Is this possible? See the below simplified 2-D example.

Edit: An example of clipping by vertex shader (see comments below).

回答1:

Multi-pass:

#include <GL/glut.h>

void scene()
{
    glColor3ub( 255, 0, 0 );
    glBegin( GL_QUADS );
    glVertex2i( -1, -1 );
    glVertex2i(  1, -1 );
    glVertex2i(  1,  1 );
    glVertex2i( -1,  1 );
    glEnd();
}

void display()
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    double ar = w / h;
    glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glEnable( GL_CLIP_PLANE0 );

    // -y plane
    GLdouble plane0[] = { -1, 0, 0, 0 };
    glClipPlane( GL_CLIP_PLANE0, plane0 );

    scene();

    // -x plane
    GLdouble plane1[] = { 0, -1, 0, 0 };
    glClipPlane( GL_CLIP_PLANE0, plane1 );

    scene();

    glutSwapBuffers();
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "Clipping" );
    glutDisplayFunc( display );
    glutMainLoop();
    return 0;
}


回答2:

Using glClipPlane, no. Vertices are clipped if they are outside the positive halfspace of at least one plane. Once that happens, it doesn't matter what any other plane may be.

However, you can get this effect (or almost any other effect) by writing appropriate values to gl_ClipDistance in a vertex shader.

Any portion where the interpolated value that you write out is less than 0.0 ("negative halfspace") will be clipped, and you can write any value you like, e.g. the squared distance to a point, or the sum of distances to two planes, or anything else you calculate.



标签: opengl 3d jogl