2012-10-07 79 views
-1

我試圖通過繪製頂點做出3D方形截錐:爲什麼我的「自制」openGL 3D對象沒有正確着色?

int xPts[] = { 1.0, 1.0, -1.0, -1.0, 2.0, 2.0, -2.0, -2.0 }; 
int yPts[] = { 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0 }; 
int zPts[] = { 1.0, -1.0, -1.0, 1.0, 2.0, -2.0, -2.0, 2.0 }; 

int sideA[] = { 0, 3, 7, 4 }; 
int sideB[] = { 0, 1, 5, 4 }; 
int sideC[] = { 2, 3, 7, 6 }; 
int sideD[] = { 1, 2, 6, 5 }; 

glPolygonMode(GL_FRONT, GL_FILL); 

glPushMatrix(); 
    glTranslatef(xLoc, yLoc, zLoc); 

    glRotatef(xRotation, 1, 0, 0); 
    glRotatef(yRotation, 0, 1, 0); 
    glRotatef(zRotation, 0, 0, 1); 

    glScalef(xSize, ySize, zSize); 

    glBegin(GL_POLYGON); 
     for (int i = 0; i < 4; i++) { 
      glVertex3f(xPts[i], yPts[i], zPts[i]); 
     } 

     for (int i = 4; i < 8; i++) { 
      glVertex3f(xPts[i], yPts[i], zPts[i]); 
     } 

     for (int i = 0; i < 4; i++) { 
      glVertex3f(xPts[sideA[i]], yPts[sideA[i]], zPts[sideA[i]]); 
     } 

     for (int i = 0; i < 4; i++) { 
      glVertex3f(xPts[sideB[i]], yPts[sideB[i]], zPts[sideB[i]]); 
     } 

     for (int i = 0; i < 4; i++) { 
      glVertex3f(xPts[sideC[i]], yPts[sideC[i]], zPts[sideC[i]]); 
     } 

     for (int i = 0; i < 4; i++) { 
      glVertex3f(xPts[sideD[i]], yPts[sideD[i]], zPts[sideD[i]]); 
     } 
    glEnd(); 
glPopMatrix(); 

這成功地繪製一個正方形,圓臺,我可以旋轉,縮放和平移沒有問題。但是,陰影已關閉。它應該是明亮的黃色,但所有的邊看起來像被均勻地遮蔽。你可以看到我的陰影總體上工作在我所有其他可愛的形狀上。

我是否正在研究我的平方體的構建完全錯誤?如何正確應用陰影?

enter image description here

+1

你沒有給你的頂點正常。 –

+0

對不起,我是OpenGL的新手......我沒有意識到我需要。如何做到這一點? – carmenism

回答

3

您還需要設置使用glNormal3f法線,否則沒有照明/陰影可以計算。在你的情況下計算這些最簡單的方法是簡單地計算六個平面中每一個的兩個相鄰邊的叉積。所以,如果你手頭有一些矢量數學庫,爲第一標準的代碼看起來這個問題:

Vector3f v1(xPts[0], yPts[0], zPts[0]); 
Vector3f v2(xPts[1], yPts[1], zPts[1]); 
Vector3f v3(xPts[2], yPts[2], zPts[2]); 
Vector3f edge1 = v1 - v2; 
Vector3f edge2 = v3 - v2; 
Vector3f normal = edge2.cross(edge1).normalize(); 
glNormal3f(normal.x, normal.y, normal.z); 
for (int i = 0; i < 4; i++) 
    glVertex3f(xPts[i], yPts[i], zPts[i]); 

// ... 

(你當然希望把這個變成一個功能,而不是複製它所有六個多邊形。 ..)

相關問題