从零开始学习OpenGL ES之五补遗 – setupView重写

来源:互联网 发布:淘宝商家入驻怎么 编辑:程序博客网 时间:2024/04/28 14:30

我在从零开始学习OpenGL ES之四 – 光效 一文中使用了一个普通GLfloat数组。由于它没有使用任何非OpenGL定义的数据结构,所以是最为普通和方便的方式。

 

但在此我使用在第一部分中定义的Vertex3D,Vector3DColor3D数据结构重写了 setupView:方法。并不是这种方法“更好”,但是它是一种不同的方式。当我第一次学习OpenGL时,我发现使用顶点,颜色和三角形的术语比可变长度浮点数组更容易理解。如果你和我一样,那么你会发现这个版本更容易理解。

 

除了使用自定义数据结构外,我还减少了环境光元素的数量并将光源向右移动了一点。然后使用Vector3DMakeWithStartAndEndPoints()将移动的光源指向二十面体。这样做使得光效更为生动一点。

-(void)setupView:(GLView*)view{    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0;    GLfloat size;    glEnable(GL_DEPTH_TEST);    glMatrixMode(GL_PROJECTION);    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);    CGRect rect = view.bounds;    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /               (rect.size.width / rect.size.height), zNear, zFar);    glViewport(0, 0, rect.size.width, rect.size.height);    glMatrixMode(GL_MODELVIEW);    // Enable lighting    glEnable(GL_LIGHTING);    // Turn the first light on    glEnable(GL_LIGHT0);    // Define the ambient component of the first light    static const Color3D light0Ambient[] = {{0.05, 0.05, 0.05, 1.0}};    glLightfv(GL_LIGHT0, GL_AMBIENT, (const GLfloat *)light0Ambient);    // Define the diffuse component of the first light    static const Color3D light0Diffuse[] = {{0.4, 0.4, 0.4, 1.0}};    glLightfv(GL_LIGHT0, GL_DIFFUSE, (const GLfloat *)light0Diffuse);    // Define the specular component and shininess of the first light    static const Color3D light0Specular[] = {{0.7, 0.7, 0.7, 1.0}};    glLightfv(GL_LIGHT0, GL_SPECULAR, (const GLfloat *)light0Specular);    glLightf(GL_LIGHT0, GL_SHININESS, 0.4);    // Define the position of the first light   // const GLfloat light0Position[] = {10.0, 10.0, 10.0};    static const Vertex3D light0Position[] = {{10.0, 10.0, 10.0}};    glLightfv(GL_LIGHT0, GL_POSITION, (const GLfloat *)light0Position);     // Calculate light vector so it points at the object    static const Vertex3D objectPoint[] = {{0.0, 0.0, -3.0}};    const Vertex3D lightVector = Vector3DMakeWithStartAndEndPoints(light0Position[0], objectPoint[0]);    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, (GLfloat *)&lightVector);    // Define a cutoff angle. This defines a 50° field of vision, since the cutoff    // is number of degrees to each side of an imaginary line drawn from the light's    // position along the vector supplied in GL_SPOT_DIRECTION above    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 25.0);    glLoadIdentity();    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);}

 

你可以随意调整光的属性,增加额外的光源或二十面体,体验一下这些调整会为场景带来什么样的变化。这些东西是很难体验出来的,所以不要指望一晚上就理解了所有东西。

 

原文见:setupView: from Part IV Rewritten


原创粉丝点击