Lighting和OpenGL ES

时间:2010-05-12 21:54:17

标签: opengl-es lighting

我正在努力在我的OpenGL ES iPhone场景上获得简单的照明。我正在显示一个以原点为中心的简单对象,并使用一个弧形球通过触摸屏幕来旋转它。所有这一切都很好,除了我尝试添加一个固定的光(固定的眼睛位置)并且它被严重拧紧:整个对象(在这个例子中是一个二十面体)被均匀地点亮,即它们都以相同的颜色出现。

我尽可能简化了我的代码,因此它是独立的,并且仍然可以重现我的体验:

    glClearColor (0.25, 0.25, 0.25, 1.);
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable (GL_DEPTH_TEST);

    glEnable(GL_LIGHTING);

    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    glOrthof(-1, 1, -(float)backingWidth/backingHeight, (float)backingWidth/backingHeight, -10, 10);

    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity ();

    GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
    GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f };
    GLfloat specularLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };
    GLfloat position[] = { -1.5f, 1.0f, -400.0f, 0.0f };

    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
    glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
    glLightfv(GL_LIGHT0, GL_POSITION, position);

    glShadeModel(GL_SMOOTH);
    glEnable(GL_NORMALIZE);

    float currRot[4];
    [arcball getCurrentRotation:currRot];
    glRotatef (currRot[0], currRot[1], currRot[2], currRot[3]);

    float f[4];
    f[0] = 0.5; f[1] = 0; f[2] = 0; f[3] = 1;
    glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT, f);
    glMaterialfv (GL_FRONT_AND_BACK, GL_DIFFUSE, f);

    f[0] = 0.2;     f[1] = 0.2; f[2] = 0.2; f[3] = 1;
    glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, f);

    glEnableClientState (GL_VERTEX_ARRAY);
    drawSphere(0, 0, 0, 1);

其中drawSphere函数实际绘制了二十面体:

static void drawSphere (float x, float y, float z, float rad)
{ 
    glPushMatrix ();
    glTranslatef (x, y, z);
    glScalef (rad, rad, rad);

    // Icosahedron
    const float vertices[] =
    { 0., 0., -1., 0., 0., 1., -0.894427, 0., -0.447214, 0.894427, 0.,
            0.447214, 0.723607, -0.525731, -0.447214, 0.723607, 0.525731,
            -0.447214, -0.723607, -0.525731, 0.447214, -0.723607, 0.525731,
            0.447214, -0.276393, -0.850651, -0.447214, -0.276393, 0.850651,
            -0.447214, 0.276393, -0.850651, 0.447214, 0.276393, 0.850651,
            0.447214 };
    const GLubyte indices[] =
    { 1, 11, 7, 1, 7, 6, 1, 6, 10, 1, 10, 3, 1, 3, 11, 4, 8, 0, 5, 4, 0,
            9, 5, 0, 2, 9, 0, 8, 2, 0, 11, 9, 7, 7, 2, 6, 6, 8, 10, 10, 4, 3,
            3, 5, 11, 4, 10, 8, 5, 3, 4, 9, 11, 5, 2, 7, 9, 8, 6, 2 };

    glVertexPointer (3, GL_FLOAT, 0, vertices);
    glDrawElements (GL_TRIANGLES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_BYTE, indices);
    glPopMatrix ();
}

我看到的结果是here。感谢任何能够对此有所了解的人(不开玩笑!)。我相信它对某些人来说看起来很琐碎,但我发誓,在此之前我已经看过很多照明教程而且被卡住了。

1 个答案:

答案 0 :(得分:1)

尝试使用glNormalPointer()添加一些顶点法线。看起来OpenGL ES只是使用default normal来处理所有事情。