1. 程式人生 > 實用技巧 >著色器-GLSL

著色器-GLSL

檔案字尾.vert // 頂點著色器

檔案字尾.frag // 片段著色器

#version version_number
in type in_variable_name;

out type out_variable_name; uniform type uniform_name; int main() { // 處理輸入並進行一些圖形操作 ... // 輸出處理過的結果到輸出變數 out_variable_name = weird_stuff_we_processed; }

xx.vert

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location 
= 1) in vec3 aColor; layout (location = 2) in vec2 aTexCoord; out vec3 outColor; out vec2 TexCoord; void main(){ gl_Position = vec4(aPos, 1.0f); outColor = aColor; TexCoord = aTexCoord; }

xx.frag

#version 330 core
out vec4 FragColor;

in vec3 outColor;
in vec2 TexCoord;

uniform sampler2D ourTexture;

void main() { FragColor = texture(ourTexture, TexCoord); }

頂點著色器與片段著色器通訊用關鍵詞in和out.

著色器與cpu通訊使用uniform. uniform vec4 ourColor; // 在OpenGL程式程式碼中設定這個變數

int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
glUseProgram(shaderProgram);
glUniform4f(vertexColorLocation, 0.0f, 1.0f, 0.0f
, 1.0f);

使用location這一元資料指定輸入變數,這樣可以在CPU上配置頂點屬性.數字0,1,2對應位置,也可以忽略layout (location = 0)識別符號,通過在OpenGL程式碼中使用glGetAttribLocation查詢屬性位置值(Location)

    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    // texture coord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);