在OpenGL 4中绘制几个对象

时间:2014-12-21 21:33:07

标签: opengl

我正在尝试重新创建经典游戏Asteroids作为练习OpenGL 4的练习。我读过的所有教程都开始教授如何绘制1个对象(通常是三角形)。好吧,我无法弄清楚如何绘制几个对象。我有一个三角形的船和八角形的小行星。我能够绘制它们,但它们都是连接的。

GLfloat ship_vertices[][2] = {
  { -0.05f, -0.05f },
  {  0.05f, -0.05f },
  {  0.00f,  0.05f }
};

struct asteroid
{
  GLfloat asteroid_vertices[num_asteroid_vertices][2];  
};

vector<asteroid> asteroids;

GLuint asteroid_buffer_object;
GLuint ship_buffer_object;
GLuint asteroid_vao;
GLuint ship_vao;


void InitializeVertexBuffer()
{
    glGenBuffers(1, &asteroid_buffer_object);
    glBindBuffer(GL_ARRAY_BUFFER, asteroid_buffer_object);
    glBufferData(GL_ARRAY_BUFFER, sizeof(asteroid)*asteroids.size(), &asteroids[0], GL_STATIC_DRAW);
    cout << sizeof(asteroid) << endl;
    cout << asteroids.size() << endl;
    cout << sizeof(asteroid)*asteroids.size() << endl;
    glGenVertexArrays(1, &asteroid_vao);
    glBindVertexArray(asteroid_vao);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glGenBuffers(1, &ship_buffer_object);
    glBindBuffer(GL_ARRAY_BUFFER, ship_buffer_object);
    glBufferData(GL_ARRAY_BUFFER, sizeof(ship_vertices), ship_vertices, GL_STATIC_DRAW);
    glGenVertexArrays(1, &ship_vao);
    glBindVertexArray(ship_vao);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0); 
}

void display()
{
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);

  glUseProgram(theProgram);
  glBindVertexArray(asteroid_vao);

  glDrawArrays(GL_LINE_LOOP, 0, num_asteroid_vertices*asteroids.size());

  glBindVertexArray(ship_vao);
  glDrawArrays(GL_LINE_LOOP, 0, num_ship_vertices);

  glBindVertexArray(0);
  glUseProgram(0);

  glutSwapBuffers();
}

1 个答案:

答案 0 :(得分:0)

线环将每个点连接到下一个点并且不会区分小行星(openGL不知道你试图绘制几个小行星)

你需要一个代替:

for(int i = 0; i < asteroids.size(); i++){
    glDrawArrays(GL_LINE_LOOP, num_asteroid_vertices*i, num_asteroid_vertices);
}

但是glMultiDrawArrays会对此有所帮助;

GLint[] startindexes = new GLInt[asteroids.size()];
GLsizei[] numberindexes = new GLsizei[asteroids.size()];
for(int i = 0; i < asteroids.size(); i++){
    startindexes[i] = num_asteroid_vertices*i;
    numberindexes[i] = num_asteroid_vertices;
}
glMultiDrawArrays(GL_LINE_LOOP, startindexes, numberindexes, asteroids.size());

还有一个indirect variant,其中这些数组存储在VBO中