OpenGL中的光照包括环境光、散色光和镜面光,在系统中加入光照以后,设置一些材料属性以后,多边形才能反射光线,设置材料属性有两种方法
程序运行后:






变量的设置:
1 float lightPos[]={0.0,0.0,75.0,1.0};//创建风光位置
2 float specular[]={1.0f,1.0f,1.0f,1.0f};//为光照的镜面光成分指定了一种非常亮的白色光源
3 float ambientlight[]={0.5,0.5,0.5,1.0};
4 float spotDir[]={0.0,0.0,-1.0};
光照系统初始化:

glEnable(GL_LIGHTING);//启用光照
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,ambientlight);//设置和启用光照0,提供一种微弱的环境光,
glLightfv(GL_LIGHT0,GL_AMBIENT,ambientlight);
glLightfv(GL_LIGHT0,GL_SPECULAR,specular);//为light0添加了这种镜面光成分
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,60.0);//特定的光点效果,切角为60-把一个位置性光源实际变成一个聚光灯
glEnable(GL_LIGHT0);//特别启用这用光照
glEnable(GL_COLOR_MATERIAL);//启用颜色追踪
glColorMaterial(GL_FRONT,GL_AMBIENT_AND_DIFFUSE);//设置材料属性,对应与glColor值
//此后所有的材料都具有完全的强光泽镜面反射属性
glMaterialfv(GL_FRONT,GL_SPECULAR,specular);
glMateriali(GL_FRONT,GL_SHININESS,128);
场景绘制:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();//首先放置光源,保存坐标转换
glRotatef(xrot,0.1,1.0,0.0);
glRotatef(yrot,1.0,0.0,0.0);
glRotatef(yrot,0.0,0.0,1.0);
//根据旋转后的坐标系统指定新的位置和方向
glLightfv(GL_LIGHT0,GL_POSITION, lightPos);
glLightfv(GL_LIGHT0,GL_SPOT_DIRECTION,spotDir);

//绘制一个红色的锥体 封装光源
glColor3ub(255,0,0);

//把原点移动到光锥外光的位置
glTranslatef( lightPos[0], lightPos[1], lightPos[2]);

glutSolidCone(4.0f,6.0f,15,15);

//在不同位置绘制一个更小的球体,表示灯泡
//保存光照状态变量
glPushAttrib(GL_LIGHTING_BIT);

//关闭光照,并指定一个明亮的黄色球体
glDisable(GL_LIGHTING);
glColor3ub(255,255,0);
glutSolidSphere(3.0,15,15);

//恢复光照
glPopAttrib();

//恢复坐标转换
glPopMatrix();

//设置材料颜色,在中间绘制一个球体
glColor3ub(0,0,255);