Search Unity

Question Best practice sharing Mesh data with c++ library

Discussion in 'Scripting' started by fortgreeneVR, Nov 24, 2020.

  1. fortgreeneVR

    fortgreeneVR

    Joined:
    Sep 5, 2018
    Posts:
    50
    I like to share Mesh data, vertices and triangles, with a general purpose c++ library and I'm wondering what the most memory efficient way of doing this is.
    The meshes will be built at run time in a c# script. I know how to share data made in a c# script with a c++ library, but I wonder if there is a way to avoid having an extra copy in the Mesh class of this data. It seems that all methods that set data on a Mesh in fact make a copy of it, including the newer SetVertexBufferData method.
    The app will use 2019.4 and run on a mobile Android system.
    Any insight will be appreciated.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    You can avoid duplicates generally at the cost of maintaining and operating an API that gets the data across the managed / unmanaged boundary as often as needed. For something like a mesh this is probably impractical.

    Have you even done back-of-envelope estimates of data size? It would have to be a MASSIVE mesh to really make a dent in memory consumption just by being duplicated.

    If you want to avoid duplication so that you don't have to update it in two places, see back to paragraph 1 above, but again, that has a performance cost.
     
  3. fortgreeneVR

    fortgreeneVR

    Joined:
    Sep 5, 2018
    Posts:
    50
    While looking into this I found this method I hadn't noticed before:
    https://docs.unity3d.com/ScriptReference/Mesh.UploadMeshData.html
    It can be used to free Unity's CPU side of the mesh data, effectively solving my problem: Unity has its GPU data and I can keep my original CPU c++ data.

    (one could argue that in my case data is still duplicated since on the Android device in question there is no dedicate main GPU memory, only a fast memory block for rendering tiles. So Unity's GPU data and my CPU data reside in the same memory! However openGL doesn't seem to allow continuous sharing of data, even it if is read only, but only supports mapping buffers to 'client' memory temporarily. Perhaps vulcan allows this on devices that share the same memory anyway??)
     
  4. fortgreeneVR

    fortgreeneVR

    Joined:
    Sep 5, 2018
    Posts:
    50
    I'm running into a bit of an issue using that 'UploadMeshData' method.
    To avoid memory fragmentation I pool the Unity Mesh objects and re-use them as needed.
    However, once UploadMeshData(true) is called, the mesh object can not be reset to its initial state.
    Calling Clear on it, does not reset it, the mesh stays unreadable. (In Unity 2019.4LTS)
    This seems to be a bug to me.