Advertisement
donkaban

PG Code Review

Jun 25th, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.08 KB | None | 0 0
  1.  /*-- Written in C -- */
  2.  
  3. /* common includes */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <iostream>
  7. #include <vector>
  8.  
  9. /* x-server related includes */
  10. #include<X11/X.h>
  11. #include<X11/Xlib.h>
  12.  
  13. #include "./../utils/opengl.h"
  14. #include "./../utils/shader.h"
  15.  
  16. Display                 *dpy;
  17. Window                  root;
  18. GLint                   att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
  19. XVisualInfo             *vi;
  20. Colormap                cmap;
  21. XSetWindowAttributes    swa;
  22. Window                  win;
  23. GLXContext              glc;
  24. XWindowAttributes       gwa;
  25. XEvent                  xev;
  26.  
  27.  
  28. std::vector<float> square_vertices =
  29. //   x      y     z         tx    ty
  30. {
  31.    -0.5f,  0.5f, 0.0f,     0.0f, 0.0f,
  32.     0.5f,  0.5f, 0.0f,     1.0f, 0.0f,
  33.     0.5f, -0.5f, 0.0f,     1.0f, 1.0f,
  34.    -0.5f, -0.5f, 0.0f,     0.0f, 1.0f
  35. };
  36. std::vector<uint16_t> square_indicies = {1,0,3, 3,2,1};
  37.  
  38.  
  39. void printGlError(const char* where)
  40. {
  41.         GLenum err;
  42.         err = glGetError();
  43.         if(err != GL_NO_ERROR)
  44.             printf("GL error: %d ... (at \"%s\") \n", err, where);
  45. }
  46.  
  47.  
  48. void loadGeometryToGPU(GLuint &vId, GLuint &iId )
  49. {
  50.     auto v_size = square_vertices.size() * sizeof(float);
  51.     auto i_size = square_indicies.size() * sizeof(uint16_t);
  52.     glGenBuffers(1, &vId);
  53.     glGenBuffers(1, &iId);
  54.     glBindBuffer(GL_ARRAY_BUFFER,vId);
  55.     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iId);
  56.     glBufferData(GL_ARRAY_BUFFER,v_size,&square_vertices[0], GL_STATIC_DRAW);
  57.     glBufferData(GL_ELEMENT_ARRAY_BUFFER,i_size,&square_indicies[0], GL_STATIC_DRAW);
  58.     printf("geometry: vert : %lu bytes; ndx: %lu bytes\n", v_size, i_size);
  59. }
  60.  
  61.  
  62.  
  63. GLuint createMaterial(const char * vsh, const char * fsh)
  64. {
  65.     GLuint g_program = glCreateProgram();
  66.     shaderAttachFromFile(g_program, GL_VERTEX_SHADER, vsh);
  67.     shaderAttachFromFile(g_program, GL_FRAGMENT_SHADER, fsh);
  68.     glLinkProgram(g_program);
  69.     GLint result;
  70.     glGetProgramiv(g_program, GL_LINK_STATUS, &result);
  71.     if(result == GL_FALSE)
  72.     {
  73.         GLint length;
  74.         char *log;
  75.         glGetProgramiv(g_program, GL_INFO_LOG_LENGTH, &length);
  76.         log = (char*)malloc(length);
  77.         glGetProgramInfoLog(g_program, length, &result, log);
  78.         fprintf(stderr, "sceneInit(): Program linking failed: %s\n", log);
  79.         free(log);
  80.         glDeleteProgram(g_program);
  81.         g_program = 0;
  82.     }
  83.     return g_program;
  84. }
  85.  
  86. void bindAttributes(GLuint gl_program)
  87. {
  88.         GLint pos_attr = glGetAttribLocation(gl_program, "in_position");
  89.         GLint tc_attr  = glGetAttribLocation(gl_program, "tcoordinate");
  90.  
  91.         printGlError("after getting in_position location");
  92.         if(pos_attr != -1)
  93.         {    
  94.             glVertexAttribPointer(
  95.                 pos_attr,                    
  96.                 3,                   // размер аттрибута - 3 флоата, позиция    
  97.                 GL_FLOAT,                
  98.                 GL_FALSE,                
  99.                 sizeof(float) * 5,   // размер вертекса (у нас сейчас - 5 флоатов)    
  100.                 (const void *)(0)    // смешение в вертексе до интересующего нас значения          
  101.             );
  102.             glEnableVertexAttribArray(pos_attr);
  103.         }
  104.         if(tc_attr != -1)
  105.         {
  106.             glVertexAttribPointer(
  107.                 tc_attr,  
  108.                 2,                      
  109.                 GL_FLOAT,                
  110.                 GL_FALSE,                
  111.                 sizeof(float) * 5,      
  112.                 (const void *)(3*sizeof(float))
  113.             );
  114.             glEnableVertexAttribArray(tc_attr);
  115.         }  
  116.         printGlError("after glVertexAttribPointer");
  117. }
  118.  
  119.  
  120. void draw(GLuint vertexID, GLuint indexID, GLuint materialID)
  121. {
  122.     glUseProgram(materialID);                        // текущая программа
  123.     glBindBuffer(GL_ARRAY_BUFFER,vertexID);          // текущий буфер вершин
  124.     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexID);   // текущие индексы
  125.      
  126.     bindAttributes(materialID); // размечаем аттрибуты
  127.    
  128.     // заполняем униформы :
  129.  
  130.     GLint timeUniformHandle = glGetUniformLocation(materialID, "time");
  131.     GLfloat time = (GLfloat)clock() / (GLfloat)CLOCKS_PER_SEC  * 10.0;
  132.     glUniform1f(timeUniformHandle, time);
  133.    
  134.     // рисуем
  135.  
  136.     glDrawElements(GL_TRIANGLES, square_indicies.size(),GL_UNSIGNED_SHORT,(const void *)(0));
  137. }
  138.  
  139.  
  140. int main()
  141. {
  142.  
  143.     dpy = XOpenDisplay(NULL);
  144.     if(!dpy)
  145.     {
  146.         printf("\n\tcannot connect to X server\n\n");
  147.         exit(0);
  148.     }
  149.     root = DefaultRootWindow(dpy);
  150.     vi = glXChooseVisual(dpy, 0, att);
  151.     if(vi == NULL)
  152.     {
  153.         printf("\n\tno appropriate visual found\n\n");
  154.         exit(0);
  155.     } else {
  156.             printf("\n\tvisual %p selected\n", (void *)vi->visualid); /* %p creates hexadecimal output like in glxinfo */
  157.     }
  158.     cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
  159.     swa.colormap = cmap;
  160.     swa.event_mask = ExposureMask | KeyPressMask;
  161.     win = XCreateWindow(dpy, root, 0, 0, 600, 600, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa);
  162.     XMapWindow(dpy, win);
  163.     XStoreName(dpy, win, "VERY SIMPLE APPLICATION (PRESS ESC TO EXIT!) ");
  164.     glc = glXCreateContext(dpy, vi, NULL, GL_TRUE);
  165.     glXMakeCurrent(dpy, win, glc);
  166.     glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  167.     XGetWindowAttributes(dpy, win, &gwa);
  168.     glViewport(0, 0, gwa.width, gwa.height);
  169.     glEnable(GL_DEPTH_TEST);
  170.  
  171.     printf(" gl version = %s ...\n", glGetString(GL_VERSION));
  172.     printf(" glsl version = %s ...\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
  173.  
  174.     // загрузили геометрию и материал
  175.    
  176.     GLuint vertexID;
  177.     GLuint indexID;
  178.     loadGeometryToGPU(vertexID,indexID);
  179.     auto materialID = createMaterial("vshader_attr.txt","fshader_attr.txt");
  180.  
  181.     // основной цикл
  182.  
  183.     while(true)
  184.     {
  185.         for (int i = 0; i < XPending(dpy); i++)
  186.         {    
  187.             XNextEvent(dpy, &xev);
  188.             switch(xev.type)
  189.             {
  190.                 case KeyPress :
  191.                 {
  192.                     printf("KeyPress: keycode %u state %u\n", xev.xkey.keycode, xev.xkey.state);
  193.                     if(xev.xkey.keycode == 9 || xev.xkey.keycode == 61 )
  194.                     {
  195.                         glXMakeCurrent(dpy, None, NULL);
  196.                         glXDestroyContext(dpy, glc);
  197.                         XDestroyWindow(dpy, win);
  198.                         XCloseDisplay(dpy);
  199.                         exit(0);
  200.                     }
  201.                 }
  202.            
  203.                 default:
  204.                     break;
  205.             }
  206.         }
  207.          
  208.         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // стираем
  209.         draw(vertexID,indexID,materialID);                  // рисуем
  210.         glXSwapBuffers(dpy, win);                           // показываем
  211.     }
  212. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement