Search Unity

NativeArray<float> for SetHeights()

Discussion in 'World Building' started by crysicle, Aug 22, 2019.

  1. crysicle

    crysicle

    Joined:
    Oct 24, 2018
    Posts:
    95
    Hello, i was wondering if SetHeights() is going to have similar API changes as the Mesh in 2019.3, which received Mesh.SetVertices(NativeArray<T> inVertices) method to efficiently assign new vertices. This is something which could be very useful for terrain as well to assign new heightmap data as both the job system and async readback requires the use of NativeArrays.

    Currently i'm working on a system which dynamicly deforms millions of heightmaps and am trying to synchronize collisions in areas where they would be necessary. I used a mesh collider for collisions first, but after hitting Physix rebaking limitations, decided to give the terrain collider a try. After some test, i found that if you split the terrain into smaller chunks of 33x33 and then check the amount of time it takes to synchronize collision data versus a mesh with 33x33 vertices, the terrain wins in performance by a factor of 7-8. However, due to the extra memory copy to float[,], that factor dips to about 3-4.

    Here's the data:
    Mesh vertice assignment: 1000 verts - 0,00ms - 0,01ms
    Mesh Collider rebaking: 1000 verts - 0.69ms - 1.73ms

    Copy NativeArray<float> to float[,] : 1,000 heightmaps - 0.15ms - 0.2ms
    SetHeights() on terrainData : 1,000 heightmaps - 0.09ms - 0.18ms

    Total:
    Mesh collider lag per 1000 verts = 0.69ms - 1.74ms
    Terrain collider lag per 1000 heightmaps = 0.24 - 0.38ms

    CPU used: i7-5820k

    If the method was introduced, it'd easily double the amount of heightmaps you could update.
     
  2. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    You can do memcpy of native to managed and visa versa using UnsafeUtility.
     
    crysicle likes this.
  3. crysicle

    crysicle

    Joined:
    Oct 24, 2018
    Posts:
    95
    Thanks, never heard of it.
     
  4. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    This is the basics of using to copy native to managed.

    Code (csharp):
    1.  
    2. void* managedBuffer = UnsafeUtility.AddressOf(ref array[0]);
    3. void* nativeBuffer = nativeArray.GetUnsafePtr();
    4. UnsafeUtility.MemCpy(managedBuffer, nativeBuffer, length);
    5.