How to efficiently remove a triangle from the middle of a webgl attribute buffer
Asked Answered
M

1

12

I'm wondering how to efficiently remove a triangle from the middle a webgl attribute buffer.

The first solution that comes to mind would be to rebuffer all the data from the middle to the end, shifting everything back one. This seems pretty inefficient for just wanting to remove a single triangle.

The second solution that I thought of would be to add an additional attribute to track whether a triangle was removed and if so move it outside the frustum in the vertex shader to get culled. This adds memory overhead and I guess you would want to track the triangles that were removed in order to reuse those chunks of memory.

I guess a third way would be to take the last triangle in the buffer and move it into the spot of the triangle being removed and then decrement the number of triangles to draw.

Is there a common way to solve this problem?

Millisent answered 24/2, 2021 at 4:13 Comment(1)
Maybe htis helps, it's no direct answer but a long page with general hints: developer.mozilla.org/en-US/docs/Web/API/WebGL_API/….Cardiology
S
4

The simplest and probably most common solution is to manipulate the buffer. Moving the last triangle of the buffer to the position of the triangle to remove and rendering 1 triangle less is probably the most efficient solution. Alternatively, just change the vertex coordinates of the 2nd and 3rd points of the triangle to be equal to the 1st point.
A Triangle primitives where 2 (or all 3) points are equal will not render at all. You don't have to update the entire buffer because you can use bufferSubData to change just those two vertex attributes. If a vertex consists of 3 floats, that means changing only 24 bytes.
If you use an index buffer (ELEMENT_ARRAY_BUFFER), the solution is even simpler. You just have to make the 3 indices of the triangle equal or replace the indices with the index of the last triangle.
No matter what you decide, you always have to make sure that you only have to do it once. Change the buffer once and render the updated buffer every frame. This has the least impact on performance.

Sargent answered 9/5, 2022 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.