Skip to content

Instantly share code, notes, and snippets.

@hybridherbst
Last active August 19, 2019 13:31
Show Gist options
  • Save hybridherbst/4084474d155de2dfb8843ca83e9512f9 to your computer and use it in GitHub Desktop.
Save hybridherbst/4084474d155de2dfb8843ca83e9512f9 to your computer and use it in GitHub Desktop.
Quill Fixup. Make sure to adjust the name filter in FixupPostprocessor for your pipeline BEFORE you drop these into an Editor folder.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
namespace pfc.WeirdQuillFixup
{
public static class Fixup
{
public static void FixMeshInPlace(Mesh mesh)
{
var vs = mesh.vertices;
var cs = mesh.colors;
var ind = mesh.GetTriangles(0);
var avg = Vector3.zero;
var min = Mathf.Infinity;
var max = Mathf.NegativeInfinity;
var threshold = 1f;
var toDiscard = 0;
min = Mathf.Infinity;
max = Mathf.NegativeInfinity;
List<int> trianglesToDiscard = new List<int>();
// find broken triangles
for (int i = 0; i < ind.Length; i += 3)
{
if (
CheckEdge(vs[ind[i + 0]], vs[ind[i + 1]], ref min, ref max, threshold) ||
CheckEdge(vs[ind[i + 1]], vs[ind[i + 2]], ref min, ref max, threshold) ||
CheckEdge(vs[ind[i + 2]], vs[ind[i + 0]], ref min, ref max, threshold))
{
trianglesToDiscard.Add(i + 0);
trianglesToDiscard.Add(i + 1);
trianglesToDiscard.Add(i + 2);
}
}
avg /= vs.Length;
toDiscard += trianglesToDiscard.Count;
var copy = ind.ToList();
for (int j = trianglesToDiscard.Count - 1; j >= 0; j--)
{
copy.RemoveAt(trianglesToDiscard[j]);
}
mesh.SetTriangles(copy, 0);
mesh.Optimize();
mesh.RecalculateBounds();
}
public static bool CheckEdge(Vector3 a, Vector3 b, ref float min, ref float max, float threshold)
{
if (a.sqrMagnitude == 0 || b.sqrMagnitude == 0) return true;
return false;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace pfc.WeirdQuillFixup
{
// Adds a mesh collider to each game object that contains collider in its name
public class Example : AssetPostprocessor
{
void OnPostprocessModel(GameObject g)
{
// Make sure you have a clear naming scheme for your Quill files and detect it here.
// Otherwise, other meshes in your project will get "fixed" and most likely become corrupt!
if (!g.name.Contains("Quill")) return;
Debug.Log("Postprocessing " + g.name);
var mfs = g.GetComponentsInChildren<MeshFilter>();
foreach (var mf in mfs)
Fixup.FixMeshInPlace(mf.sharedMesh);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment