对一个四边形定义顶点位置 ,顶点颜色 顶点法线
定义方向光源,光源颜色,
渲染一个四边形,光源只对其两个顶点照射:
点光源:point light具有位置和颜色的属性,它在空间中占据一个点,并向四面八方散射,光线照射到某个物体后,反射光的强度与物体表面的法线和入射光线的夹角有关,这一点和方向光泪水,不同的是,因为点光源具有位置属性,所以光线达到每个顶点的方向与距离不同,并且它还会光源随着物体的距离增大而衰减,
1
//计算点光源,只与顶点位置,顶点法线以及光源位置有关
2
void CalculatePointLight (Vertex_PCN *pVertices, int num_vertices)
{
3
float fSpotLightCutoffCos=FastMath::Cos (FastMath::DegreeToRadian (g_fSpotLightCutoff));
4
for(int i=0;i<num_vertices;i++)
{
5
Vector4 vPosition=pVertices[i].m_position *g_world_matrix;
6
Vector4 vNormal=g_world_matrix.RotateVector (pVertices[i].m_normal );
7
Vector4 vVertex_to_Light=g_vLightPosition-vPosition;
8
float light_distance=vVertex_to_Light.NormalizeAndGetLength ();
9
Vector4 vDistance(1.0,light_distance,light_distance*light_distance);
10
Vector4 vAttenuation=Vector3Dot(vDistance,g_vLightAttenuation);
11
Vector4 vIntensity=Vector3Dot(vNormal,vVertex_to_Light);
12
pVertices[i].m_color +=vIntensity*g_vLightColor/vAttenuation;
13
}
14
}
取四边形的一个顶点位置 法线 颜色参与点光源的照射:
使用OpenGL自己定义的函数可以实现方向光,点光源以及聚光灯
//方向光参数light0

float vDirection[4]=
{0.0f, 1.0f, 0.0f, 0.0f};//w=0,表示平行光

float vDirAmbientColor[4]=
{0.0f, 0.0f, 0.0f, 1.0f};

float vDirDiffuseColor[4]=
{1.0f, 0.0f, 0.0f, 1.0f};

//点光源参数Light1

float vPointPosition[4]=
{0.0f,3.0f, -5.0f, 1.0f};//w=1表示点光源

float vPoiAmbientColor[4]=
{0.0f, 0.0f, 0.0f, 1.0f};

float vPoiDiffuseColor[4]=
{0.0f, 1.0f, 0.0f, 1.0f};

float vPoiAttenuation[4]=
{2.0f, 1.0f, 0.5f};
//聚光灯参数Light2

float vSpotPoint[4]=
{0.0f, 10.0f, 0.0f, 1.0f};//w=1

float vSpotDirection[4]=
{0.0f, 0.0f,-1.0f, 0.0f};

float vSpotAmbientColor[4]=
{0.0f, 0.0f, 0.0f, 1.0f};

float vSpotDiffuseColor[4]=
{0.0f, 0.0f, 1.0f, 1.0f};

float vSpotAttenuationg[4]=
{1.0f, 1.0f, 0.0f};
float mfSpotLightCutoff=20;
float mfSpotLightExponent=5;


方向光:

void Light::SetDirectionLight()
{
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, vDirection);
}
点光源:

void Light::SetPointLight ()
{
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// `光源位置`
glLightfv(GL_LIGHT0, GL_POSITION, vPointPosition);
// `随距离的衰减值 `
// 1/(CONSTANT + LINEAR*d + QUADRATIC*d^2) `公式中的CONSTANT,LINEAR,QUADRATIC值`
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, vPoiAttenuation[0]);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, vPoiAttenuation[1]);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION,vPoiAttenuation[2]);

}
聚光灯:

void Light::SetSpotLight ()
{
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// `光源位置`
glLightfv(GL_LIGHT0, GL_POSITION, vSpotPoint);
// `随距离的衰减值`
// 1/(CONSTANT + LINEAR*d + QUADRATIC*d^2) `公式中的CONSTANT, LINEAR, QUADRATIC值`
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, vSpotAttenuationg[0]);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, vSpotAttenuationg[1]);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, vSpotAttenuationg[2]);
// `光柱的方向`
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, vSpotDirection);
// `光柱圆锥的一半角度`
glLightf(GL_LIGHT2, GL_SPOT_CUTOFF, mfSpotLightCutoff);
// `光柱圆锥的角度衰减`
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, mfSpotLightExponent);
);

}