//=====================================================================
//TITLE:
// 《OpenGL编程指南》示例笔记(1)--渲染光照球体
//AUTHOR:
// norains
//DATE:
// Monday 21-June-2010
//Environment:
// Windows XP
//=====================================================================
示例概述
例名:渲染光照球体
序号:5-1
页码:P127
源代码:
#include ".//glut//glut.h" #include "windows.h" void Init() { GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat mat_shininess[] = {50.0}; GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0}; GLfloat white_light[] = {1.0, 1.0, 1.0, 1.0}; GLfloat lmodel_ambient[] = {0.1, 0.1, 0.1, 1.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); glLightfv(GL_LIGHT0,GL_DIFFUSE,white_light); glLightfv(GL_LIGHT0,GL_SPECULAR,white_light); glLightModelfv(GL_LIGHT_MODEL_AMBIENT,lmodel_ambient); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } void Display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutSolidSphere(1.0, 20, 16); glFlush(); } void Reshape(int w, int h) { glViewport(0,0,(GLsizei)w,(GLsizei)h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(w <= h) { glOrtho(-1.5, 1.5, -1.5 *(GLfloat)h / (GLfloat)w,1.5 * (GLfloat)h / (GLfloat)w,-10.0,10.0); } else { glOrtho(-1.5 * (GLfloat)w / (GLfloat)h,1.5*(GLfloat)w/(GLfloat)h,-1.5,1.5,-10.0,10.0); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char **argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500,500); glutInitWindowPosition(200,200); glutCreateWindow(argv[0]); Init(); glutDisplayFunc(Display); glutReshapeFunc(Reshape); glutMainLoop(); return 0; }
运行显示:
球体并不是很圆,可以很明显看到是由线条所组成的。我们更改一下glutSolidSphere的第二个形参赋值,将其更改为300,即:glutSolidSphere(1.0, 300, 16);
这时候的显示就圆滑很多,像一个真正的球了:
原代码里的光源是白色的,我们更改一下光源的颜色看看是什么效果。我们将white_light的数值更改为红色,即:
GLfloat white_light[] = {1.0, 0.0, 0.0, 1.0};
程序运行时显示如下:
红不溜秋的,很充实,呵呵~
原来的代码只有一个光源LIGHT0,我们现在手动再添加一个光源LIGHT1。先将之前的white_light数值恢复为白色光,然后添加一个红色的光源。我们下面的代码添加到Init函数的后面:
GLfloat red_light[] = {1.0, 0.0, 0.0, 1.0};
Lightfv(GL_LIGHT1,GL_POSITION,light_position);
glLightfv(GL_LIGHT1,GL_DIFFUSE,red_light);
glLightfv(GL_LIGHT1,GL_SPECULAR,red_light);
glEnable(GL_LIGHT1);
程序的运行如图:
最后,我们移动一下光源的X轴,即light_position的数值更改为:
GLfloat light_position[] = {-20.0, 1.0, 10.0, 0.0};
程序跑起来,我们看到光源很明显移到了左边: