幾何著色器(二) 表面法線視覺化
阿新 • • 發佈:2019-02-11
從之前的介紹,我們已經瞭解了幾何著色器的基本知識,現在介紹一下如何用幾何著色器實現表面法線的視覺化
如果是第一次瞭解幾何著色器,可以先了解基本知識:幾何著色器(一)
效果圖:
首先我們先了解一下繪製流程:
1.啟用頂點著色器和片元著色器
2.正常繪製模型
3.啟用頂點、幾何、片元著色器
4.繪製法線
也就是說我們要繪製兩次
著色器程式碼:
頂點著色器:
attribute vec3 a_Vertex; attribute vec2 a_TexCoord; uniform mat4 MVP_matrix; varying vec2 v_TexCoord0; varying vec3 v_position; varying vec4 color; out Vertex { vec2 v_TexCoord0; vec3 v_position; vec4 color; } vertex; void main(void) { gl_Position = MVP_matrix *vec4(a_Vertex,1.0); v_position = a_Vertex; v_TexCoord0 = a_TexCoord; vertex.v_TexCoord0 = a_TexCoord; vertex.v_position = a_Vertex; vertex.color = vec4(0,0,0,1); color = vec4(0,0,0,1); }
幾何著色器:
這裡我是在幾何著色器上再次計算了法線,但是如果模型已經計算了法線,那麼直接傳入然後使用就可以了。
#version 330 core layout(triangles) in ; layout(line_strip, max_vertices = 6) out; //輸出的圖元為直線,最多輸出六個點 out vec2 v_TexCoord0; out vec3 v_position; out vec4 color; in Vertex //從頂點著色器獲得的引數,注意這裡應為一個數組 { vec2 v_TexCoord0; vec3 v_position; vec4 color; } vertex[]; vec3 getNormal(vec4 pos0, vec4 pos1, vec4 pos2) { vec3 a = vec3(pos0) - vec3(pos1); vec3 b = vec3(pos2) - vec3(pos1); return normalize(cross(a, b)); } void makeDo() { int i =0; vec3 normal = getNormal(gl_in[0].gl_Position,gl_in[1].gl_Position,gl_in[2].gl_Position); vec3 c = vec3(gl_in[0].gl_Position); for( i =0; i< gl_in.length(); i++) { gl_Position = gl_in[i].gl_Position; v_position = vertex[i].v_position; v_TexCoord0 = vertex[i].v_TexCoord0; color = vec4(1,0,0,1); EmitVertex(); gl_Position = gl_in[i].gl_Position+vec4(normal,1)*2; v_position = vertex[i].v_position; v_TexCoord0 = vertex[i].v_TexCoord0; color = vec4(1,0,0,1); EmitVertex(); EndPrimitive(); } void main() { makeDo(); }
片元著色器:
uniform sampler2D u_Texture0;
in vec2 v_TexCoord0;
in vec3 v_position;
in vec4 color;
void main(void)
{
if(color ==vec4(0,0,0,1))
gl_FragColor = texture2D(u_Texture0, v_TexCoord0)*0.9;
else
gl_FragColor = vec4(0,1,0,1);
}