Search Unity

Optimizing by having all geometry in world space so MVP transform becomes VP shared by all objects

Discussion in 'Shaders' started by Phong, May 9, 2017.

  1. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,085
    I have been experimenting with an optimization where all meshes are transformed into worldspace, meaning the position of all vertices are the same as their worldspace positions (MeshRenderers have transform p=0,0,0 r=0,0,0 s=1,1,1).

    For these meshes the Model matrix is the identity matrix so MVP becomes VP which only needs to be calculated once per frame instead of once per object. I calculate VP and write it to shader memory using

    Shader.SetGlobalMatrix("u_VP", myVPmatrix);

    I created a scene with 1200 cubes, disabled static and dynamic batching. Then I modified a simple shader so it uses the Uniform u_VP instead of UNITY_MATRIX_MVP. In the stats window I can see 1200 drawcalls. This should save Unity the effort of creating 1200 MVP matrices every frame.

    However I see no difference in rendering time. The scene takes 64 ms to render per frame on my Android phone whether I use the UNITY_MATRIX_MVP or the u_VP in the shader.

    Does anyone know if there is something that needs to be done (perhaps a pragma) to tell Unity not to create the MVP matrix per object (I presumed if it is not present in the shader code Unity won't generate it.)?

    Has anyone tried this optimization?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    This is already what static batching does, the UNITY_MATRIX_MVP is just the UNITY_MATRIX_VP for all staticly batched meshes as they are pre-transformed into world space. Otherwise Unity is still calculating the full MVP even if the mesh's transform is an identity matrix or the shader isn't using it.
     
    Last edited: May 9, 2017
  3. Phong

    Phong

    Joined:
    Apr 12, 2010
    Posts:
    2,085
    I hadn't thought of it that way before but it make sense. Interestingly I heard about this from a developer who used it in Unity 4 and said it was very effective. I am curious now what his setup was.