OpenGL 缓冲区更新 [英] OpenGL buffer update

查看:103
本文介绍了OpenGL 缓冲区更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在编写一个模拟水的程序.以下是我执行的步骤:

Currently I'm writing a program that simulates water. Here are the steps that I do:

  1. 创建水面 - 平面.
  2. 创建 VAO
  3. 创建顶点缓冲区对象,在其中存储法线和顶点.
  4. 绑定指向此 VBO 的指针.
  5. 创建索引缓冲区对象.

然后我使用 glDrawElements 渲染这个平面,然后我调用一个 update() 函数来改变水面顶点的位置.之后我调用 glBufferSubData 函数来更新顶点位置.

Then I render this plane using glDrawElements and then I invoke an update() function which changes positions of vertices of water surface. After that I invoke glBufferSubData function to update vertices positions.

当我这样做时 - 没有任何反应,就好像缓冲区没有改变一样.

When I do that - nothing happens as if the buffer isn't changed.

这是代码片段:

glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Oscillator) * nOscillators, oscillators, GL_DYNAMIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Oscillator), 0);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Oscillator), (const GLvoid*)12);
glEnableVertexAttribArray(0);  // Vertex position
glEnableVertexAttribArray(2);  // normals position

glGenBuffers(1, &indicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * nIndices, indices, GL_DYNAMIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer);
glBindVertexArray(0);

然后渲染:

glBindVertexArray(vaoHandle);
glDrawElements(GL_TRIANGLES, nIndices, GL_UNSIGNED_INT, 0); 
update(time);

和更新功能:

//some calculations
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Oscillator) * nOscillators, oscillators);

Oscillator - 这是一个结构,分别具有:8 个浮点数 - x、y、z(顶点位置)、nx、ny、nz(法线)、upSpeed、新的

Oscillator - it's a structure that has: 8 floats respectively - x, y, z (vertex position), nx, ny, nz (normals), upSpeed, newY

oscillators - 这是一个振荡器结构数组.

oscillators - this is an array of Oscillator structures.

我做错了什么?

推荐答案

在更新数据之前,您必须绑定正确的缓冲区.例如:

Before updating the data you have to bind the correct buffer. E.g:

glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

由于您一次更新完整缓冲区,我建议使用 glMapBuffer 来更新它

Since you are updating the full buffer at once I would suggest to use glMapBuffer to update it

void* data = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
//[...] update the buffer with new values
bool done = glUnmapBuffer(GL_ARRAY_BUFFER);

记住在修改要复制到 gl 缓冲区的数据之前等待(或强制)glFlush().

And remember to wait (or force) a glFlush() before modifying the data you are goin to copy to the gl buffer.

这篇关于OpenGL 缓冲区更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆