PDA

View Full Version : how to implement backface culling



bloggingzoom
05-24-2005, 10:07 AM
Please tell me some source code without windows programing on how to implement backface culling.
Thanks

PickleWorld
05-24-2005, 10:20 AM
You mean the basic two calls?

glCullFace( GL_BACK );
glEnable(GL_CULL_FACE);

Ehsan Kamrani
05-24-2005, 10:51 AM
I wrote an example for you. important functions are:
glEnable( GL_CULL_FACE ), glFrontFace(), glCullFace() and glPolygonMode().press the A and S buttons to see the result.

//Culling
//Ehsan Kamrani

#include <GL/glut.h>

int wh = 0;
GLenum mode = GL_CCW;
void init()
{
glClearColor( 0.0, 0.0, 0.0, 0.0 );
glColor3f( 1.0f, 1.0f, 0.0f );

glEnable( GL_CULL_FACE );
glCullFace( GL_BACK );
glPolygonMode( GL_FRONT, GL_FILL );

}

void reshape( int width, int height )
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( -1.0, 1.0, -1.0, 1.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glViewport( 0, 0, width, height );

wh = height;
}

void display()
{
glClear( GL_COLOR_BUFFER_BIT );
glFrontFace( mode );
glBegin( GL_POLYGON );
glVertex3f( -0.5, -0.5, 0.0 );
glVertex3f( 0.5, -0.5, 0.0 );
glVertex3f( 0.5, 0.5, 0.0 );
glVertex3f( -0.5, 0.5, 0.0 );
glEnd();
glFlush();
glutSwapBuffers();
}

void idle()
{
glutPostRedisplay();
}
void keyboard( unsigned char key, int x, int y )
{
switch( key )
{
case 'A': case 'a':
mode = GL_CW ;
break;
case 'S': case 's':
mode = GL_CCW;
break;
}

}
int main( int argc, char* argv[] )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA );
glutInitWindowSize( 500, 500 );
glutCreateWindow( "Culling" );
glutDisplayFunc( display );
glutReshapeFunc( reshape );
glutKeyboardFunc( keyboard );
glutIdleFunc( idle );
init();
glutMainLoop();
return 0;
}

-Ehsan-

powerpad
05-24-2005, 11:18 AM
1. get the nnormal of your triangle face/ plane -> n

2. get the cameras viewing direction vector -> v

3. compute the dot product between n and v

doing d = n.x*v.x + n.y*v.y+n.z*v.z + n.w*v.d

4. decide whether the face is front facing with
regard to the viewing direction
by examing d, notice that the dot product tells you the angle that is formed by n and v

if(d > 0)
n and v go to the same direction
thus the face is a backfacing face

if(d < 0)
n and v go to the opposite direction
thus the face is a frontfacing face

although the above said depends on how you calculate your normals ...
we assume a counterclockwise winding for all verts