OpenGL光照设置,实现渲染效果

OpenGL实现具有凹凸感的渲染效果图OpenGL光照设置,实现渲染效果_第1张图片


一、设置光照

1、设置光照成分

环境光:环境光来自于四面八方。所有场景中的对象都处于环境光的照射中。
漫射光:由特定的光源产生,并在您的场景中的对象表面上产生反射。处于漫射光直接照射下的任何对象表面都变得很亮,而几乎未被照射到的区域就显得要暗一些。这样在我们所创建的木板箱的棱边上就会产生的很不错的阴影效果。
镜面光

2、指定光照位置

3、绑定光源

4、启动光源

BOOL CtestviewView::InitializeOpenGL(CDC* pDC)
{
	m_pDC = pDC;
	SetupPixelFormat();
	//生成绘制描述表
	m_hRC = ::wglCreateContext(m_pDC->GetSafeHdc());
	//置当前绘制描述表
	::wglMakeCurrent(m_pDC->GetSafeHdc(), m_hRC);


	设置0号光源
	GLfloat light_diffuse[]={1.0f,1.0f,1.0f,0.0f};
	GLfloat light_position0[]={0.0f,0.0f,-9.0f,0.0f};
	glLightfv(GL_LIGHT0,GL_POSITION,light_position0);
	glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);

	//设置1号光源
	GLfloat light_position1[]={0.0f,0.0f,9.0f,0.0f};
	glLightfv(GL_LIGHT1,GL_POSITION,light_position1);
	glLightfv(GL_LIGHT1,GL_DIFFUSE,light_diffuse);


	//定义材质
	float mat_diffuse[]={0.8f,0.8f,0.8f,1.0f};
	glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,mat_diffuse);
	
	//启动光源
	glEnable(GL_LIGHT0);
	glEnable(GL_LIGHT1);
	glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);//启动双面光照(important!)
	glEnable(GL_LIGHTING);

	//glClearDepth(1.0f);
	//glEnable(GL_DEPTH_TEST);
	//glMatrixMode(GL_MODELVIEW);
	//glLoadIdentity();
	//glEnable(GL_LIGHTING);

	return TRUE;


二、材质设置

三、面元法线设置

只有设置好了三角面元的法线,才有凹凸纹理的感觉

//画渲染图
void CtestviewView::ShowLight(void)
{
	glPushMatrix();
	//材质设置
	float mat_diffuse[]={0.8f,0.8f,0.8f,1.0f};
	glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,mat_diffuse);
	glClearColor(0.0,0.0,0.0,0.0);
	glShadeModel(GL_SMOOTH);


	glPolygonMode(GL_FRONT,GL_FILL);
	glColor3f(1.0f,1.0f,1.0f);
	for (int i=0;iclass3d ab;
		ab.x= vector3d[vectortri[i].index2].x-vector3d[vectortri[i].index1].x;
		ab.y= vector3d[vectortri[i].index2].y-vector3d[vectortri[i].index1].y;
		ab.z= vector3d[vectortri[i].index2].z-vector3d[vectortri[i].index1].z;
		class3d bc;
		bc.x = vector3d[vectortri[i].index3].x-vector3d[vectortri[i].index1].x;
		bc.y = vector3d[vectortri[i].index3].y-vector3d[vectortri[i].index1].y;
		bc.z = vector3d[vectortri[i].index3].z-vector3d[vectortri[i].index1].z;
        //然后计算法线,即另一个向量。求该对象的法向量(norm)。下面的代码用于计算向量ab和bc的外积:
		class3d norm;
		norm.x = (ab.y * bc.z) - (ab.z * bc.y);
		norm.y = (ab.z * bc.x) - (ab.x * bc.z);
		norm.z = (ab.x * bc.y) - (ab.y * bc.x);

		//归一化
		double dNormalLength=sqrt(norm.x*norm.x+norm.y*norm.y+norm.z*norm.z);
		if(dNormalLength!=0.0)
		{
			norm.x=norm.x/dNormalLength;
			norm.y=norm.y/dNormalLength;
			norm.z=norm.z/dNormalLength;
		}
		else
		{
			norm.x=0.0;
			norm.y=0.0;
			norm.z=1.0;
		}
		glBegin(GL_POLYGON);
		glNormal3d(norm.x,norm.y,norm.z);
		glVertex3f(vector3d[vectortri[i].index1].x,vector3d[vectortri[i].index1].y,vector3d[vectortri[i].index1].z);
		glVertex3f(vector3d[vectortri[i].index2].x,vector3d[vectortri[i].index2].y,vector3d[vectortri[i].index2].z);
		glVertex3f(vector3d[vectortri[i].index3].x,vector3d[vectortri[i].index3].y,vector3d[vectortri[i].index3].z);
		glEnd();
	}
	glPopMatrix();

}











你可能感兴趣的:(OpenGL)