如何在OpenGL中使用圆圈剪辑

lin*_*llo 4 opengl geometry buffer clipping

我想知道是否可以模拟在OpenGL中查看锁孔的效果.

我绘制了我的3D场景,但除了中心圆外,我想让每一个都变黑.

我试过这个解决方案,但它与我想要的完全相反:

// here i draw my 3D scene 

// Begin 2D orthographic mode
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();

GLint viewport [4];
glGetIntegerv(GL_VIEWPORT, viewport);

gluOrtho2D(0, viewport[2], viewport[3], 0);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

// Here I draw a circle in the center of the screen
float radius=50;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y);
for( int n = 0; n <= 100; ++n )
{
    float const t = 2*M_PI*(float)n/(float)100;
    glVertex2f(x + sin(t)*r, y + cos(t)*r);
}
glEnd();

// end orthographic 2D mode
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
Run Code Online (Sandbox Code Playgroud)

我得到的是在中心绘制的圆圈,但我想获得它的补充......

Die*_*Epp 6

与OpenGL中的其他所有内容一样,有几种方法可以做到这一点.这是我头顶的两个.

使用圆形纹理:(推荐)

  1. 画出场景.
  2. 切换到正交投影,并使用在中心具有白色圆圈的纹理在整个屏幕上绘制四边形.使用适当的混合功能:

    glEnable(GL_BLEND);
    glBlendFunc(GL_ZERO, GL_SRC_COLOR);
    /* Draw a full-screen quad with a white circle at the center */
    
    Run Code Online (Sandbox Code Playgroud)

或者,您可以使用像素着色器生成圆形.

使用模板测试:(不推荐,但如果你没有纹理或着色器可能会更容易)

  1. 清除模板缓冲区,并将圆圈绘制到其中.

    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 1, 1);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    /* draw circle */
    
    Run Code Online (Sandbox Code Playgroud)
  2. 为场景的其余部分启用模板测试.

    glEnable(GL_STENCIL_TEST)
    glStencilFunc(GL_EQUAL, 1, 1);
    glStencileOp(GL_KEEP, GL_KEEP, GL_KEEP);
    /* Draw the scene */
    
    Run Code Online (Sandbox Code Playgroud)

脚注:我建议在代码中的任何位置避免使用立即模式,而是使用数组.这将提高代码的兼容性,可维护性,可读性和性能 - 在所有领域都取得胜利.