OpenGL緩衝區對象之UBO

轉載:http://blog.csdn.net/csxiaoshui/article/details/32101977
  • 概述

UBO(Uniform Buffer Object)是用來存儲着色語言中Uniform類型變量的緩衝區對象,使用UBO可以讓uniform變量在不同的着色語言程序中實現共用,也可以在着色語言程序中實現uniform類型變量的設置與更新。

提到UBO就必須要提到着色語言GLSL中的Uniform Blocks,它將衆多的Uniform類型的變量集中在一起進行統一的管理,對於需要大量Uniform類型變量的程序可以顯著地提高性能。

  • 優勢

相比傳統設置單個uniform類型變量的方式,ubo有着以下一些特點:

  1. 可以通過切換不同的UBO綁定迅速更新程序中的uniform類型變量的值(在單一着色語言程序中)
  2. 可以存儲更多的uniform類型變量
  3. 可以在不同的着色語言程序中通過更新UBO中的數據實現所有uniform類型變量的更新
  • 使用

UBO必須配合Uniform Block一起使用,Uniform Block的定義和C/C++中的struct很類似。Uniform Block定義的語法如下:

  1. storage_qualifier block_name  
  2. {  
  3.   <define members here>  
  4. } instance_name;  
  1. //定義MatrixBlock Uniform Block  
  2. uniform MatrixBlock  
  3. {  
  4.   mat4 projection;  
  5.   mat4 modelview;  
  6. } matrices;  
  • 關聯UBO和Uniform Block

當Uniform Block在着色語言程序中鏈接之後,會在着色語言中生成很多個綁定索引值,通過這些索引可以找到Uniform Block。獲取Uniform Block可以使用如下的API:

  1. GLuint glGetUniformBlockIndex​( GLuint program​, const char *uniformBlockName​ );  

參數中uniformBlockName指的是着色語言程序中的Uniform Block(上文中的MatrixBlock)

獲取Uniform Block index的目的是爲了使得它和uniformBlock ID值進行綁定,這個Uniform Block的ID值存放在OpenGL Context中,通過它可以作爲連接Uniform Block和UBO的橋樑:(通過把Uniform Block和UBO綁定到相同的Binding points(ID)上實現UBO和Uniform Block 的互動)


將Uniform Block 的索引值綁定到binding points需要使用下面的方式:

  1. void glUniformBlockBinding(GLuint program, GLuint uBlockIndex, GLuint uBlockBinding);  

其中uBlockIndex是前面通過glGetUniformBlockIndex得到的索引值;uBlockBinding是傳入的Binding point值

通過以上兩個函數可以完成上面示意圖中的左邊部分,右邊部分的實現通過下面的API完成:

1.glGenBuffers生成緩衝區對象,需要注意的是要創建GL_UNIFORM_BUFFER

2.glBindBuffer綁定GL_UNIFROM_BUFFER

3.glBufferData傳入緩衝區對象存儲的內容

4.glBindBufferBase來設置緩衝區與binding point的綁定

  1. void glBindBufferBase(GLenum target, GLuint bindingPoint, GLuint bufferName);  
target的取值:GL_UNIFORM_BUFFER

bindingPoint:必須和glUniformBlockBinding中的uBlockBinding值一樣,這樣就讓Block Uniform和Uniform Buffer連接起來

bufferName:通過glGenBuffers生成的ID值

整個設置綁定的過程如下所示:

  1. // 需要注意的是binding point的值必須小於GL_MAX_UNIFORM_BUFFER_BINDINGS  
  2. GLuint bindingPoint = 1;  
  3. GLuint buffer;   
  4. GLuint blockIndex;  
  5. //複製到緩衝區存儲空間的值   
  6. float myFloats[8] = {1.0, 0.0, 0.0, 1.0,   0.4, 0.0, 0.0, 1.0};  
  7. //獲取Uniform Block的索引值   
  8. blockIndex = glGetUniformBlockIndex(p, ”ColorBlock”);  
  9. //將Uniform Block的索引值和binding point關聯  
  10.  glUniformBlockBinding(p, blockIndex, bindingPoint);  
  11.  //生成UBO  
  12. glGenBuffers(1, &buffer);  
  13. glBindBuffer(GL_UNIFORM_BUFFER, buffer);  
  14.  //設置UBO存儲的數據(用來給Uniform Block中變量賦值)  
  15. glBufferData(GL_UNIFORM_BUFFER, sizeof(myFloats), myFloats, GL_DYNAMIC_DRAW);  
  16. //將UBO與同樣的binding point關聯  
  17.  glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, buffer);  

  • 設置和更新Uniform Block

假設我們定義瞭如下的Uniform Block(具體內容見後面分析)

  1. layout (std140) uniform ColorBlock {  
  2.     vec4 diffuse;  
  3.     vec4 ambient;  
  4. };  

爲了給diffuse和ambient變量設置值,最關鍵的地方是我們需要獲得這些變量在UBO中相對於UBO存儲位置的偏移量,可以通過如下的命令設置:

  1. void glGetActiveUniformBlockiv(GLuint program, GLuint uBlockIndex, GLenum pname, GLint *params);查詢Uniform Block的相關信息  
  2. 參數:<p>program:當前鏈接好的着色語言程序;</p><p>uBlockIndex:Block Uniform的索引值;</p><p>pname:GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS(查詢Block中有多少個Uniform變量);<code>GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES</code>(獲取Block中uniform的索引值)</p><p>params:獲取得到的結果</p>  

當我們獲得了Block Uniform中某個uniform的索引值之後,可以通過glGetActiveUniformsiv來獲取uniform數據:

  1. void glGetActiveUniformsiv(GLuint program, GLsizei ucount, const GLuint *uIndices, GLenum pname, GLint *params);  
  2. 參數:  
  3. ucount:索引值的個數  
  4. uindices:索引值數組  
  5. pname:我們需要獲取的內容:<code>GL_UNIFORM_TYPE</code>, <code>GL_UNIFORM_OFFSET</code>, <code>GL_UNIFORM_SIZE</code>, <code>GL_UNIFORM_ARRAY_STRIDE</code>, <code>GL_UNIFORM_MATRIX_STRIDE</code>.  
  6. params:獲取得到的結果  
當獲取到Uniform在Uniform Block中的偏移量之後,我們可以利用glBufferSubData來更新UBO中的數據,這樣就實現了設置和修改Uniform Block中相應變量的值

  1. void glBufferSubData( GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid * data);  

例如對於上面我們的ColorBlock,通過查詢我們可以看到它佔用的空間:

  1. ColorBlock  
  2.     Size 32  
  3.     Block binding point: 0  
  4.     Buffer bound to binding point: 0   
  5.     {  
  6.        ambient  
  7.             GL_FLOAT_VEC4  
  8.             offset: 16  
  9.             size: 16  
  10.        diffuse  
  11.             GL_FLOAT_VEC4  
  12.             offset: 0  
  13.             size: 16  
  14.     }  

於是,當我們需要更新ambient的數據時,我們可以這樣去做:

  1. float color[4] = {0.3, 0.0, 0.0, 1.0};  
  2. GLuint offset = 16;  
  3. glBindBuffer(GL_UNIFORM_BUFFER, buffer);  
  4. glBufferSubData(GL_UNIFORM_BUFFER, offset , sizeof(color), color);  

當我們修改一下ColorBlock中的內容:

  1. layout (std140) uniform ColorBlock2 {  
  2.     vec3 diffuse;  
  3.     vec3 ambient;  
  4. };  

再次查詢ColorBlock佔用的空間:

  1. ColorBlock2  
  2.     Size 28  
  3.     Block binding point: 0  
  4.     Buffer bound to binding point: 0   
  5.     {  
  6.        ambient  
  7.             GL_FLOAT_VEC3  
  8.             <span style=”color:#FF0000;”>offset: 16</span>  
  9.             size: 12  
  10.        diffuse  
  11.             GL_FLOAT_VEC3  
  12.             offset: 0  
  13.             <span style=”color:#FF0000;”>size: 12</span>  
  14.     }  

發現diffuse佔用的空間是12個字節,但是ambient卻是從16個字節處開始的。這裏面就涉及到一個字節對齊的概念,前面我們聲明Uniform Block的時候都使用了一個標識符std140,指的是GLSL 1.4版本的時候指定的一個字節對齊的規範,具體的內容如下表:

變量類型

變量大小/偏移量

標量數據類型(bool,int,uint,float)

基於基本機器類型的標量值大小

(例如,sizeof(GLfloat))

二元向量(bvec2,ivec2,uvec2,vec2)

標量類型大小的兩倍

三元向量(bvec3,ivec3,uvec3,vec3)

標量類型大小的四倍

三元向量(bvec4,ivec4,uvec4,vec4)

標量類型大小的四倍

標量的數組或向量

數組中每個元素大小是基本類型的大小,偏移量是其索引值(從0開始)與元素大小的乘積。整個數組必須是vec4類型的大小的整數倍(不足將在尾部填充)。

一個或多個C列R行列主序矩陣組成的數組

以C個向量(每個有R個元素)組成的數組形式存儲。會像其他數組一樣填充。

如果變量是M個列主序矩陣的數組,那麼它的存儲形式是:M*C個向量(每個有R個元素)組成的數組。

一個或多個R行C列的行主序矩陣組成的數組

以R個向量(每個有C個元素)組成的數組。默認像其他數組一樣填充。

如果變量是M個行主序矩陣組成的數組,則存儲形式是M*R個向量(每個有C個元素)組成的數組。

單個結構體或多個結構體組成的數組

單個結構體成員的偏移量和大小可以由前面的規則計算出。結構大小總是vec4大小的整數倍(不足在後面補齊)。

由結構組成的數組,偏移量的計算需要考慮單個結構的對齊和補齊。結構的成員偏移量由前面的規則計算出。


也就是說我們有兩種方式來更新這些Uniform Block中的Uniform變量的值:

1.使用OpenGL中的查詢函數來查詢Uniform Block中Uniform變量在UBO中的偏移量,然後使用glBufferSubData更新之;

2.使用std140之後直接尋找到uniform在UBO中的偏移量(由於它是一個標準,因此具體大小可以自己計算),然後使用glBufferSubData更新之。


下面使用一個具體的例子來總結UBO的使用方法:(使用FreeGlut)

  1. #pragma comment(lib, “glew32.lib”)  
  2. #pragma comment(lib, “freeglut.lib”)  
  3.   
  4. #include <gl/glew.h>  
  5. #include <gl/freeglut.h>  
  6. #include <iostream>  
  7.   
  8. #include “glshadertools.h”  
  9.   
  10. GLuint      programID;  
  11. GLuint      uboID;  
  12.   
  13. GLuint bindingPoint = 1;  
  14. GLuint ubIndex;  
  15.   
  16. GLfloat color1[] = {1.0f, 0.0f, 0.0f, 0.0f};    
  17. GLfloat color2[] = {0.0f, 1.0f, 0.0f, 1.0f};    
  18.   
  19.   
  20. //////////////////////////////////////////////////////////////////////////  
  21. GLfloat xRot;         
  22. GLfloat yRot;  
  23. GLfloat zoom = -10.0f;  
  24.   
  25. bool mouseLeftDown;  
  26. float mouseX, mouseY;  
  27.   
  28.   
  29.   
  30.   
  31. void    init()  
  32. {  
  33.     programID = gltLoadShaderProgram(”hello.vert”“hello.frag”);  
  34.       
  35.     ubIndex = glGetUniformBlockIndex(programID, ”ColorBlock”);  
  36.     glUniformBlockBinding(programID, ubIndex, bindingPoint);  
  37.   
  38.     GLint   bufferSize = 0;  
  39.     glGetActiveUniformBlockiv(programID, ubIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &bufferSize);  
  40.   
  41.     glGenBuffers(1, &uboID);  
  42.     glBindBuffer(GL_UNIFORM_BUFFER, uboID);  
  43.     glBufferData(GL_UNIFORM_BUFFER, bufferSize, NULL, GL_DYNAMIC_READ);  
  44.       
  45.     glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, uboID);  
  46.       
  47.     //尋找每一個uniform變量的偏移值  
  48.     const GLchar *names[] = {“color1”,“color2”};    
  49.     GLuint indices[2];    
  50.     glGetUniformIndices(programID, 2, names, indices);    
  51.     GLint offset[2];  
  52.     glGetActiveUniformsiv(programID, 4, indices, GL_UNIFORM_OFFSET, offset);  
  53.       
  54.     //拷貝數據到UBO中(給Uniform Block中的color1和color2變量賦值)  
  55.     glBufferSubData(GL_UNIFORM_BUFFER, offset[0], 4*sizeof(float), color1);  
  56.     glBufferSubData(GL_UNIFORM_BUFFER, offset[1], 4*sizeof(float), color2);  
  57.   
  58.     glUseProgram(programID);  
  59. }  
  60.   
  61.   
  62. void reshape(int w, int h)  
  63. {  
  64.     glViewport(0, 0, (GLsizei)w, (GLsizei)h);  
  65.     glMatrixMode(GL_PROJECTION);  
  66.     glLoadIdentity();  
  67.     gluPerspective(60.0f, (float)(w)/h, 0.1f, 1000.0f);  
  68.     glMatrixMode(GL_MODELVIEW);  
  69.     glLoadIdentity();  
  70. }  
  71.   
  72.   
  73. void    display()  
  74. {  
  75.     glClearColor(0, 0, 0, 0);  
  76.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
  77.     glColor3f(1.0f, 0.0f, 1.0f);  
  78.   
  79.     glLoadIdentity();  
  80.   
  81.     glTranslatef(0, 0, zoom);  
  82.     glRotatef(xRot, 1, 0, 0);   // pitch  
  83.     glRotatef(yRot, 0, 1, 0);   // heading  
  84.   
  85.     glutSolidTeapot(2.0);  
  86.   
  87.     glutSwapBuffers();  
  88. }  
  89.   
  90.   
  91.   
  92. void mouse(int button, int state, int x, int y)  
  93. {  
  94.     mouseX = (float)x;  
  95.     mouseY = (float)y;  
  96.   
  97.     switch (button)  
  98.     {  
  99.     case GLUT_LEFT_BUTTON:  
  100.         {  
  101.             if (state == GLUT_DOWN) {  
  102.                 mouseLeftDown = true;  
  103.             } else if (state == GLUT_UP) {  
  104.                 mouseLeftDown = false;  
  105.             }  
  106.         }  
  107.         break;  
  108.   
  109.     case GLUT_RIGHT_BUTTON:  
  110.         {  
  111.             if (state == GLUT_DOWN) {  
  112.   
  113.             }  
  114.         }  
  115.         break;  
  116.   
  117.     default:  
  118.         break;  
  119.     }  
  120. }  
  121.   
  122.   
  123. void mouseMove(int x, int y)  
  124. {  
  125.     if(mouseLeftDown)  
  126.     {  
  127.         yRot += (x - mouseX);  
  128.         xRot += (y - mouseY);  
  129.         mouseX = (float)x;  
  130.         mouseY = (float)y;  
  131.     }  
  132.     glutPostRedisplay();  
  133. }  
  134.   
  135.   
  136. void mouseWheel(int wheel, int direction, int x, int y)  
  137. {  
  138.     switch (direction)  
  139.     {  
  140.   
  141.     case 1: //means wheel up  
  142.         {  
  143.             zoom -= 1.0f;  
  144.         }  
  145.         break;  
  146.   
  147.     case -1: //means wheel down  
  148.         {  
  149.             zoom += 1.0f;  
  150.         }  
  151.         break;  
  152.   
  153.     default:  
  154.         break;  
  155.     }  
  156.     glutPostRedisplay();  
  157. }  
  158.   
  159.   
  160. void keyboard(unsigned char key, int x, int y)  
  161. {  
  162.     switch(key)  
  163.     {  
  164.     case 27: // ESCAPE  
  165.         exit(0);  
  166.         break;  
  167.   
  168.     default:  
  169.         break;  
  170.     }  
  171.   
  172. }  
  173.   
  174.   
  175. void idle()  
  176. {  
  177.     glutPostRedisplay();  
  178. }  
  179.   
  180.   
  181. int main(int argc, char** argv)  
  182. {  
  183.     glutInit(&argc, argv);  
  184.     glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);  
  185.     glutInitWindowSize(640, 480);  
  186.     glutCreateWindow(argv[0]);  
  187.     if (glewInit()) {  
  188.         std::cerr << ”Unable to initialize GLEW … exiting” << std::endl;  
  189.         exit(EXIT_FAILURE);  
  190.     }  
  191.     init();  
  192.     glutDisplayFunc(display);  
  193.     glutReshapeFunc(reshape);  
  194.     glutMouseFunc(mouse);  
  195.     glutMotionFunc(mouseMove);  
  196.     glutMouseWheelFunc(mouseWheel);  
  197.     glutKeyboardFunc(keyboard);  
  198.     glutIdleFunc(idle);  
  199.     glutMainLoop();  
  200. }  

程序簡單地將兩個顏色值相加作爲最終輸出片元的顏色:

頂點Shader:

  1. #version 330  
  2.   
  3. void main()  
  4. {  
  5.     gl_Position = ftransform();  
  6. }  

片元shader:

  1. #version 330  
  2.   
  3. layout (std140) uniform ColorBlock  
  4. {  
  5.     vec4 color1;  
  6.     vec4 color2;  
  7. };  
  8.   
  9. void main()  
  10. {  
  11.     gl_FragColor = color1 + color2;  
  12. }  

發佈了23 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章