i use unity c#. i generate a mesh with marching cubes and want to remove duplicate vertices. i do sort them by distance to origin so i can merge nearby vertices. the distance of them to each other is important as otherwise holes in the mesh can emerge
Assistant
User
how does blender merge vertices by distance
Assistant
User
optimize
Assistant
When you generate a mesh using the Marching Cubes algorithm in Unity and want to remove duplicate vertices, ensuring that you don't introduce holes or artifacts in the mesh is crucial. Here is a step-by-step guide on how you can approach this problem in C# for Unity.
Steps to Remove Duplicate Vertices
Store Vertices and Triangles:
As you generate vertices and triangles, store them in appropriate data structures. Usually, you would have a list of Vector3 for vertices and a list of int for triangle indices referencing those vertices.
Use a Dictionary to Merge Nearby Vertices:
You can use a dictionary to map unique vertices to their indices. This way, as you iterate through your vertices, you can check if a similar vertex already exists and merge them accordingly.
Rebuild the Triangle Indices:
After merging vertices, you will need to update your triangle indices to reference the new set of unique vertices.
Sample Code
Here's a sample implementation of how you can remove duplicate vertices in Unity using C#:
csharp
using System.Collections.Generic;
using UnityEngine;
public class MeshOptimizer : MonoBehaviour
{
public MeshFilter meshFilter;
void Start()
{
Mesh mesh = meshFilter.mesh;
List<Vector3> oldVertices = new List<Vector3>(mesh.vertices);
List<int> oldTriangles = new List<int>(mesh.triangles);
// Optimize the mesh
OptimizeMesh(oldVertices, oldTriangles, out var newVertices, out var newTriangles);
// Update the mesh with optimized vertices and triangles
mesh.Clear();
mesh.SetVertices(newVertices);
mesh.SetTriangles(newTriangles, 0);
mesh.RecalculateNormals(); // Recalculate normals if needed
}
void OptimizeMesh(List<Vector3> vertices, List<int> triangles,
out List<Vector3> newVertices, out List<int> newTriangles)
{
Dictionary<Vector3, int> vertexDict = new Dictionary<Vector3, int>();
newVertices = new List<Vector3>();
newTriangles = new List<int>();
// Tolerance value for merging vertices
float tolerance = 0.0001f;
foreach (var vertex in vertices)
{
Vector3 uniqueVertex = RoundVector(vertex, tolerance);
if (!vertexDict.ContainsKey(uniqueVertex))
{
vertexDict[uniqueVertex] = newVertices.Count;
newVertices.Add(vertex);
}
}
foreach (var index in triangles)
{
Vector3 vertex = vertices[index];
Vector3 uniqueVertex = RoundVector(vertex, tolerance);
int uniqueIndex = vertexDict[uniqueVertex];
newTriangles.Add(uniqueIndex);
}
}
// Helper method to round vector to specified tolerance
Vector3 RoundVector(Vector3 v, float tolerance)
{
return new Vector3(
Mathf.Round(v.x / tolerance) * tolerance,
Mathf.Round(v.y / tolerance) * tolerance,
Mathf.Round(v.z / tolerance) * tolerance);
}
}
Explanation
Storing and Accessing Data:
The old vertices and triangles are stored.
A dictionary is used to keep track of unique vertices and their indices.
Rounding to Merge Vertices:
A RoundVector helper method rounds vertices to the nearest value defined by the tolerance. This method helps in deciding if vertices are "close enough" to be considered duplicates.
Building New Vertex and Triangle Lists:
As the vertices are iterated, they are rounded and checked against the dictionary.
If a unique vertex is found, it is added to the new list.
New triangle indices are built using the unique vertex indices.
Updating the Mesh:
Finally, the mesh is cleared and updated with the new vertices and triangles lists.
Recalculate normals if required.
Notes
Tolerance: Adjust the tolerance value according to your precision requirements. Too high a value may undesirably merge vertices that should remain separate, while too low a value might not remove enough duplicates.
Performance: This method is relatively straightforward but can be optimized further for large meshes.
Normals and Other Attributes: If your mesh has normals, UV coordinates, or other vertex attributes, you will need to handle those similarly while removing duplicate vertices.
Blender's approach to merging vertices by distance typically involves a "Remove Doubles" (or "Merge by Distance" in newer versions) operation. This operation merges vertices that fall within a specified distance of one another. While Blender's implementation is not directly exposed in its source code for easy replication, the basic principles can be mimicked in Unity using C#.
Here's a high-level overview of how Blender's merge by distance works, and how you can implement a similar feature in Unity:
Blender's Merge by Distance
Identify Close Vertices:
Analyze vertices and find those within a certain distance threshold.
Merge Vertices:
Replace each group of close vertices with their average position.
Update Mesh Topology:
Update the mesh indices to reflect the new vertex positions.
Implementing Merge by Distance in Unity
To achieve similar functionality in Unity, below is a more detailed implementation:
Cluster Vertices within Distance Threshold:
Group vertices that are closer than a specified threshold.
Average the Positions of Grouped Vertices:
Combine the vertices into a single vertex at the average position of the group.
Rebuild the Mesh:
Rebuild the vertex and triangle lists to use the new set of vertices without duplicates.
Implementation in Unity C#
Here's an implementation that mirrors Blender's merge by distance behavior:
csharp
using System.Collections.Generic;
using UnityEngine;
public class MeshOptimizer : MonoBehaviour
{
public MeshFilter meshFilter;
public float mergeDistance = 0.01f;
void Start()
{
Mesh mesh = meshFilter.mesh;
List<Vector3> oldVertices = new List<Vector3>(mesh.vertices);
List<int> oldTriangles = new List<int>(mesh.triangles);
// Optimize the mesh
OptimizeMesh(oldVertices, oldTriangles, out var newVertices, out var newTriangles);
// Update the mesh with optimized vertices and triangles
mesh.Clear();
mesh.SetVertices(newVertices);
mesh.SetTriangles(newTriangles, 0);
mesh.RecalculateNormals(); // Recalculate normals if needed
}
void OptimizeMesh(List<Vector3> vertices, List<int> triangles,
out List<Vector3> newVertices, out List<int> newTriangles)
{
newVertices = new List<Vector3>();
newTriangles = new List<int>();
Dictionary<int, int> vertexMap = new Dictionary<int, int>();
List<Vector3> mergedVertices = new List<Vector3>();
for (int i = 0; i < vertices.Count; i++)
{
bool merged = false;
Vector3 currentVertex = vertices[i];
for (int j = 0; j < mergedVertices.Count; j++)
{
if (Vector3.Distance(currentVertex, mergedVertices[j]) <= mergeDistance)
{
vertexMap[i] = j;
mergedVertices[j] = (mergedVertices[j] + currentVertex) / 2;
merged = true;
break;
}
}
if (!merged)
{
vertexMap[i] = mergedVertices.Count;
mergedVertices.Add(currentVertex);
}
}
newVertices = new List<Vector3>(mergedVertices);
foreach (int oldIndex in triangles)
{
newTriangles.Add(vertexMap[oldIndex]);
}
}
}
Explanation
Main Structure:
The OptimizeMesh function takes the original list of vertices and triangles and outputs a new set of merged vertices and updated triangle indices.
Dictionary for Vertex Mapping:
A dictionary is used to map old vertex indices to new (merged) vertex indices.
Merging Logic:
For each vertex in the original list, it checks against vertices already added to the merged list.
If a vertex is within the mergeDistance threshold of any vertex in the merged list, it merges them (by averaging their positions) and updates the mapping.
If no close vertex is found, it adds the vertex to the merged list as a new vertex.
Rebuilding Triangles:
The original triangle indices are remapped to the new vertices using the dictionary.
Recalculate Normals:
After updating the mesh vertices and triangles, normals are recalculated to ensure correct shading.
Conclusion
This approach effectively clusters vertices within a specified distance and merges them, similar to Blender's "Merge by Distance" functionality. Adjusting the mergeDistance allows control over the precision of the merging operation. Remember that for very complex meshes, more optimized spatial data structures (like spatial hashing or k-d trees) can be used to improve performance.
To further optimize the process of merging vertices by distance, especially for large meshes, we can incorporate more efficient spatial data structures, such as a spatial hash grid, which can substantially reduce the number of distance checks required.
Spatial Hash Grid Concept
A spatial hash grid divides the 3D space into a grid of cells. Each cell contains a list of vertices that fall within its boundaries. By only comparing vertices within the same cell and neighboring cells, we can significantly cut down unnecessary distance checks.
Optimized Implementation
Here’s a more optimized version using the spatial hash grid concept:
csharp
using System.Collections.Generic;
using UnityEngine;
public class MeshOptimizer : MonoBehaviour
{
public MeshFilter meshFilter;
public float mergeDistance = 0.01f;
void Start()
{
Mesh mesh = meshFilter.mesh;
List<Vector3> oldVertices = new List<Vector3>(mesh.vertices);
List<int> oldTriangles = new List<int>(mesh.triangles);
// Optimize the mesh
OptimizeMesh(oldVertices, oldTriangles, out var newVertices, out var newTriangles);
// Update the mesh with optimized vertices and triangles
mesh.Clear();
mesh.SetVertices(newVertices);
mesh.SetTriangles(newTriangles, 0);
mesh.RecalculateNormals(); // Recalculate normals if needed
}
void OptimizeMesh(List<Vector3> vertices, List<int> triangles,
out List<Vector3> newVertices, out List<int> newTriangles)
{
newVertices = new List<Vector3>();
newTriangles = new List<int>();
Dictionary<int, int> vertexMap = new Dictionary<int, int>();
Dictionary<Vector3Int, List<int>> spatialHash = new Dictionary<Vector3Int, List<int>>();
float cellSize = mergeDistance * 2; // Adjust cell size based on merge distance
for (int i = 0; i < vertices.Count; i++)
{
Vector3 currentVertex = vertices[i];
Vector3Int cell = GetCell(currentVertex, cellSize);
if (!spatialHash.ContainsKey(cell))
{
spatialHash[cell] = new List<int>();
}
bool merged = false;
foreach (int j in GetNearbyCells(cell, spatialHash, cellSize))
{
if (Vector3.Distance(currentVertex, vertices[j]) <= mergeDistance)
{
vertexMap[i] = vertexMap[j];
newVertices[vertexMap[j]] = (newVertices[vertexMap[j]] + currentVertex) / 2;
merged = true;
break;
}
}
if (!merged)
{
vertexMap[i] = newVertices.Count;
newVertices.Add(currentVertex);
spatialHash[cell].Add(i);
}
}
foreach (int oldIndex in triangles)
{
newTriangles.Add(vertexMap[oldIndex]);
}
}
Vector3Int GetCell(Vector3 point, float cellSize)
{
return new Vector3Int(
Mathf.FloorToInt(point.x / cellSize),
Mathf.FloorToInt(point.y / cellSize),
Mathf.FloorToInt(point.z / cellSize));
}
IEnumerable<int> GetNearbyCells(Vector3Int cell, Dictionary<Vector3Int, List<int>> spatialHash, float cellSize)
{
for (int x = cell.x - 1; x <= cell.x + 1; x++)
{
for (int y = cell.y - 1; y <= cell.y + 1; y++)
{
for (int z = cell.z - 1; z <= cell.z + 1; z++)
{
Vector3Int nearbyCell = new Vector3Int(x, y, z);
if (spatialHash.ContainsKey(nearbyCell))
{
foreach (int index in spatialHash[nearbyCell])
{
yield return index;
}
}
}
}
}
}
}
Explanation
Spatial Hashing:
A Dictionary<Vector3Int, List<int>> is used to store vertex indices in cells. The Vector3Int keys represent cell coordinates in the 3D grid.
Cell Calculation:
The GetCell method computes which cell a vertex belongs to, based on its position and the defined cellSize.
Nearby Cells:
The GetNearbyCells method retrieves indices of vertices in the same cell and adjacent cells to check for potential merging.
Merging Logic:
For each vertex, it checks nearby cells for close vertices using the spatial hash grid.
Vertices within the merge distance are averaged and mapped accordingly.
Rebuilding the Mesh:
The mesh is reconstructed with new, merged vertices and updated triangle indices.
Benefits of Optimization
Efficiency: Reduces the number of distance checks by limiting them to vertices within the same and adjacent cells.
Scalability: Handles large meshes more efficiently, as most unnecessary comparisons are avoided.
Conclusion
By adopting spatial hashing, we significantly enhance the performance of the merging process, making it suitable for larger meshes and more complex scenarios. This approach ensures that the final mesh is optimized with minimal performance overhead.