使用动态数组和缓冲区对象绘图

时间:2012-12-15 09:47:26

标签: c++ opengl graphics vertex-buffer vertex-array

创建顶点数组和索引数组时遇到问题。我不知道代码究竟出了什么问题,但我想这是阵列类型的问题,有人可以就此给我一个亮点吗?

#define GL_GLEXT_PROTOTYPES
#include<GL/glut.h>
#include<iostream>
using namespace std;

#define BUFFER_OFFSET(offset) ((GLfloat*) NULL + offset)

const GLuint numDiv = 2;
const GLuint numVerts = 9;
GLuint VAO;

void display(void) {  

  enum vertex {VERTICES, INDICES, NUM_BUFFERS};

  GLuint * buffers = new GLuint[NUM_BUFFERS];

  GLfloat (*squareVerts)[2] = new GLfloat[numVerts][2];
  GLubyte * indices = new GLubyte[numDiv*numDiv*4];

  GLuint delta = 80/numDiv;
  for(GLuint i = 0; i < numVerts; i++)
  {
  squareVerts[i][1] = (i/(numDiv+1))*delta;
  squareVerts[i][0] = (i%(numDiv+1))*delta;
  }

  for(GLuint i=0; i < numDiv; i++){
  for(GLuint j=0; j < numDiv; j++){
      //cada iteracao gera 4 pontos
      #define NUM_VERT(ii,jj) ((ii)*(numDiv+1)+(jj))
      #define INDICE(ii,jj) (4*((ii)*numDiv+(jj)))
      indices[INDICE(i,j)]   = NUM_VERT(i,j);
      indices[INDICE(i,j)+1] = NUM_VERT(i,j+1);
      indices[INDICE(i,j)+2] = NUM_VERT(i+1,j+1);
      indices[INDICE(i,j)+3] = NUM_VERT(i+1,j);
  }
  }

  glGenVertexArrays(1, &VAO);
  glBindVertexArray(VAO);

  glGenBuffers(NUM_BUFFERS, buffers);

  glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]);
  glBufferData(GL_ARRAY_BUFFER, sizeof(squareVerts),
  squareVerts, GL_STATIC_DRAW);
  glVertexPointer(2, GL_FLOAT, 0, BUFFER_OFFSET(0));
  glEnableClientState(GL_VERTEX_ARRAY);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices),
      indices, GL_STATIC_DRAW);

  glClear(GL_COLOR_BUFFER_BIT);
  glColor3f(1.0,1.0,1.0);
  glDrawElements(GL_POINTS, 16, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
  glutSwapBuffers();
}

void init() 
{
  glClearColor(0.0, 0.0, 0.0, 0.0);
  gluOrtho2D((GLdouble) -1.0, (GLdouble) 90.0, (GLdouble) -1.0, (GLdouble) 90.0);  
}

int main(int argv, char** argc) {

  glutInit(&argv, argc);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutInitWindowSize(500,500);
  glutInitWindowPosition(100,100); 
  glutCreateWindow("myCode.cpp");
  init();
  glutDisplayFunc(display);
  glutMainLoop();

  return 0;  
}

编辑:

这里的问题是绘图根本不起作用。但我没有得到任何错误,这只是不显示我想要显示的内容。 即使我把构成顶点的代码放在不同函数的缓冲区中,这也行不通。我只是试着这样做:

void display(void) {  

      glBindVertexArray(VAO);  
      glClear(GL_COLOR_BUFFER_BIT);
      glColor3f(1.0,1.0,1.0);
      glDrawElements(GL_POINTS, 16, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
      glutSwapBuffers();
}

我将其余的代码放在显示在程序启动时调用的另一个函数中。但问题仍然存在

EDIT2:

发现问题了          glBufferData(GL_ARRAY_BUFFER,的sizeof(squareVerts),squareVerts,GL_STATIC_DRAW);

sizeof(squareVerts)应为sizeof(GLfloat)* x,与索引相同。

0 个答案:

没有答案