• Advertisement
Sign in to follow this  

Confuse in OpenGL's Lighting when rendering a triangle mesh

This topic is 1480 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, Everyone, 


I'am a beginner in OpenGL. Recently I encounter a confuse problem about OpenGL's lighting.

I write a small program in C++ that rendering a triangle mesh, the program is just simple, get 

every triangle's vertex position, compute its normal vector, then render it. Following is my code:

void OpenGLTests::Rendering()
	GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
	GLfloat mat_shininess[] = { 50.0 };
	GLfloat light_position[] = { 0.0, 0.0, -1.0, 0.0 };

	glClearColor (0.0, 0.0, 0.0, 0.0);
	glShadeModel (GL_SMOOTH);

	glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
	glLightfv(GL_LIGHT0, GL_POSITION, light_position);

	//Draw the mesh
	glVertexPointer(3, GL_DOUBLE, 0, m_pPoints);
 	for ( unsigned int i = 0; i < m_nTriangleCount; ++i)
		unsigned int vs[3] = {m_pTriangleArray[3*i], m_pTriangleArray[3*i+1], m_pTriangleArray[3*i+2]};

		//Get this trangle's points 
		CPoint pt1(m_pPoints[vs[0]].xyz[0],m_pPoints[vs[0]].xyz[1],m_pPoints[vs[0]].xyz[2]) ;
		CPoint pt2(m_pPoints[vs[1]].xyz[0],m_pPoints[vs[1]].xyz[1],m_pPoints[vs[1]].xyz[2]);
		CPoint pt3(m_pPoints[vs[2]].xyz[0],m_pPoints[vs[2]].xyz[1],m_pPoints[vs[2]].xyz[2]);
		//if ( pt1.x <= 0 || pt2.x <= 0 || pt3.x <= 0 )
		//	continue;

		//Compute this triangle's normal
		CVector v1(pt2.x-pt1.x, pt2.y-pt1.y, pt2.z-pt1.z);
		CVector v2(pt3.x-pt1.x, pt3.y-pt1.y, pt3.z-pt1.z);
		CVector vn = VectorCrossProduct1(v2, v1);

		glNormal3d(vn.x, vn.y, vn.z);
		//double dx = abs(pt1.x)+abs(pt2.x)+abs(pt3.x)/3;
		//double dy = abs(pt1.y)+abs(pt2.y)+abs(pt3.y)/3;
		//double dz = abs(pt1.z)+abs(pt2.z)+abs(pt3.z)/3;
		//double d = dx+dy+dz;
		//glColor4d(dx/d,dy/d,dz/d, 0);

When I render the whole mesh, It looks like this picture:


It seems that have many black areas.


When I render the front part(triangles whose Z coordinate is greater than 0, just uncomment the red code ) of the mesh only, 


It seems that everything is OK, But once I rotate the mesh, those black areas will emerge

again, see this picture:



My problem is why those black areas emerge? I'm sure the normal vector of every triangle 

is computed correctly. Anyone can help me? thankssmile.png .

Share this post

Link to post
Share on other sites

Seem to me like the near and far plane are not setup correctly, i might be wrong tho.

Thanks Vortez, I check my near plane setting, it was set to 0, but the mesh's some vertices Z coordinate are greater than 0, 

Now I set near plane to 10, it works correctly, thanks your help very muchsmile.png

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement