javascript 在 WebGL 中动态更改顶点缓冲区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7166931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change vertex buffer dynamically in WebGL
提问by Sebastian Breit
I'm developing a cloth simulator in WebGL, got all the physics and the animation ready but I just can't render it. I am used to use glVertex in Opengl, so in every iteration I can change the position of the vertex and it will move, but in WebGL (OpenGL ES) there is not such method.
我正在 WebGL 中开发布料模拟器,准备好所有物理和动画,但我无法渲染它。我习惯在Opengl中使用glVertex,所以在每次迭代中我可以改变顶点的位置并且它会移动,但是在WebGL(OpenGL ES)中没有这样的方法。
This is my code:
这是我的代码:
//Initialization:
puntosBuffer= gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, puntosBuffer);
telaVertices3=new Array(12);
telaVertices3=[
0.0,0.0,0.0,
2.0,0.0,0.0,
1.0,1.7,0.0,
0.0,1.0,0.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(telaVertices3), gl.DYNAMIC_DRAW);
//loop:
posx=posx+0.2;
telaVertices3[0]=posx;
gl.bindBuffer(gl.ARRAY_BUFFER, puntosBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, new Float32Array(telaVertices3));
But it always renders at the same points!!!
但它总是在相同的点呈现!!!
回答by sinisterchipmunk
I use additional calls to gl.bufferData(...)
instead of gl.bufferSubData(...)
. I don't know if this matters or not, but I think it's the only thing I'm doing differently from your example.
我使用额外的调用来gl.bufferData(...)
代替gl.bufferSubData(...)
. 我不知道这是否重要,但我认为这是我唯一与您的示例不同的事情。
You can see my current implementation of buffer management at jax/buffer.js#L48and an older version at webgl/buffer.js#L26. As you can see, I'm not doing anything special:
您可以在jax/buffer.js#L48和webgl/buffer.js#L26 中查看我当前的缓冲区管理实现和旧版本。如您所见,我没有做任何特别的事情:
gl.bindBuffer(self.bufferType, buffer);
gl.bufferData(self.bufferType, instance, self.drawType);
You can see the animation in a live demo at webgldemos/md2.
您可以在webgldemos/md2的现场演示中看到动画。
However
然而
If you're planning to update a lot of vertices at once then this is probably not the best method. Instead, I'd propose sending the relevant data down to the video card and performing animation directly within GLSL, so that you aren't limited by JavaScript slowness and can take advantage of hardware acceleration. In fact, I'm transitioning most of my code to work this way. Two live examples of vertex manipulation on the video card are available at jax/blobularand jax/meadow. The source code for those demos is freely available hereand here, respectively.
如果您打算一次更新很多顶点,那么这可能不是最好的方法。相反,我建议将相关数据发送到显卡并直接在 GLSL 中执行动画,这样您就不会受到 JavaScript 缓慢的限制,并且可以利用硬件加速。事实上,我正在将我的大部分代码转换为以这种方式工作。在jax/blobular和jax/meadow中提供了视频卡上顶点操作的两个实时示例。这些演示的源代码分别可在此处和此处免费获得。
I hope this was helpful to you.
我希望这对你有帮助。