2013-09-30 71 views
1

我想了解改變opengl中指向光源位置的效果,但遇到問題。有人可以解釋不同的位置如何影響模型的照明?如何在opengl中設置光源的位置?

我使用的代碼如下 -

void display() 
{ 
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
glMatrixMode(GL_MODELVIEW); 
glLoadIdentity(); 
GLfloat lightPos0[] = {0.0f,0.0f, -1.0f, 0.0f}; 
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0); 
//gluLookAt(0, 6, 6.0, 0, -2, 0, 0.0f, 1.0f, 0.0f); 



glTranslatef(0,0,-6); 

GLfloat ambientColor[] = {0.1f, 0.1f, 0.1f, 1.0f}; 

glRotatef(50,1,0,0); 

glRotatef(-45,0,1,0); 

glBegin(GL_QUADS); 


glNormal3f(-1,0,0); 
glColor3f(0, 0, 0); glVertex3f(-1, -1, -1); 
glColor3f(0, 0, 1); glVertex3f(-1, -1, 1); 
glColor3f(0, 1, 1); glVertex3f(-1, 1, 1); 
glColor3f(0, 1, 0); glVertex3f(-1, 1, -1); 
glNormal3f(1,0,0); 
glColor3f(1, 0, 0); glVertex3f(1, -1, -1); 
glColor3f(1, 0, 1); glVertex3f(1, -1, 1); 
glColor3f(1, 1, 1); glVertex3f(1, 1, 1); 
glColor3f(1, 1, 0); glVertex3f(1, 1, -1); 
glNormal3f(0,-1,0); 
glColor3f(0, 0, 0); glVertex3f(-1, -1, -1); 
glColor3f(0, 0, 1); glVertex3f(-1, -1, 1); 
glColor3f(1, 0, 1); glVertex3f(1, -1, 1); 
glColor3f(1, 0, 0); glVertex3f(1, -1, -1); 


glNormal3f(0,0,-1); 
glColor3f(0, 0, 0); glVertex3f(-1, -1, -1); 
glColor3f(0, 1, 0); glVertex3f(-1, 1, -1); 
glColor3f(1, 1, 0); glVertex3f(1, 1, -1); 
glColor3f(1, 0, 0); glVertex3f(1, -1, -1); 
glNormal3f(0,0,1); 
glColor3f(0, 0, 1); glVertex3f(-1, -1, 1); 
glColor3f(0, 1, 1); glVertex3f(-1, 1, 1); 
glColor3f(1, 1, 1); glVertex3f(1, 1, 1); 
glColor3f(1, 0, 1); glVertex3f(1, -1, 1); 

glEnd(); 
glTranslatef(-1,1,0); 
glRotatef(a,0,0,1); 
glTranslatef(1,-1,0); 

glBegin(GL_QUADS); 
glNormal3f(0,1,0); 
glColor3f(0, 1, 0); glVertex3f(-1, 1, -1); 
glColor3f(0, 1, 1); glVertex3f(-1, 1, 1); 
glColor3f(1, 1, 1); glVertex3f(1, 1, 1); 
glColor3f(1, 1, 0); glVertex3f(1, 1, -1); 

glEnd(); 
glFlush(); 
if(a>90) 
    a=a-90; 
a=a+1; 
glutSwapBuffers(); 
glutPostRedisplay(); 
    } 

我期待光(0,0,-1)將在立方體亮從前,因爲我已經翻譯立方體-6。但是光線從後面傳來。

回答

1

在執行轉換後,OpenGL不會將對象引用到(0,0,0)。在翻譯立方體對象時,您將參考點更改爲立方體的中心。任何你正在轉換和繪製的東西都會偏離立方體居中的地方。您需要推送並彈出變換矩陣。

glPushMatrix()

glPopMatrix()

Related Forum Post

如果我沒記錯的話,這將是你必須遵循以下格式:

glPushMatrix(); 
    glTranslatef(0,0,-6); 
    GLfloat ambientColor[] = {0.1f, 0.1f, 0.1f, 1.0f}; 
    glRotatef(50,1,0,0); 
    glRotatef(-45,0,1,0); 
    glBegin(GL_QUADS); 
    //DRAW THE OBJECT 
    glEnd(); 
glPopMatrix(); 
glPushMatrix(); 
    glTranslate(0,0,-1); 
    //Draw the light 
glPopMatrix(); 
+0

不要忘記,照明通常在渲染之前設置e場景。 – fintelia

+0

我試了一下,但沒有任何影響,它仍然從背面照亮使用光照位置(0,0,-1) – pcoder