From 7acbf22b4de7c3b5251fbb720bb5b575946622f6 Mon Sep 17 00:00:00 2001 From: mob-sakai Date: Wed, 28 Oct 2020 12:21:34 +0900 Subject: [PATCH] fix: fix the sorting algorithm --- Scripts/Utils.cs | 66 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/Scripts/Utils.cs b/Scripts/Utils.cs index a14f61e..e40d429 100644 --- a/Scripts/Utils.cs +++ b/Scripts/Utils.cs @@ -190,30 +190,52 @@ public static void SortForRendering(this List self, Transform tr self.Sort((a, b) => { var tr = transform; - var ra = a.GetComponent(); - var rb = b.GetComponent(); - - if (!Mathf.Approximately(ra.sortingFudge, rb.sortingFudge)) - return ra.sortingFudge < rb.sortingFudge ? 1 : -1; - - var pa = tr.InverseTransformPoint(a.transform.position).z; - var pb = tr.InverseTransformPoint(b.transform.position).z; - - if (!Mathf.Approximately(pa, pb)) - return pa < pb ? 1 : -1; - - var aQueue = ra.sharedMaterial.renderQueue; - var bQueue = rb.sharedMaterial.renderQueue; - if (aQueue != bQueue) - return aQueue < bQueue ? 1 : -1; + var aRenderer = a.GetComponent(); + var bRenderer = b.GetComponent(); + + // Render queue: ascending + var aMat = aRenderer.sharedMaterial; + var bMat = bRenderer.sharedMaterial; + if (aMat.renderQueue != bMat.renderQueue) + return aMat.renderQueue - bMat.renderQueue; + + // Sorting layer: ascending + if (aRenderer.sortingLayerID != bRenderer.sortingLayerID) + return aRenderer.sortingLayerID - bRenderer.sortingLayerID; + + // Sorting order: ascending + if (aRenderer.sortingOrder != bRenderer.sortingOrder) + return aRenderer.sortingOrder - bRenderer.sortingOrder; + + // Z position & sortingFudge: descending + var aTransform = a.transform; + var bTransform = b.transform; + var aPos = tr.InverseTransformPoint(aTransform.position).z+ aRenderer.sortingFudge; + var bPos = tr.InverseTransformPoint(bTransform.position).z+ bRenderer.sortingFudge; + if (!Mathf.Approximately(aPos, bPos)) + return (int)Mathf.Sign(bPos - aPos); + + // Material instance ID: match + if (aMat.GetInstanceID() == bMat.GetInstanceID()) + return 0; + + // Transform: ascending + return TransformCompare(aTransform, bTransform); + }); + } - var aHash = ra.sharedMaterial.GetHashCode(); - var bHash = rb.sharedMaterial.GetHashCode(); - if (aHash != bHash) - return aHash < bHash ? 1 : -1; + private static int TransformCompare(Transform a, Transform b) + { + while (true) + { + if (!a && !b) return 0; + if (!a) return -1; + if (!b) return 1; + if (a.parent == b.parent) return a.GetSiblingIndex() - b.GetSiblingIndex(); - return 0; - }); + a = a.parent; + b = b.parent; + } } public static long GetMaterialHash(this ParticleSystem self, bool trail)