There is a first solution. When I draw the triangles over the rectangle I use the counter clock wise winding to view it on recto and clock wise winding on verso.
#include <iostream>
#include <GL/glut.h>
#include <GL/glu.h>
static float angle = 0.0;
static void draw(void);
static void drawQuads(void);
static void init(void);
static void redraw(void);
static void reshape(int w,int h);
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL|GLUT_DOUBLE);
glutInitWindowSize(640,480);
glutCreateWindow("Ortho");
glutReshapeFunc(reshape);
glutDisplayFunc(draw);
glutIdleFunc(redraw);
init();
glutMainLoop();
return(EXIT_SUCCESS);
}
void draw(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
glLoadIdentity();
angle+=1.0f;
glRotatef(angle,0.0,1.0,0.0);
drawQuads();
glutSwapBuffers();
}
void drawQuads(void)
{
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glColor4f(1.0,1.0,1.0,1.0);
glBegin(GL_QUADS);
glVertex4f(-100.0,-100.0,0.0,1.0);
glVertex4f(100.0,-100.0,0.0,1.0);
glVertex4f(100.0,100.0,0.0,1.0);
glVertex4f(-100.0,100.0,0.0,1.0);
glEnd();
glStencilFunc(GL_EQUAL, 0x1, 0x1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDepthMask(GL_FALSE);
glEnable(GL_CULL_FACE);
glDepthFunc(GL_ALWAYS);
glColor4f(1.0,0.0,0.0,1.0);
glBegin(GL_TRIANGLE_STRIP);
glVertex4f(-50.0,-50.0,0.0,1.0);
glVertex4f(50.0,-50.0,0.0,1.0);
glVertex4f(0.0,50.0,0.0,1.0);
glEnd();
glColor4f(0.0,1.0,0.0,1.0);
glBegin(GL_TRIANGLE_STRIP);
glVertex4f(-50.0,-50.0,0.0,1.0);
glVertex4f(0.0,50.0,0.0,1.0);
glVertex4f(50.0,-50.0,0.0,1.0);
glEnd();
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE);
glDisable(GL_STENCIL_TEST);
}
void init(void)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
void reshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// gluPerspective(65.0,(GLfloat)width/(GLfloat)height,1.0,100.0);
glOrtho(-200,200,-200,200,-1000.0,1000.0);
// glOrtho(0.0,(GLdouble)width,0,(GLdouble)height,-1.0,100.0);
glMatrixMode(GL_MODELVIEW);
}
void redraw(void)
{
glutPostRedisplay();
}
So the next thing to do is try to reset the stencil buffer where I draw the rectangle without the need of clearing the entire stencil buffer and make it work in a complex scene.