[OpenGL]Shader編譯流程示例

這裡以演示如何編譯Vertex Shader為例,其他類型的Shader類似。

1,先用io流讀取shader文件

std::stringstream code;ncode << inFile.rdbuf();ninFile.close();nstring codeStr(code.str());n

2,創建空白Shader對象

GLuint vertShader = glCreateShader( GL_VERTEX_SHADER );n

3,編譯Shader代碼到Shader對象中

// Load the source code into the shader objectnconst GLchar* codeArray[] = {codeStr.c_str()};nglShaderSource(vertShader, 1, codeArray, NULL);nn// Compile the shadernglCompileShader( fragShader );n

4,Shader鏈接

4.1 創建program對象

// Create the program objectnGLuint programHandle = glCreateProgram();n

4.2 附加Shader對象到program對象中

// Attach the shaders to the program objectnglAttachShader( programHandle, vertShader );nglAttachShader( programHandle, fragShader );n

4.3 鏈接program

// Link the programnglLinkProgram( programHandle );n

4.4 使用program對象

glUseProgram( programHandle );n

5,創建並綁定buffer對象

// Create and populate the buffer objectsnGLuint vboHandles[2];nglGenBuffers(2, vboHandles);nGLuint positionBufferHandle = vboHandles[0];nGLuint colorBufferHandle = vboHandles[1];nnglBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);nglBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), positionData, GL_STATIC_DRAW);nnglBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);nglBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), colorData, GL_STATIC_DRAW);n

6,開闢Array數組並組裝其各個元素數據

// Create and set-up the vertex array objectnglGenVertexArrays( 1, &vaoHandle );nglBindVertexArray(vaoHandle);nnglEnableVertexAttribArray(0); // Vertex positionnglEnableVertexAttribArray(1); // Vertex colornnglBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);nglVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );nnglBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);nglVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL );nglBindVertexArray(0);n

推薦閱讀:

如何開始寫一個virtual globe軟體,類似於google earth那樣?
震驚!時間之神又給了這個古老的API+了0.1
WebGL 和 OpenGL ES 有什麼區別?
Opengl編程指南(紅寶書)第八版中文版怎麼樣,適合入門學習么?
Minecraft那些方塊用OpenGL怎麼畫比較好?

TAG:OpenGL | shader | 计算机图形学 |