Javier-Garzo / Marching-cubes-on-Unity-3D

Terrain voxel engine with the use of Marching Cubes implemented in Unity 2020.3.17f1 (LTS).
MIT License
332 stars 43 forks source link

Too much vertices? #15

Closed dario2pro closed 1 year ago

dario2pro commented 1 year ago

Hi, I have been having fun with your code, and making some changes. I realized on flat planes mesh has 1536 vertices, and 512 triangles. Shouldn't there be 289 vertices since plane is 17 * 17. I just wanted to ask if i could improve performance by reducing the number of vertices somehow.

Javier-Garzo commented 1 year ago

First of all, sorry for the late response. The problem with the big amount pf vertexs (I will explain like if it was 2D), you have the information vertex matrix, that is that 1717, which vertex contains if it's air or terrain and the type of terrain (color). However, from that information matrix we need to transform it to a mesh using the Marching Cubes algorithm. When you get 4 vertex to generate the cell of terrain, you need two triangles for represent it, so you can calculate the number of vertex 161623 = 1536 (Number of cells triangles per. cell vertex per triangle). The code that generate the mesh don't check if exit a vertex in that position, so for that reason we always use the max number of vertex. You can modify the code to check if in the same voxel exist other vertex with the same position but it will cause more CPU usage for the chunk build. You need to chose CPU on chunk generation or GPU for extra vertex.

The idea of reducing the number of vertex can be improved from two possible solutions, the previous one mentioned that will decrease the number of vertex by reutilisation of existing ones in same positions but not expect a big change if the terrain is not plain. Other posible solutions it's the use of a LOD system where you get the 17*17 vertex and reduce the size of the matrix by adding the near vertex. so if we apply a x2 reduction we have a 9x9 information matrix(remember that the impair line of vertex is used to save the vertex from the attached chunk, needed for build the chunk). This second solution allow you a more render because the low quality chunk need les time to build and have less vertices and triangles.

There is a big load of information in this answer if you need more explanation of some part, just ask a question about it.