The vertex shader processes incoming data from the client, applying transformations, or doing other types of math to calculate lighting effects, displacement, color values, and so on. To render a triangle with three vertices, the vertex shader is executed three times, once for each vertex. On today’s hardware, there are multiple execution units running simulta-neously, which means all three vertices are processed simultaneously. Graphics processors today are massively parallel computers. Don’t be fooled by clock speed when comparing them to CPUs. They are orders of magnitude faster at graphics operations.
頂點處理器負責運行頂點著色器。頂點著色器的輸入為頂點數據,也就是它的位置、顏色和法線等,這取決于OpenGL應用程序的發送。
下面的OpenGL代碼為每個頂點向頂點處理器發送了一個顏色和一個頂點位置信息。
1 glBegin (
);
2 glColor3f (0.2,0.4,0.6);
3 glVertex3f (-1.0,1.0,2.0);
4 glColor3f (0.2,0.4,0.8);
5 glVertex3f (1.0,-1.0,2.0);
6 glEnd ();
在一個頂點著色器中,你可以編寫代碼用于完成如下任務:
- 使用模型視圖和投影矩陣進行頂點位置變換
- 法線變換,如果需要,還有法線的標準化
- 紋理坐標生成和變換
- 每個頂點的光照或為每個像素計算光照值
- 顏色計算
并沒有要求你的著色器執行上面的所有操作,例如你的應用程序可能不使用光照。盡管如此,一旦你編寫了一個頂點著色器并且用于替換頂點處理器的全部功能,那么你就不能執行法線變換,不能期望固定功能執行紋理坐標生成。當使用頂點著色器后,那么它負責管線中本階段的所有功能。
在前一小節,我們了解到頂點處理器并沒有關于頂點的連接信息,因為需要拓撲信息的操作不能在頂點著色器中進行。例如頂點著色器不可能執行背面剔除操作,因為頂點處理器處理的是頂點而不是面。頂點處理器孤立地處理每個頂點,處理每個頂點時,并不需要其他頂點的信息。
頂點著色器至少負責寫一個變量:gl_Position,通常是使用模型視圖和投影矩陣變換頂點。
頂點著色器能夠訪問OpenGL狀態,因此它能夠執行光照,使用材料等操作。它還能夠訪問紋理(只在最新的硬件上可用)。但是它不能夠訪問幀緩沖區。
散射光照:散射光照方程:Cdiff= max{N•L,0}*Cmat*Cli