GLSL 三種變數類型(uniform,attribute和varying)

來源:互聯網
上載者:User

做人要厚道:http://blog.csdn.net/jackers679/article/details/6848085

1.uniform變數

uniform變數是外部application程式傳遞給(vertex和fragment)shader的變數。因此它是application通過函數glUniform**()函數賦值的。在(vertex和fragment)shader程式內部,uniform變數就像是C語言裡面的常量(const ),它不能被shader程式修改。(shader只能用,不能改)

如果uniform變數在vertex和fragment兩者之間聲明方式完全一樣,則它可以在vertex和fragment共用使用。(相當於一個被vertex和fragment shader共用的全域變數)

uniform變數一般用來表示:變換矩陣,材質,光照參數和顏色等資訊。

以下是例子:

uniform mat4 viewProjMatrix; //投影+視圖矩陣
uniform mat4 viewMatrix;        //視圖矩陣
uniform vec3 lightPosition;     //光源位置

 

2.attribute變數

attribute變數是只能在vertex shader中使用的變數。(它不能在fragment shader中聲明attribute變數,也不能被fragment shader中使用)

一般用attribute變數來表示一些頂點的資料,如:頂點座標,法線,紋理座標,頂點顏色等。

在application中,一般用函數glBindAttribLocation()來綁定每個attribute變數的位置,然後用函數glVertexAttribPointer()為每個attribute變數賦值。

以下是例子:

uniform mat4 u_matViewProjection;
attribute vec4 a_position;
attribute vec2 a_texCoord0;
varying vec2 v_texCoord;
void main(void)
{
gl_Position = u_matViewProjection * a_position;
v_texCoord = a_texCoord0;
}

3.varying變數

varying變數是vertex和fragment shader之間做資料傳遞用的。一般vertex shader修改varying變數的值,然後fragment shader使用該varying變數的值。因此varying變數在vertex和fragment shader二者之間的聲明必須是一致的。application不能使用此變數。

以下是例子:

// Vertex shader
uniform mat4 u_matViewProjection;
attribute vec4 a_position;
attribute vec2 a_texCoord0;
varying vec2 v_texCoord; // Varying in vertex shader
void main(void)
{
gl_Position = u_matViewProjection * a_position;
v_texCoord = a_texCoord0;
}


// Fragment shader
precision mediump float;
varying vec2 v_texCoord; // Varying in fragment shader
uniform sampler2D s_baseMap;
uniform sampler2D s_lightMap;
void main()
{
vec4 baseColor;
vec4 lightColor;
baseColor = texture2D(s_baseMap, v_texCoord);
lightColor = texture2D(s_lightMap, v_texCoord);
gl_FragColor = baseColor * (lightColor + 0.25);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.