Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Showcase Faster bounds re-calculations (5x faster than Unity's implementation)

Discussion in 'Scripting' started by DevDunk, Jun 7, 2023.

  1. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,362
    I am working on a mesh deformation system and noticed the mesh.RecalculateBounds() is quite slow.
    A mesh with 40k triangles tool 0.26ms on the RecalculateBounds and my bursted job took 0.051ms, about 5 times faster. This can also run in the background (schedule in Update() and obtain data in LateUpdate()).

    Jobified code:
    Code (CSharp):
    1. [BurstCompile(FloatPrecision.Low, FloatMode.Fast)]
    2.     public struct CalculateBoundsJob : IJob
    3.     {
    4.         [ReadOnly] public NativeArray<float3> vertices;
    5.         [WriteOnly] public NativeReference<float3> pos, size;
    6.  
    7.         [SkipLocalsInit]
    8.         public void Execute()
    9.         {
    10.             float3 minPos = new float3(float.MaxValue, float.MaxValue, float.MaxValue);
    11.             float3 maxPos = new float3(float.MinValue, float.MinValue, float.MinValue);
    12.  
    13.             for (int i = 0; i < vertices.Length; i++)
    14.             {
    15.                 minPos = math.min(minPos, vertices[i]);
    16.                 maxPos = math.max(maxPos, vertices[i]);
    17.             }
    18.  
    19.             pos.Value = (maxPos + minPos) * 0.5f;
    20.             size.Value = maxPos - minPos;
    21.         }
    22.     }
     
    ADNCG, Ryiah and orionsyndrome like this.
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Part of me now wishes to tackle RecalculateNormals, I have a classic C# implementation of it lying around. It wasn't faster than Unity's (though it wasn't slower either), but it did expose some features to runtime, i.e. autosmoothing and the exact algorithm (which was important for flat low poly). Now with Burst it's doable in runtime.

    Can't find good references right now, maybe this one. Basically face- and angle-weighing.
     
  3. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,362
    That's an interesting one as well yeah, might pick it up end-juli if I have the time (if you aren't faster haha)