Search Unity

Question Bake vertex offset to mesh

Discussion in 'Shaders' started by ignarmezh, Dec 18, 2020.

  1. ignarmezh

    ignarmezh

    Joined:
    Mar 23, 2017
    Posts:
    56
    Hi!
    We are trying to bake vertex offset created by a displacement map in a shader into a mesh. So we could send a displaced mesh to a lightmapper that can take this displacement into account for light computation.

    We've started with some instructions provided in this topic: https://forum.unity.com/threads/bake-vertex-offset-shader-to-mesh.513123/

    We used an empty Ampllify Unlit shader which code we modified according to these steps:


    Then we created a following script:

    Code (CSharp):
    1.  void Start()
    2.     {
    3.         ComputeBuffer OutputVertexBuffer = new ComputeBuffer( gameObject.GetComponent<MeshFilter>().mesh.vertexCount, Marshal.SizeOf( typeof( Vector3 ) ) );
    4.         Graphics.SetRandomWriteTarget( 1, OutputVertexBuffer, true );
    5.         gameObject.GetComponent<Renderer>().material.SetBuffer( ????, OutputVertexBuffer );
    6.         Vector3[] vertices = gameObject.GetComponent<MeshFilter>().mesh.vertices;
    7.         OutputVertexBuffer.GetData( vertices );
    8.         gameObject.GetComponent<MeshFilter>().mesh.vertices = vertices;
    9.         var savePath = "Assets/NEWMESH.asset";
    10.         AssetDatabase.CreateAsset( gameObject.GetComponent<MeshFilter>().mesh, savePath );
    11.     }
    Our main issue is that we can't figure out what should we use as an ID in SetBuffer function.

    If we use 0 or 1 then we do get a new mesh but with polygons collapsed in a random manner, though this code is supposed to keep it intact (because we don't displace anything in the shader yet) and just create a copy.