# Unity procedural smooth normals

I have a Unity project, which heavily relies on the marching cubes algorithm. Because this algorithm doesn't return the triangles in order, I can only index them in the order they are present in the vertices array.

For example:

vertices: {Vector3(0, 0, 0), Vector3(1, 0, 1), Vector3(1, 1, 0)...}
triangles: {0, 1, 2, 3...}


Because of this, Unity's RecalculateNormals method doesn't work properly and it gives me the following result:

Is there anyway I can make the normals smoother? Keep in mind, that I need to possibly recalculate these vertices everytime the values change, so I can't rely on very heavy methods.

I don't think it's the order in which you generate the triangles that's the problem, but the way you generate your vertices. If you generate a vertex position once for every voxel touching that vertex, then Unity will take that to mean that each of these copies should use its own normal, leading to hard edges between adjacent triangles.

Instead, you want to re-use previously created vertices. Two ways to approach this:

• As you generate each voxel's mesh, keep track of the indices of the vertices it uses. If a vertex you want to generate is on an edge shared with a neighbouring voxel that's already been generated, ask that voxel for the index to the existing vertex, instead of creating a copy.

or

• Each time you create a new vertex, stick it into a dictionary cache, using its position as a key, and its index in the vertices array as its value. When you're about to create a vertex, first look it up in the cache. If it exists, use the existing index instead of adding to the vertex array.

This should reduce the size of your vertices array, and make your normals smooth.

Maybe I can give you a little bit of light in your problem. First of all, the reason, recalculate normal works properly, you problem is in the triangles generation. You are creating each triangle one by one, so it's mean that two triangles placed together don't share any edge and the light is not interpolated between two triangles(this effect is use in low poly games). So the solution of your problem is create the triangles sharing the edges.

Cheers!

• You didn't said anything new, most of this is already in my question. I know why it happens, I want to know what would be a good way to solve it – Bálint Oct 30 '16 at 22:17