TKGP

Terrible mesh flattener

Oct 12th, 2020
864
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. private static Vector3 GetSurfaceNormal(FLVER.Vertex[] face)
  2. {
  3.     Vector3 v1 = face[2].Position - face[1].Position;
  4.     Vector3 v2 = face[1].Position - face[0].Position;
  5.     return Vector3.Normalize(Vector3.Cross(v1, v2));
  6. }
  7.  
  8. private static Vector4 MakeTangent(Vector3 normal)
  9. {
  10.     Vector3 t1 = Vector3.Cross(normal, Vector3.UnitX);
  11.     Vector3 t2 = Vector3.Cross(normal, Vector3.UnitY);
  12.     if (t1.Length() > t2.Length())
  13.         return new Vector4(t1, 1);
  14.     else
  15.         return new Vector4(t2, 1);
  16. }
  17.  
  18. private static void FlattenMesh(FLVER2.Mesh mesh)
  19. {
  20.     var faceGroups = new List<List<FLVER.Vertex[]>>();
  21.     foreach (var face in mesh.GetFaces())
  22.     {
  23.         Vector3 normal = GetSurfaceNormal(face);
  24.         var group = faceGroups.Find(fg => (normal - GetSurfaceNormal(fg[0])).Length() < 0.0001f); // Heuristic: my ass
  25.         if (group == null)
  26.         {
  27.             group = new List<FLVER.Vertex[]>();
  28.             faceGroups.Add(group);
  29.         }
  30.         group.Add(face);
  31.     }
  32.  
  33.     var newVertices = new List<FLVER.Vertex>();
  34.     var newIndices = new List<int>();
  35.     foreach (var group in faceGroups)
  36.     {
  37.         var indices = new Dictionary<FLVER.Vertex, int>();
  38.         int addVertex(FLVER.Vertex vert, Vector3 norm, Vector4 tang)
  39.         {
  40.             vert.Normal = norm;
  41.             for (int i = 0; i < vert.Tangents.Count; i++)
  42.                 vert.Tangents[i] = tang;
  43.  
  44.             if (!indices.ContainsKey(vert))
  45.             {
  46.                 indices[vert] = newVertices.Count;
  47.                 newVertices.Add(new FLVER.Vertex(vert));
  48.             }
  49.             return indices[vert];
  50.         }
  51.  
  52.         Vector3 normal = GetSurfaceNormal(group[0]);
  53.         Vector4 tangent = MakeTangent(normal);
  54.         foreach (var face in group)
  55.         {
  56.             newIndices.Add(addVertex(face[0], normal, tangent));
  57.             newIndices.Add(addVertex(face[1], normal, tangent));
  58.             newIndices.Add(addVertex(face[2], normal, tangent));
  59.         }
  60.     }
  61.  
  62.     mesh.Vertices = newVertices;
  63.     mesh.FaceSets.ForEach(fs => fs.Indices = newIndices);
  64. }
RAW Paste Data