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.
頂點(diǎn)處理器負(fù)責(zé)運(yùn)行頂點(diǎn)著色器。頂點(diǎn)著色器的輸入為頂點(diǎn)數(shù)據(jù),也就是它的位置、顏色和法線等,這取決于OpenGL應(yīng)用程序的發(fā)送。
下面的OpenGL代碼為每個(gè)頂點(diǎn)向頂點(diǎn)處理器發(fā)送了一個(gè)顏色和一個(gè)頂點(diǎn)位置信息。
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 ();
在一個(gè)頂點(diǎn)著色器中,你可以編寫代碼用于完成如下任務(wù):
- 使用模型視圖和投影矩陣進(jìn)行頂點(diǎn)位置變換
- 法線變換,如果需要,還有法線的標(biāo)準(zhǔn)化
- 紋理坐標(biāo)生成和變換
- 每個(gè)頂點(diǎn)的光照或?yàn)槊總€(gè)像素計(jì)算光照值
- 顏色計(jì)算
并沒有要求你的著色器執(zhí)行上面的所有操作,例如你的應(yīng)用程序可能不使用光照。盡管如此,一旦你編寫了一個(gè)頂點(diǎn)著色器并且用于替換頂點(diǎn)處理器的全部功能,那么你就不能執(zhí)行法線變換,不能期望固定功能執(zhí)行紋理坐標(biāo)生成。當(dāng)使用頂點(diǎn)著色器后,那么它負(fù)責(zé)管線中本階段的所有功能。
在前一小節(jié),我們了解到頂點(diǎn)處理器并沒有關(guān)于頂點(diǎn)的連接信息,因?yàn)樾枰負(fù)湫畔⒌牟僮鞑荒茉陧旤c(diǎn)著色器中進(jìn)行。例如頂點(diǎn)著色器不可能執(zhí)行背面剔除操作,因?yàn)轫旤c(diǎn)處理器處理的是頂點(diǎn)而不是面。頂點(diǎn)處理器孤立地處理每個(gè)頂點(diǎn),處理每個(gè)頂點(diǎn)時(shí),并不需要其他頂點(diǎn)的信息。
頂點(diǎn)著色器至少負(fù)責(zé)寫一個(gè)變量:gl_Position,通常是使用模型視圖和投影矩陣變換頂點(diǎn)。
頂點(diǎn)著色器能夠訪問OpenGL狀態(tài),因此它能夠執(zhí)行光照,使用材料等操作。它還能夠訪問紋理(只在最新的硬件上可用)。但是它不能夠訪問幀緩沖區(qū)。
散射光照:散射光照方程:Cdiff= max{N•L,0}*Cmat*Cli