Drawing many unique triangles with a single draw c

2019-08-08 02:04发布

Here is a fiddle of the simplest case: http://jsfiddle.net/headchem/r28mm/10/

Is there any way to avoid calling this line for every single triangle I wish to draw?

gl.drawArrays(gl.TRIANGLES, 0, numItems);

As a learning exercise, I'm trying to create a 2D game out of simple colored triangles. I'd like to put several hundred moving triangles on screen each frame, but my framerate is very slow with my current attempts. I suspect it's because of the hundreds of drawArrays() calls I am making each frame.

I've read a bit about Vertex Buffer Objects, and this question sounds promising, but I'm having trouble putting all the pieces together in my fiddle demo above. Is it possible to render hundreds of unique 2D triangle shapes + different colors + transparency in a single draw call with good performance?

1条回答
在下西门庆
2楼-- · 2019-08-08 02:44

Weather you use a VBO or not you seem to have a major problem in your vertex data design as each object contains the data needed for drawing and those data are not in the same array. First thing you should consider is how to pack those data together. In my opinion it would be best to create an array of vertices in your case combined both positions and colours, then your triangle objects should have a reference to a specific point that array where its vertex data lay. For instance the first object would be at 0, second would be at (3*3 + 3*4) as in (number_of_vertices * number_of_floats_per_point + number_of_vertices * number_of_floats_per_color). In this case you can now draw all the triangles using a single draw call with this same array of vertex data.

There can be a few problems in this procedure as you might need to inflate/deflate the array of data but you should be able to make it.

As for VBO the procedure is exactly the same except you need to maintaing the whole array as the VBO, getting the pointer and changing the data on the fly. Now if those data are constantly moving (you are changing most of the data on every frame) then you will gain nothing from the VBO and it is useless to even crate it. But if you do use it try to have only 1 buffer for all the triangles.

Also note you do NEED to have a colour as an attribute and must be defined per-vertex to complete your drawing as a single draw call.

查看更多
登录 后发表回答